1 use crate::stable_hasher::{HashStable, StableHasher};
2 use std::borrow::Borrow;
3 use std::cmp::Ordering;
4 use std::iter::FromIterator;
6 use std::ops::{Bound, Index, IndexMut, RangeBounds};
10 pub use index_map::SortedIndexMultiMap;
12 /// `SortedMap` is a data structure with similar characteristics as BTreeMap but
13 /// slightly different trade-offs: lookup, insertion, and removal are *O*(log(*n*))
14 /// and elements can be iterated in order cheaply.
16 /// `SortedMap` can be faster than a `BTreeMap` for small sizes (<50) since it
17 /// stores data in a more compact way. It also supports accessing contiguous
18 /// ranges of elements as a slice, and slices of already sorted elements can be
19 /// inserted efficiently.
20 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)]
21 pub struct SortedMap<K, V> {
25 impl<K, V> Default for SortedMap<K, V> {
27 fn default() -> SortedMap<K, V> {
28 SortedMap { data: Vec::new() }
32 impl<K, V> SortedMap<K, V> {
34 pub const fn new() -> SortedMap<K, V> {
35 SortedMap { data: Vec::new() }
39 impl<K: Ord, V> SortedMap<K, V> {
40 /// Construct a `SortedMap` from a presorted set of elements. This is faster
41 /// than creating an empty map and then inserting the elements individually.
43 /// It is up to the caller to make sure that the elements are sorted by key
44 /// and that there are no duplicates.
46 pub fn from_presorted_elements(elements: Vec<(K, V)>) -> SortedMap<K, V> {
47 debug_assert!(elements.array_windows().all(|[fst, snd]| fst.0 < snd.0));
49 SortedMap { data: elements }
53 pub fn insert(&mut self, key: K, mut value: V) -> Option<V> {
54 match self.lookup_index_for(&key) {
56 let slot = unsafe { self.data.get_unchecked_mut(index) };
57 mem::swap(&mut slot.1, &mut value);
61 self.data.insert(index, (key, value));
68 pub fn remove(&mut self, key: &K) -> Option<V> {
69 match self.lookup_index_for(key) {
70 Ok(index) => Some(self.data.remove(index).1),
76 pub fn get<Q>(&self, key: &Q) -> Option<&V>
81 match self.lookup_index_for(key) {
82 Ok(index) => unsafe { Some(&self.data.get_unchecked(index).1) },
88 pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
93 match self.lookup_index_for(key) {
94 Ok(index) => unsafe { Some(&mut self.data.get_unchecked_mut(index).1) },
99 /// Gets a mutable reference to the value in the entry, or insert a new one.
101 pub fn get_mut_or_insert_default(&mut self, key: K) -> &mut V
106 let index = match self.lookup_index_for(&key) {
109 self.data.insert(index, (key, V::default()));
113 unsafe { &mut self.data.get_unchecked_mut(index).1 }
117 pub fn clear(&mut self) {
121 /// Iterate over elements, sorted by key
123 pub fn iter(&self) -> std::slice::Iter<'_, (K, V)> {
127 /// Iterate over the keys, sorted
129 pub fn keys(&self) -> impl Iterator<Item = &K> + ExactSizeIterator + DoubleEndedIterator {
130 self.data.iter().map(|&(ref k, _)| k)
133 /// Iterate over values, sorted by key
135 pub fn values(&self) -> impl Iterator<Item = &V> + ExactSizeIterator + DoubleEndedIterator {
136 self.data.iter().map(|&(_, ref v)| v)
140 pub fn len(&self) -> usize {
145 pub fn is_empty(&self) -> bool {
150 pub fn range<R>(&self, range: R) -> &[(K, V)]
154 let (start, end) = self.range_slice_indices(range);
155 &self.data[start..end]
159 pub fn remove_range<R>(&mut self, range: R)
163 let (start, end) = self.range_slice_indices(range);
164 self.data.splice(start..end, std::iter::empty());
167 /// Mutate all keys with the given function `f`. This mutation must not
168 /// change the sort-order of keys.
170 pub fn offset_keys<F>(&mut self, f: F)
174 self.data.iter_mut().map(|&mut (ref mut k, _)| k).for_each(f);
177 /// Inserts a presorted range of elements into the map. If the range can be
178 /// inserted as a whole in between to existing elements of the map, this
179 /// will be faster than inserting the elements individually.
181 /// It is up to the caller to make sure that the elements are sorted by key
182 /// and that there are no duplicates.
184 pub fn insert_presorted(&mut self, elements: Vec<(K, V)>) {
185 if elements.is_empty() {
189 debug_assert!(elements.array_windows().all(|[fst, snd]| fst.0 < snd.0));
191 let start_index = self.lookup_index_for(&elements[0].0);
193 let elements = match start_index {
195 let mut elements = elements.into_iter();
196 self.data[index] = elements.next().unwrap();
200 if index == self.data.len() || elements.last().unwrap().0 < self.data[index].0 {
201 // We can copy the whole range without having to mix with
202 // existing elements.
203 self.data.splice(index..index, elements.into_iter());
207 let mut elements = elements.into_iter();
208 self.data.insert(index, elements.next().unwrap());
214 for (k, v) in elements {
219 /// Looks up the key in `self.data` via `slice::binary_search()`.
221 fn lookup_index_for<Q>(&self, key: &Q) -> Result<usize, usize>
226 self.data.binary_search_by(|&(ref x, _)| x.borrow().cmp(key))
230 fn range_slice_indices<R>(&self, range: R) -> (usize, usize)
234 let start = match range.start_bound() {
235 Bound::Included(ref k) => match self.lookup_index_for(k) {
236 Ok(index) | Err(index) => index,
238 Bound::Excluded(ref k) => match self.lookup_index_for(k) {
239 Ok(index) => index + 1,
242 Bound::Unbounded => 0,
245 let end = match range.end_bound() {
246 Bound::Included(ref k) => match self.lookup_index_for(k) {
247 Ok(index) => index + 1,
250 Bound::Excluded(ref k) => match self.lookup_index_for(k) {
251 Ok(index) | Err(index) => index,
253 Bound::Unbounded => self.data.len(),
260 pub fn contains_key<Q>(&self, key: &Q) -> bool
265 self.get(key).is_some()
269 impl<K: Ord, V> IntoIterator for SortedMap<K, V> {
271 type IntoIter = std::vec::IntoIter<(K, V)>;
273 fn into_iter(self) -> Self::IntoIter {
274 self.data.into_iter()
278 impl<'a, K, Q, V> Index<&'a Q> for SortedMap<K, V>
285 fn index(&self, key: &Q) -> &Self::Output {
286 self.get(key).expect("no entry found for key")
290 impl<'a, K, Q, V> IndexMut<&'a Q> for SortedMap<K, V>
295 fn index_mut(&mut self, key: &Q) -> &mut Self::Output {
296 self.get_mut(key).expect("no entry found for key")
300 impl<K: Ord, V> FromIterator<(K, V)> for SortedMap<K, V> {
301 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
302 let mut data: Vec<(K, V)> = iter.into_iter().collect();
304 data.sort_unstable_by(|&(ref k1, _), &(ref k2, _)| k1.cmp(k2));
305 data.dedup_by(|&mut (ref k1, _), &mut (ref k2, _)| k1.cmp(k2) == Ordering::Equal);
311 impl<K: HashStable<CTX>, V: HashStable<CTX>, CTX> HashStable<CTX> for SortedMap<K, V> {
313 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
314 self.data.hash_stable(ctx, hasher);