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) },
100 pub fn clear(&mut self) {
104 /// Iterate over elements, sorted by key
106 pub fn iter(&self) -> std::slice::Iter<'_, (K, V)> {
110 /// Iterate over the keys, sorted
112 pub fn keys(&self) -> impl Iterator<Item = &K> + ExactSizeIterator + DoubleEndedIterator {
113 self.data.iter().map(|&(ref k, _)| k)
116 /// Iterate over values, sorted by key
118 pub fn values(&self) -> impl Iterator<Item = &V> + ExactSizeIterator + DoubleEndedIterator {
119 self.data.iter().map(|&(_, ref v)| v)
123 pub fn len(&self) -> usize {
128 pub fn is_empty(&self) -> bool {
133 pub fn range<R>(&self, range: R) -> &[(K, V)]
137 let (start, end) = self.range_slice_indices(range);
138 &self.data[start..end]
142 pub fn remove_range<R>(&mut self, range: R)
146 let (start, end) = self.range_slice_indices(range);
147 self.data.splice(start..end, std::iter::empty());
150 /// Mutate all keys with the given function `f`. This mutation must not
151 /// change the sort-order of keys.
153 pub fn offset_keys<F>(&mut self, f: F)
157 self.data.iter_mut().map(|&mut (ref mut k, _)| k).for_each(f);
160 /// Inserts a presorted range of elements into the map. If the range can be
161 /// inserted as a whole in between to existing elements of the map, this
162 /// will be faster than inserting the elements individually.
164 /// It is up to the caller to make sure that the elements are sorted by key
165 /// and that there are no duplicates.
167 pub fn insert_presorted(&mut self, elements: Vec<(K, V)>) {
168 if elements.is_empty() {
172 debug_assert!(elements.array_windows().all(|[fst, snd]| fst.0 < snd.0));
174 let start_index = self.lookup_index_for(&elements[0].0);
176 let elements = match start_index {
178 let mut elements = elements.into_iter();
179 self.data[index] = elements.next().unwrap();
183 if index == self.data.len() || elements.last().unwrap().0 < self.data[index].0 {
184 // We can copy the whole range without having to mix with
185 // existing elements.
186 self.data.splice(index..index, elements.into_iter());
190 let mut elements = elements.into_iter();
191 self.data.insert(index, elements.next().unwrap());
197 for (k, v) in elements {
202 /// Looks up the key in `self.data` via `slice::binary_search()`.
204 fn lookup_index_for<Q>(&self, key: &Q) -> Result<usize, usize>
209 self.data.binary_search_by(|&(ref x, _)| x.borrow().cmp(key))
213 fn range_slice_indices<R>(&self, range: R) -> (usize, usize)
217 let start = match range.start_bound() {
218 Bound::Included(ref k) => match self.lookup_index_for(k) {
219 Ok(index) | Err(index) => index,
221 Bound::Excluded(ref k) => match self.lookup_index_for(k) {
222 Ok(index) => index + 1,
225 Bound::Unbounded => 0,
228 let end = match range.end_bound() {
229 Bound::Included(ref k) => match self.lookup_index_for(k) {
230 Ok(index) => index + 1,
233 Bound::Excluded(ref k) => match self.lookup_index_for(k) {
234 Ok(index) | Err(index) => index,
236 Bound::Unbounded => self.data.len(),
243 pub fn contains_key<Q>(&self, key: &Q) -> bool
248 self.get(key).is_some()
252 impl<K: Ord, V> IntoIterator for SortedMap<K, V> {
254 type IntoIter = std::vec::IntoIter<(K, V)>;
256 fn into_iter(self) -> Self::IntoIter {
257 self.data.into_iter()
261 impl<'a, K, Q, V> Index<&'a Q> for SortedMap<K, V>
268 fn index(&self, key: &Q) -> &Self::Output {
269 self.get(key).expect("no entry found for key")
273 impl<'a, K, Q, V> IndexMut<&'a Q> for SortedMap<K, V>
278 fn index_mut(&mut self, key: &Q) -> &mut Self::Output {
279 self.get_mut(key).expect("no entry found for key")
283 impl<K: Ord, V> FromIterator<(K, V)> for SortedMap<K, V> {
284 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
285 let mut data: Vec<(K, V)> = iter.into_iter().collect();
287 data.sort_unstable_by(|&(ref k1, _), &(ref k2, _)| k1.cmp(k2));
288 data.dedup_by(|&mut (ref k1, _), &mut (ref k2, _)| k1.cmp(k2) == Ordering::Equal);
294 impl<K: HashStable<CTX>, V: HashStable<CTX>, CTX> HashStable<CTX> for SortedMap<K, V> {
296 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
297 self.data.hash_stable(ctx, hasher);