1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use std::borrow::Borrow;
12 use std::cmp::Ordering;
13 use std::convert::From;
15 use std::ops::{RangeBounds, Bound, Index, IndexMut};
17 /// `SortedMap` is a data structure with similar characteristics as BTreeMap but
18 /// slightly different trade-offs: lookup, inseration, and removal are O(log(N))
19 /// and elements can be iterated in order cheaply.
21 /// `SortedMap` can be faster than a `BTreeMap` for small sizes (<50) since it
22 /// stores data in a more compact way. It also supports accessing contiguous
23 /// ranges of elements as a slice, and slices of already sorted elements can be
24 /// inserted efficiently.
25 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug, RustcEncodable,
27 pub struct SortedMap<K: Ord, V> {
31 impl<K: Ord, V> SortedMap<K, V> {
34 pub fn new() -> 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>
48 debug_assert!(elements.windows(2).all(|w| w[0].0 < w[1].0));
56 pub fn insert(&mut self, key: K, mut value: V) -> Option<V> {
57 match self.lookup_index_for(&key) {
60 self.data.get_unchecked_mut(index)
62 mem::swap(&mut slot.1, &mut value);
66 self.data.insert(index, (key, value));
73 pub fn remove(&mut self, key: &K) -> Option<V> {
74 match self.lookup_index_for(key) {
76 Some(self.data.remove(index).1)
85 pub fn get(&self, key: &K) -> Option<&V> {
86 match self.lookup_index_for(key) {
89 Some(&self.data.get_unchecked(index).1)
99 pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
100 match self.lookup_index_for(key) {
103 Some(&mut self.data.get_unchecked_mut(index).1)
113 pub fn clear(&mut self) {
117 /// Iterate over elements, sorted by key
119 pub fn iter(&self) -> ::std::slice::Iter<(K, V)> {
123 /// Iterate over the keys, sorted
125 pub fn keys(&self) -> impl Iterator<Item=&K> + ExactSizeIterator {
126 self.data.iter().map(|&(ref k, _)| k)
129 /// Iterate over values, sorted by key
131 pub fn values(&self) -> impl Iterator<Item=&V> + ExactSizeIterator {
132 self.data.iter().map(|&(_, ref v)| v)
136 pub fn len(&self) -> usize {
141 pub fn range<R>(&self, range: R) -> &[(K, V)]
142 where R: RangeBounds<K>
144 let (start, end) = self.range_slice_indices(range);
145 (&self.data[start .. end])
149 pub fn remove_range<R>(&mut self, range: R)
150 where R: RangeBounds<K>
152 let (start, end) = self.range_slice_indices(range);
153 self.data.splice(start .. end, ::std::iter::empty());
156 /// Mutate all keys with the given function `f`. This mutation must not
157 /// change the sort-order of keys.
159 pub fn offset_keys<F>(&mut self, f: F)
162 self.data.iter_mut().map(|&mut (ref mut k, _)| k).for_each(f);
165 /// Inserts a presorted range of elements into the map. If the range can be
166 /// inserted as a whole in between to existing elements of the map, this
167 /// will be faster than inserting the elements individually.
169 /// It is up to the caller to make sure that the elements are sorted by key
170 /// and that there are no duplicates.
172 pub fn insert_presorted(&mut self, mut elements: Vec<(K, V)>) {
173 if elements.is_empty() {
177 debug_assert!(elements.windows(2).all(|w| w[0].0 < w[1].0));
179 let start_index = self.lookup_index_for(&elements[0].0);
181 let drain = match start_index {
183 let mut drain = elements.drain(..);
184 self.data[index] = drain.next().unwrap();
188 if index == self.data.len() ||
189 elements.last().unwrap().0 < self.data[index].0 {
190 // We can copy the whole range without having to mix with
191 // existing elements.
192 self.data.splice(index .. index, elements.drain(..));
196 let mut drain = elements.drain(..);
197 self.data.insert(index, drain.next().unwrap());
203 for (k, v) in drain {
208 /// Looks up the key in `self.data` via `slice::binary_search()`.
210 fn lookup_index_for(&self, key: &K) -> Result<usize, usize> {
211 self.data.binary_search_by(|&(ref x, _)| x.cmp(key))
215 fn range_slice_indices<R>(&self, range: R) -> (usize, usize)
216 where R: RangeBounds<K>
218 let start = match range.start_bound() {
219 Bound::Included(ref k) => {
220 match self.lookup_index_for(k) {
221 Ok(index) | Err(index) => index
224 Bound::Excluded(ref k) => {
225 match self.lookup_index_for(k) {
226 Ok(index) => index + 1,
230 Bound::Unbounded => 0,
233 let end = match range.end_bound() {
234 Bound::Included(ref k) => {
235 match self.lookup_index_for(k) {
236 Ok(index) => index + 1,
240 Bound::Excluded(ref k) => {
241 match self.lookup_index_for(k) {
242 Ok(index) | Err(index) => index,
245 Bound::Unbounded => self.data.len(),
252 impl<K: Ord, V> IntoIterator for SortedMap<K, V> {
254 type IntoIter = ::std::vec::IntoIter<(K, V)>;
255 fn into_iter(self) -> Self::IntoIter {
256 self.data.into_iter()
260 impl<K: Ord, V, Q: Borrow<K>> Index<Q> for SortedMap<K, V> {
262 fn index(&self, index: Q) -> &Self::Output {
263 let k: &K = index.borrow();
268 impl<K: Ord, V, Q: Borrow<K>> IndexMut<Q> for SortedMap<K, V> {
269 fn index_mut(&mut self, index: Q) -> &mut Self::Output {
270 let k: &K = index.borrow();
271 self.get_mut(k).unwrap()
275 impl<K: Ord, V, I: Iterator<Item=(K, V)>> From<I> for SortedMap<K, V> {
276 fn from(data: I) -> Self {
277 let mut data: Vec<(K, V)> = data.collect();
278 data.sort_unstable_by(|&(ref k1, _), &(ref k2, _)| k1.cmp(k2));
279 data.dedup_by(|&mut (ref k1, _), &mut (ref k2, _)| {
280 k1.cmp(k2) == Ordering::Equal
290 use super::SortedMap;
293 fn test_insert_and_iter() {
294 let mut map = SortedMap::new();
295 let mut expected = Vec::new();
298 assert_eq!(map.iter().cloned().collect::<Vec<_>>(), expected);
300 let x = 1000 - x * 2;
302 expected.insert(0, (x, x));
307 fn test_get_and_index() {
308 let mut map = SortedMap::new();
309 let mut expected = Vec::new();
319 for mut x in expected {
321 assert_eq!(map.get(&x), Some(&x));
322 assert_eq!(map.get_mut(&x), Some(&mut x));
323 assert_eq!(map[&x], x);
324 assert_eq!(&mut map[&x], &mut x);
326 assert_eq!(map.get(&x), None);
327 assert_eq!(map.get_mut(&x), None);
334 let mut map = SortedMap::new();
340 let keys = |s: &[(_, _)]| {
341 s.into_iter().map(|e| e.0).collect::<Vec<u32>>()
344 for start in 0 .. 11 {
350 let mut expected = vec![1, 3, 6, 9];
351 expected.retain(|&x| x >= start && x < end);
353 assert_eq!(keys(map.range(start..end)), expected, "range = {}..{}", start, end);
360 fn test_offset_keys() {
361 let mut map = SortedMap::new();
366 map.offset_keys(|k| *k += 1);
368 let mut expected = SortedMap::new();
369 expected.insert(2, 1);
370 expected.insert(4, 3);
371 expected.insert(7, 6);
373 assert_eq!(map, expected);
376 fn keys(s: SortedMap<u32, u32>) -> Vec<u32> {
377 s.into_iter().map(|(k, _)| k).collect::<Vec<u32>>()
380 fn elements(s: SortedMap<u32, u32>) -> Vec<(u32, u32)> {
381 s.into_iter().collect::<Vec<(u32, u32)>>()
385 fn test_remove_range() {
386 let mut map = SortedMap::new();
392 for start in 0 .. 11 {
398 let mut expected = vec![1, 3, 6, 9];
399 expected.retain(|&x| x < start || x >= end);
401 let mut map = map.clone();
402 map.remove_range(start .. end);
404 assert_eq!(keys(map), expected, "range = {}..{}", start, end);
411 let mut map = SortedMap::new();
412 let mut expected = Vec::new();
416 expected.push((x, x));
420 let mut map = map.clone();
421 let mut expected = expected.clone();
423 assert_eq!(map.remove(&x), Some(x));
424 expected.remove(x as usize);
426 assert_eq!(map.iter().cloned().collect::<Vec<_>>(), expected);
431 fn test_insert_presorted_non_overlapping() {
432 let mut map = SortedMap::new();
436 map.insert_presorted(vec![(3, 0), (7, 0)]);
438 let expected = vec![2, 3, 7, 8];
439 assert_eq!(keys(map), expected);
443 fn test_insert_presorted_first_elem_equal() {
444 let mut map = SortedMap::new();
448 map.insert_presorted(vec![(2, 0), (7, 7)]);
450 let expected = vec![(2, 0), (7, 7), (8, 8)];
451 assert_eq!(elements(map), expected);
455 fn test_insert_presorted_last_elem_equal() {
456 let mut map = SortedMap::new();
460 map.insert_presorted(vec![(3, 3), (8, 0)]);
462 let expected = vec![(2, 2), (3, 3), (8, 0)];
463 assert_eq!(elements(map), expected);
467 fn test_insert_presorted_shuffle() {
468 let mut map = SortedMap::new();
472 map.insert_presorted(vec![(1, 1), (3, 3), (8, 8)]);
474 let expected = vec![(1, 1), (2, 2), (3, 3), (7, 7), (8, 8)];
475 assert_eq!(elements(map), expected);
479 fn test_insert_presorted_at_end() {
480 let mut map = SortedMap::new();
484 map.insert_presorted(vec![(3, 3), (8, 8)]);
486 let expected = vec![(1, 1), (2, 2), (3, 3), (8, 8)];
487 assert_eq!(elements(map), expected);