1 use std::borrow::Borrow;
2 use std::cmp::Ordering;
3 use std::iter::FromIterator;
5 use std::ops::{Bound, Index, IndexMut, RangeBounds};
7 /// `SortedMap` is a data structure with similar characteristics as BTreeMap but
8 /// slightly different trade-offs: lookup, insertion, and removal are O(log(N))
9 /// and elements can be iterated in order cheaply.
11 /// `SortedMap` can be faster than a `BTreeMap` for small sizes (<50) since it
12 /// stores data in a more compact way. It also supports accessing contiguous
13 /// ranges of elements as a slice, and slices of already sorted elements can be
14 /// inserted efficiently.
27 pub struct SortedMap<K: Ord, V> {
31 impl<K: Ord, V> SortedMap<K, V> {
33 pub fn new() -> SortedMap<K, V> {
34 SortedMap { data: vec![] }
37 /// Construct a `SortedMap` from a presorted set of elements. This is faster
38 /// than creating an empty map and then inserting the elements individually.
40 /// It is up to the caller to make sure that the elements are sorted by key
41 /// and that there are no duplicates.
43 pub fn from_presorted_elements(elements: Vec<(K, V)>) -> SortedMap<K, V> {
44 debug_assert!(elements.windows(2).all(|w| w[0].0 < w[1].0));
46 SortedMap { data: elements }
50 pub fn insert(&mut self, key: K, mut value: V) -> Option<V> {
51 match self.lookup_index_for(&key) {
53 let slot = unsafe { self.data.get_unchecked_mut(index) };
54 mem::swap(&mut slot.1, &mut value);
58 self.data.insert(index, (key, value));
65 pub fn remove(&mut self, key: &K) -> Option<V> {
66 match self.lookup_index_for(key) {
67 Ok(index) => Some(self.data.remove(index).1),
73 pub fn get<Q>(&self, key: &Q) -> Option<&V>
78 match self.lookup_index_for(key) {
79 Ok(index) => unsafe { Some(&self.data.get_unchecked(index).1) },
85 pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
90 match self.lookup_index_for(key) {
91 Ok(index) => unsafe { Some(&mut self.data.get_unchecked_mut(index).1) },
97 pub fn clear(&mut self) {
101 /// Iterate over elements, sorted by key
103 pub fn iter(&self) -> ::std::slice::Iter<'_, (K, V)> {
107 /// Iterate over the keys, sorted
109 pub fn keys(&self) -> impl Iterator<Item = &K> + ExactSizeIterator {
110 self.data.iter().map(|&(ref k, _)| k)
113 /// Iterate over values, sorted by key
115 pub fn values(&self) -> impl Iterator<Item = &V> + ExactSizeIterator {
116 self.data.iter().map(|&(_, ref v)| v)
120 pub fn len(&self) -> usize {
125 pub fn is_empty(&self) -> bool {
130 pub fn range<R>(&self, range: R) -> &[(K, V)]
134 let (start, end) = self.range_slice_indices(range);
135 &self.data[start..end]
139 pub fn remove_range<R>(&mut self, range: R)
143 let (start, end) = self.range_slice_indices(range);
144 self.data.splice(start..end, ::std::iter::empty());
147 /// Mutate all keys with the given function `f`. This mutation must not
148 /// change the sort-order of keys.
150 pub fn offset_keys<F>(&mut self, f: F)
154 self.data.iter_mut().map(|&mut (ref mut k, _)| k).for_each(f);
157 /// Inserts a presorted range of elements into the map. If the range can be
158 /// inserted as a whole in between to existing elements of the map, this
159 /// will be faster than inserting the elements individually.
161 /// It is up to the caller to make sure that the elements are sorted by key
162 /// and that there are no duplicates.
164 pub fn insert_presorted(&mut self, mut elements: Vec<(K, V)>) {
165 if elements.is_empty() {
169 debug_assert!(elements.windows(2).all(|w| w[0].0 < w[1].0));
171 let start_index = self.lookup_index_for(&elements[0].0);
173 let drain = match start_index {
175 let mut drain = elements.drain(..);
176 self.data[index] = drain.next().unwrap();
180 if index == self.data.len() || elements.last().unwrap().0 < self.data[index].0 {
181 // We can copy the whole range without having to mix with
182 // existing elements.
183 self.data.splice(index..index, elements.drain(..));
187 let mut drain = elements.drain(..);
188 self.data.insert(index, drain.next().unwrap());
194 for (k, v) in drain {
199 /// Looks up the key in `self.data` via `slice::binary_search()`.
201 fn lookup_index_for<Q>(&self, key: &Q) -> Result<usize, usize>
206 self.data.binary_search_by(|&(ref x, _)| x.borrow().cmp(key))
210 fn range_slice_indices<R>(&self, range: R) -> (usize, usize)
214 let start = match range.start_bound() {
215 Bound::Included(ref k) => match self.lookup_index_for(k) {
216 Ok(index) | Err(index) => index,
218 Bound::Excluded(ref k) => match self.lookup_index_for(k) {
219 Ok(index) => index + 1,
222 Bound::Unbounded => 0,
225 let end = match range.end_bound() {
226 Bound::Included(ref k) => match self.lookup_index_for(k) {
227 Ok(index) => index + 1,
230 Bound::Excluded(ref k) => match self.lookup_index_for(k) {
231 Ok(index) | Err(index) => index,
233 Bound::Unbounded => self.data.len(),
240 pub fn contains_key<Q>(&self, key: &Q) -> bool
245 self.get(key).is_some()
249 impl<K: Ord, V> IntoIterator for SortedMap<K, V> {
251 type IntoIter = ::std::vec::IntoIter<(K, V)>;
253 fn into_iter(self) -> Self::IntoIter {
254 self.data.into_iter()
258 impl<'a, K, Q, V> Index<&'a Q> for SortedMap<K, V>
265 fn index(&self, key: &Q) -> &Self::Output {
266 self.get(key).expect("no entry found for key")
270 impl<'a, K, Q, V> IndexMut<&'a Q> for SortedMap<K, V>
275 fn index_mut(&mut self, key: &Q) -> &mut Self::Output {
276 self.get_mut(key).expect("no entry found for key")
280 impl<K: Ord, V> FromIterator<(K, V)> for SortedMap<K, V> {
281 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
282 let mut data: Vec<(K, V)> = iter.into_iter().collect();
284 data.sort_unstable_by(|&(ref k1, _), &(ref k2, _)| k1.cmp(k2));
285 data.dedup_by(|&mut (ref k1, _), &mut (ref k2, _)| k1.cmp(k2) == Ordering::Equal);