1use alloc::{
20 borrow::{
21 Borrow,
22 ToOwned,
23 },
24 collections::btree_map::{
25 self,
26 BTreeMap,
27 },
28 fmt::{
29 Debug,
30 Error,
31 Formatter,
32 },
33 vec::Vec,
34};
35
36use core::{
37 cmp::Ordering,
38 hash::{
39 Hash,
40 Hasher,
41 },
42 iter::{
43 FromIterator,
44 Iterator,
45 Sum,
46 },
47 mem,
48 ops::{
49 Add,
50 Index,
51 IndexMut,
52 RangeBounds,
53 },
54};
55
56
57#[cfg(has_specialisation)]
58use crate::util::linear_search_by;
59use crate::{
60 nodes::btree::{
61 BTreeValue,
62 Insert,
63 Node,
64 Remove,
65 },
66 util::{
67 Pool,
68 PoolRef,
69 },
70};
71
72pub use crate::nodes::btree::{
73 ConsumingIter,
74 DiffItem as NodeDiffItem,
75 DiffIter as NodeDiffIter,
76 Iter as RangedIter,
77};
78
79#[macro_export]
98macro_rules! ordmap {
99 () => { $crate::ordmap::OrdMap::new() };
100
101 ( $( $key:expr => $value:expr ),* ) => {{
102 let mut map = $crate::ordmap::OrdMap::new();
103 $({
104 map.insert($key, $value);
105 })*;
106 map
107 }};
108}
109
110#[cfg(not(has_specialisation))]
111impl<K: Ord, V> BTreeValue for (K, V) {
112 type Key = K;
113
114 fn ptr_eq(&self, _other: &Self) -> bool { false }
115
116 fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
117 where
118 BK: Ord + ?Sized,
119 Self::Key: Borrow<BK>, {
120 slice.binary_search_by(|value| Self::Key::borrow(&value.0).cmp(key))
121 }
122
123 fn search_value(slice: &[Self], key: &Self) -> Result<usize, usize> {
124 slice.binary_search_by(|value| value.0.cmp(&key.0))
125 }
126
127 fn cmp_keys<BK>(&self, other: &BK) -> Ordering
128 where
129 BK: Ord + ?Sized,
130 Self::Key: Borrow<BK>, {
131 Self::Key::borrow(&self.0).cmp(other)
132 }
133
134 fn cmp_values(&self, other: &Self) -> Ordering { self.0.cmp(&other.0) }
135}
136
137#[cfg(has_specialisation)]
138impl<K: Ord, V> BTreeValue for (K, V) {
139 type Key = K;
140
141 fn ptr_eq(&self, _other: &Self) -> bool { false }
142
143 default fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
144 where
145 BK: Ord + ?Sized,
146 Self::Key: Borrow<BK>, {
147 slice.binary_search_by(|value| Self::Key::borrow(&value.0).cmp(key))
148 }
149
150 default fn search_value(slice: &[Self], key: &Self) -> Result<usize, usize> {
151 slice.binary_search_by(|value| value.0.cmp(&key.0))
152 }
153
154 fn cmp_keys<BK>(&self, other: &BK) -> Ordering
155 where
156 BK: Ord + ?Sized,
157 Self::Key: Borrow<BK>, {
158 Self::Key::borrow(&self.0).cmp(other)
159 }
160
161 fn cmp_values(&self, other: &Self) -> Ordering { self.0.cmp(&other.0) }
162}
163
164#[cfg(has_specialisation)]
165impl<K: Ord + Copy, V> BTreeValue for (K, V) {
166 fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
167 where
168 BK: Ord + ?Sized,
169 Self::Key: Borrow<BK>, {
170 linear_search_by(slice, |value| Self::Key::borrow(&value.0).cmp(key))
171 }
172
173 fn search_value(slice: &[Self], key: &Self) -> Result<usize, usize> {
174 linear_search_by(slice, |value| value.0.cmp(&key.0))
175 }
176}
177
178def_pool!(OrdMapPool<K, V>, Node<(K, V)>);
179
180pub struct OrdMap<K, V> {
194 size: usize,
195 pool: OrdMapPool<K, V>,
196 root: PoolRef<Node<(K, V)>>,
197}
198
199impl<K, V> OrdMap<K, V> {
200 #[must_use]
202 pub fn new() -> Self {
203 let pool = OrdMapPool::default();
204 let root = PoolRef::default(&pool.0);
205 OrdMap { size: 0, pool, root }
206 }
207
208 #[cfg(feature = "pool")]
210 #[must_use]
211 pub fn with_pool(pool: &OrdMapPool<K, V>) -> Self {
212 let root = PoolRef::default(&pool.0);
213 OrdMap { size: 0, pool: pool.clone(), root }
214 }
215
216 #[inline]
227 #[must_use]
228 pub fn unit(key: K, value: V) -> Self {
229 let pool = OrdMapPool::default();
230 let root = PoolRef::new(&pool.0, Node::unit((key, value)));
231 OrdMap { size: 1, pool, root }
232 }
233
234 #[inline]
247 #[must_use]
248 pub fn is_empty(&self) -> bool { self.len() == 0 }
249
250 pub fn ptr_eq(&self, other: &Self) -> bool {
260 core::ptr::eq(self, other) || PoolRef::ptr_eq(&self.root, &other.root)
261 }
262
263 #[inline]
283 #[must_use]
284 pub fn len(&self) -> usize { self.size }
285
286 #[cfg(feature = "pool")]
291 pub fn pool(&self) -> &OrdMapPool<K, V> { &self.pool }
292
293 pub fn clear(&mut self) {
310 if !self.is_empty() {
311 self.root = PoolRef::default(&self.pool.0);
312 self.size = 0;
313 }
314 }
315}
316
317impl<K, V> OrdMap<K, V>
318where K: Ord
319{
320 #[must_use]
341 pub fn get_max(&self) -> Option<&(K, V)> { self.root.max() }
342
343 #[must_use]
364 pub fn get_min(&self) -> Option<&(K, V)> { self.root.min() }
365
366 #[must_use]
368 pub fn iter(&self) -> Iter<'_, K, V> {
369 Iter { it: RangedIter::new(&self.root, self.size, ..) }
370 }
371
372 #[must_use]
374 pub fn range<R, BK>(&self, range: R) -> Iter<'_, K, V>
375 where
376 R: RangeBounds<BK>,
377 K: Borrow<BK>,
378 BK: Ord + ?Sized, {
379 Iter { it: RangedIter::new(&self.root, self.size, range) }
380 }
381
382 #[must_use]
384 pub fn keys(&self) -> Keys<'_, K, V> { Keys { it: self.iter() } }
385
386 #[must_use]
388 pub fn values(&self) -> Values<'_, K, V> { Values { it: self.iter() } }
389
390 #[must_use]
402 pub fn diff<'a>(&'a self, other: &'a Self) -> DiffIter<'a, K, V> {
403 DiffIter { it: NodeDiffIter::new(&self.root, &other.root) }
404 }
405
406 #[must_use]
419 pub fn get<BK>(&self, key: &BK) -> Option<&V>
420 where
421 BK: Ord + ?Sized,
422 K: Borrow<BK>, {
423 self.root.lookup(key).map(|(_, v)| v)
424 }
425
426 #[must_use]
439 pub fn get_key_value<BK>(&self, key: &BK) -> Option<(&K, &V)>
440 where
441 BK: Ord + ?Sized,
442 K: Borrow<BK>, {
443 self.root.lookup(key).map(|&(ref k, ref v)| (k, v))
444 }
445
446 #[must_use]
463 pub fn get_prev<BK>(&self, key: &BK) -> Option<(&K, &V)>
464 where
465 BK: Ord + ?Sized,
466 K: Borrow<BK>, {
467 self.root.lookup_prev(key).map(|(k, v)| (k, v))
468 }
469
470 #[must_use]
487 pub fn get_next<BK>(&self, key: &BK) -> Option<(&K, &V)>
488 where
489 BK: Ord + ?Sized,
490 K: Borrow<BK>, {
491 self.root.lookup_next(key).map(|(k, v)| (k, v))
492 }
493
494 #[must_use]
508 pub fn contains_key<BK>(&self, k: &BK) -> bool
509 where
510 BK: Ord + ?Sized,
511 K: Borrow<BK>, {
512 self.get(k).is_some()
513 }
514
515 #[must_use]
523 pub fn is_submap_by<B, RM, F>(&self, other: RM, mut cmp: F) -> bool
524 where
525 F: FnMut(&V, &B) -> bool,
526 RM: Borrow<OrdMap<K, B>>, {
527 self
528 .iter()
529 .all(|(k, v)| other.borrow().get(k).map(|ov| cmp(v, ov)).unwrap_or(false))
530 }
531
532 #[must_use]
541 pub fn is_proper_submap_by<B, RM, F>(&self, other: RM, cmp: F) -> bool
542 where
543 F: FnMut(&V, &B) -> bool,
544 RM: Borrow<OrdMap<K, B>>, {
545 self.len() != other.borrow().len() && self.is_submap_by(other, cmp)
546 }
547
548 #[must_use]
564 pub fn is_submap<RM>(&self, other: RM) -> bool
565 where
566 V: PartialEq,
567 RM: Borrow<Self>, {
568 self.is_submap_by(other.borrow(), PartialEq::eq)
569 }
570
571 #[must_use]
592 pub fn is_proper_submap<RM>(&self, other: RM) -> bool
593 where
594 V: PartialEq,
595 RM: Borrow<Self>, {
596 self.is_proper_submap_by(other.borrow(), PartialEq::eq)
597 }
598}
599
600impl<K, V> OrdMap<K, V>
601where
602 K: Ord + Clone,
603 V: Clone,
604{
605 #[must_use]
621 pub fn get_mut<BK>(&mut self, key: &BK) -> Option<&mut V>
622 where
623 BK: Ord + ?Sized,
624 K: Borrow<BK>, {
625 let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
626 root.lookup_mut(&self.pool.0, key).map(|(_, v)| v)
627 }
628
629 #[must_use]
649 pub fn get_prev_mut<BK>(&mut self, key: &BK) -> Option<(&K, &mut V)>
650 where
651 BK: Ord + ?Sized,
652 K: Borrow<BK>, {
653 let pool = &self.pool.0;
654 PoolRef::make_mut(pool, &mut self.root)
655 .lookup_prev_mut(pool, key)
656 .map(|(ref k, ref mut v)| (k, v))
657 }
658
659 #[must_use]
679 pub fn get_next_mut<BK>(&mut self, key: &BK) -> Option<(&K, &mut V)>
680 where
681 BK: Ord + ?Sized,
682 K: Borrow<BK>, {
683 let pool = &self.pool.0;
684 PoolRef::make_mut(pool, &mut self.root)
685 .lookup_next_mut(pool, key)
686 .map(|(ref k, ref mut v)| (k, v))
687 }
688
689 #[inline]
713 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
714 let new_root = {
715 let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
716 match root.insert(&self.pool.0, (key, value)) {
717 Insert::Replaced((_, old_value)) => return Some(old_value),
718 Insert::Added => {
719 self.size += 1;
720 return None;
721 }
722 Insert::Split(left, median, right) => PoolRef::new(
723 &self.pool.0,
724 Node::new_from_split(&self.pool.0, left, median, right),
725 ),
726 }
727 };
728 self.size += 1;
729 self.root = new_root;
730 None
731 }
732
733 #[inline]
750 pub fn remove<BK>(&mut self, k: &BK) -> Option<V>
751 where
752 BK: Ord + ?Sized,
753 K: Borrow<BK>, {
754 self.remove_with_key(k).map(|(_, v)| v)
755 }
756
757 pub fn remove_with_key<BK>(&mut self, k: &BK) -> Option<(K, V)>
762 where
763 BK: Ord + ?Sized,
764 K: Borrow<BK>, {
765 let (new_root, removed_value) = {
766 let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
767 match root.remove(&self.pool.0, k) {
768 Remove::NoChange => return None,
769 Remove::Removed(pair) => {
770 self.size -= 1;
771 return Some(pair);
772 }
773 Remove::Update(pair, root) => {
774 (PoolRef::new(&self.pool.0, root), Some(pair))
775 }
776 }
777 };
778 self.size -= 1;
779 self.root = new_root;
780 removed_value
781 }
782
783 #[must_use]
800 pub fn update(&self, key: K, value: V) -> Self {
801 let mut out = self.clone();
802 out.insert(key, value);
803 out
804 }
805
806 #[must_use]
815 pub fn update_with<F>(self, k: K, v: V, f: F) -> Self
816 where F: FnOnce(V, V) -> V {
817 self.update_with_key(k, v, |_, v1, v2| f(v1, v2))
818 }
819
820 #[must_use]
829 pub fn update_with_key<F>(self, k: K, v: V, f: F) -> Self
830 where F: FnOnce(&K, V, V) -> V {
831 match self.extract_with_key(&k) {
832 None => self.update(k, v),
833 Some((_, v2, m)) => {
834 let out_v = f(&k, v2, v);
835 m.update(k, out_v)
836 }
837 }
838 }
839
840 #[must_use]
850 pub fn update_lookup_with_key<F>(
851 self,
852 k: K,
853 v: V,
854 f: F,
855 ) -> (Option<V>, Self)
856 where
857 F: FnOnce(&K, &V, V) -> V,
858 {
859 match self.extract_with_key(&k) {
860 None => (None, self.update(k, v)),
861 Some((_, v2, m)) => {
862 let out_v = f(&k, &v2, v);
863 (Some(v2), m.update(k, out_v))
864 }
865 }
866 }
867
868 #[must_use]
881 pub fn alter<F>(&self, f: F, k: K) -> Self
882 where F: FnOnce(Option<V>) -> Option<V> {
883 let pop = self.extract_with_key(&k);
884 match (f(pop.as_ref().map(|&(_, ref v, _)| v.clone())), pop) {
885 (None, None) => self.clone(),
886 (Some(v), None) => self.update(k, v),
887 (None, Some((_, _, m))) => m,
888 (Some(v), Some((_, _, m))) => m.update(k, v),
889 }
890 }
891
892 #[must_use]
896 pub fn without<BK>(&self, k: &BK) -> Self
897 where
898 BK: Ord + ?Sized,
899 K: Borrow<BK>, {
900 self.extract(k).map(|(_, m)| m).unwrap_or_else(|| self.clone())
901 }
902
903 #[must_use]
908 pub fn extract<BK>(&self, k: &BK) -> Option<(V, Self)>
909 where
910 BK: Ord + ?Sized,
911 K: Borrow<BK>, {
912 self.extract_with_key(k).map(|(_, v, m)| (v, m))
913 }
914
915 #[must_use]
920 pub fn extract_with_key<BK>(&self, k: &BK) -> Option<(K, V, Self)>
921 where
922 BK: Ord + ?Sized,
923 K: Borrow<BK>, {
924 let mut out = self.clone();
925 let result = out.remove_with_key(k);
926 result.map(|(k, v)| (k, v, out))
927 }
928
929 #[inline]
945 #[must_use]
946 pub fn union(mut self, other: Self) -> Self {
947 for (k, v) in other {
948 self.entry(k).or_insert(v);
949 }
950 self
951 }
952
953 #[inline]
963 #[must_use]
964 pub fn union_with<F>(self, other: Self, mut f: F) -> Self
965 where F: FnMut(V, V) -> V {
966 self.union_with_key(other, |_, v1, v2| f(v1, v2))
967 }
968
969 #[must_use]
994 pub fn union_with_key<F>(mut self, other: Self, mut f: F) -> Self
995 where F: FnMut(&K, V, V) -> V {
996 for (key, right_value) in other {
997 match self.remove(&key) {
998 None => {
999 self.insert(key, right_value);
1000 }
1001 Some(left_value) => {
1002 let final_value = f(&key, left_value, right_value);
1003 self.insert(key, final_value);
1004 }
1005 }
1006 }
1007 self
1008 }
1009
1010 #[must_use]
1026 pub fn unions<I>(i: I) -> Self
1027 where I: IntoIterator<Item = Self> {
1028 i.into_iter().fold(Self::default(), Self::union)
1029 }
1030
1031 #[must_use]
1042 pub fn unions_with<I, F>(i: I, f: F) -> Self
1043 where
1044 I: IntoIterator<Item = Self>,
1045 F: Fn(V, V) -> V, {
1046 i.into_iter().fold(Self::default(), |a, b| a.union_with(b, &f))
1047 }
1048
1049 #[must_use]
1061 pub fn unions_with_key<I, F>(i: I, f: F) -> Self
1062 where
1063 I: IntoIterator<Item = Self>,
1064 F: Fn(&K, V, V) -> V, {
1065 i.into_iter().fold(Self::default(), |a, b| a.union_with_key(b, &f))
1066 }
1067
1068 #[inline]
1089 #[must_use]
1090 pub fn difference(self, other: Self) -> Self {
1091 self.symmetric_difference(other)
1092 }
1093
1094 #[inline]
1110 #[must_use]
1111 pub fn symmetric_difference(self, other: Self) -> Self {
1112 self.symmetric_difference_with_key(other, |_, _, _| None)
1113 }
1114
1115 #[inline]
1125 #[must_use]
1126 pub fn difference_with<F>(self, other: Self, f: F) -> Self
1127 where F: FnMut(V, V) -> Option<V> {
1128 self.symmetric_difference_with(other, f)
1129 }
1130
1131 #[inline]
1136 #[must_use]
1137 pub fn symmetric_difference_with<F>(self, other: Self, mut f: F) -> Self
1138 where F: FnMut(V, V) -> Option<V> {
1139 self.symmetric_difference_with_key(other, |_, a, b| f(a, b))
1140 }
1141
1142 #[must_use]
1167 pub fn difference_with_key<F>(self, other: Self, f: F) -> Self
1168 where F: FnMut(&K, V, V) -> Option<V> {
1169 self.symmetric_difference_with_key(other, f)
1170 }
1171
1172 #[must_use]
1194 pub fn symmetric_difference_with_key<F>(
1195 mut self,
1196 other: Self,
1197 mut f: F,
1198 ) -> Self
1199 where
1200 F: FnMut(&K, V, V) -> Option<V>,
1201 {
1202 let mut out = Self::default();
1203 for (key, right_value) in other {
1204 match self.remove(&key) {
1205 None => {
1206 out.insert(key, right_value);
1207 }
1208 Some(left_value) => {
1209 if let Some(final_value) = f(&key, left_value, right_value) {
1210 out.insert(key, final_value);
1211 }
1212 }
1213 }
1214 }
1215 out.union(self)
1216 }
1217
1218 #[inline]
1234 #[must_use]
1235 pub fn relative_complement(mut self, other: Self) -> Self {
1236 for (key, _) in other {
1237 let _ = self.remove(&key);
1238 }
1239 self
1240 }
1241
1242 #[inline]
1258 #[must_use]
1259 pub fn intersection(self, other: Self) -> Self {
1260 self.intersection_with_key(other, |_, v, _| v)
1261 }
1262
1263 #[inline]
1269 #[must_use]
1270 pub fn intersection_with<B, C, F>(
1271 self,
1272 other: OrdMap<K, B>,
1273 mut f: F,
1274 ) -> OrdMap<K, C>
1275 where
1276 B: Clone,
1277 C: Clone,
1278 F: FnMut(V, B) -> C,
1279 {
1280 self.intersection_with_key(other, |_, v1, v2| f(v1, v2))
1281 }
1282
1283 #[must_use]
1303 pub fn intersection_with_key<B, C, F>(
1304 mut self,
1305 other: OrdMap<K, B>,
1306 mut f: F,
1307 ) -> OrdMap<K, C>
1308 where
1309 B: Clone,
1310 C: Clone,
1311 F: FnMut(&K, V, B) -> C,
1312 {
1313 let mut out = OrdMap::<K, C>::default();
1314 for (key, right_value) in other {
1315 match self.remove(&key) {
1316 None => (),
1317 Some(left_value) => {
1318 let result = f(&key, left_value, right_value);
1319 out.insert(key, result);
1320 }
1321 }
1322 }
1323 out
1324 }
1325
1326 #[must_use]
1332 pub fn split<BK>(&self, split: &BK) -> (Self, Self)
1333 where
1334 BK: Ord + ?Sized,
1335 K: Borrow<BK>, {
1336 let (l, _, r) = self.split_lookup(split);
1337 (l, r)
1338 }
1339
1340 #[must_use]
1346 pub fn split_lookup<BK>(&self, split: &BK) -> (Self, Option<V>, Self)
1347 where
1348 BK: Ord + ?Sized,
1349 K: Borrow<BK>, {
1350 self.iter().fold((ordmap![], None, ordmap![]), |(l, m, r), (k, v)| match k
1352 .borrow()
1353 .cmp(split)
1354 {
1355 Ordering::Less => (l.update(k.clone(), v.clone()), m, r),
1356 Ordering::Equal => (l, Some(v.clone()), r),
1357 Ordering::Greater => (l, m, r.update(k.clone(), v.clone())),
1358 })
1359 }
1360
1361 #[must_use]
1364 pub fn take(&self, n: usize) -> Self {
1365 self.iter().take(n).map(|(k, v)| (k.clone(), v.clone())).collect()
1366 }
1367
1368 #[must_use]
1371 pub fn skip(&self, n: usize) -> Self {
1372 self.iter().skip(n).map(|(k, v)| (k.clone(), v.clone())).collect()
1373 }
1374
1375 #[must_use]
1378 pub fn without_min(&self) -> (Option<V>, Self) {
1379 let (pop, next) = self.without_min_with_key();
1380 (pop.map(|(_, v)| v), next)
1381 }
1382
1383 #[must_use]
1386 pub fn without_min_with_key(&self) -> (Option<(K, V)>, Self) {
1387 match self.get_min() {
1388 None => (None, self.clone()),
1389 Some((k, _)) => {
1390 let (key, value, next) = self.extract_with_key(k).unwrap();
1391 (Some((key, value)), next)
1392 }
1393 }
1394 }
1395
1396 #[must_use]
1399 pub fn without_max(&self) -> (Option<V>, Self) {
1400 let (pop, next) = self.without_max_with_key();
1401 (pop.map(|(_, v)| v), next)
1402 }
1403
1404 #[must_use]
1407 pub fn without_max_with_key(&self) -> (Option<(K, V)>, Self) {
1408 match self.get_max() {
1409 None => (None, self.clone()),
1410 Some((k, _)) => {
1411 let (key, value, next) = self.extract_with_key(k).unwrap();
1412 (Some((key, value)), next)
1413 }
1414 }
1415 }
1416
1417 #[must_use]
1423 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
1424 if self.contains_key(&key) {
1425 Entry::Occupied(OccupiedEntry { map: self, key })
1426 }
1427 else {
1428 Entry::Vacant(VacantEntry { map: self, key })
1429 }
1430 }
1431}
1432
1433pub enum Entry<'a, K, V>
1437where
1438 K: Ord + Clone,
1439 V: Clone, {
1440 Occupied(OccupiedEntry<'a, K, V>),
1442 Vacant(VacantEntry<'a, K, V>),
1444}
1445
1446impl<'a, K, V> Entry<'a, K, V>
1447where
1448 K: Ord + Clone,
1449 V: Clone,
1450{
1451 pub fn or_insert(self, default: V) -> &'a mut V {
1454 self.or_insert_with(|| default)
1455 }
1456
1457 pub fn or_insert_with<F>(self, default: F) -> &'a mut V
1461 where F: FnOnce() -> V {
1462 match self {
1463 Entry::Occupied(entry) => entry.into_mut(),
1464 Entry::Vacant(entry) => entry.insert(default()),
1465 }
1466 }
1467
1468 pub fn or_default(self) -> &'a mut V
1471 where V: Default {
1472 self.or_insert_with(Default::default)
1473 }
1474
1475 #[must_use]
1477 pub fn key(&self) -> &K {
1478 match self {
1479 Entry::Occupied(entry) => entry.key(),
1480 Entry::Vacant(entry) => entry.key(),
1481 }
1482 }
1483
1484 pub fn and_modify<F>(mut self, f: F) -> Self
1487 where F: FnOnce(&mut V) {
1488 match &mut self {
1489 Entry::Occupied(ref mut entry) => f(entry.get_mut()),
1490 Entry::Vacant(_) => (),
1491 }
1492 self
1493 }
1494}
1495
1496pub struct OccupiedEntry<'a, K, V>
1498where
1499 K: Ord + Clone,
1500 V: Clone, {
1501 map: &'a mut OrdMap<K, V>,
1502 key: K,
1503}
1504
1505impl<'a, K, V> OccupiedEntry<'a, K, V>
1506where
1507 K: 'a + Ord + Clone,
1508 V: 'a + Clone,
1509{
1510 #[must_use]
1512 pub fn key(&self) -> &K { &self.key }
1513
1514 pub fn remove_entry(self) -> (K, V) {
1516 self
1517 .map
1518 .remove_with_key(&self.key)
1519 .expect("ordmap::OccupiedEntry::remove_entry: key has vanished!")
1520 }
1521
1522 #[must_use]
1524 pub fn get(&self) -> &V { self.map.get(&self.key).unwrap() }
1525
1526 #[must_use]
1528 pub fn get_mut(&mut self) -> &mut V { self.map.get_mut(&self.key).unwrap() }
1529
1530 #[must_use]
1532 pub fn into_mut(self) -> &'a mut V { self.map.get_mut(&self.key).unwrap() }
1533
1534 pub fn insert(&mut self, value: V) -> V {
1536 mem::replace(self.get_mut(), value)
1537 }
1538
1539 pub fn remove(self) -> V { self.remove_entry().1 }
1541}
1542
1543pub struct VacantEntry<'a, K, V>
1545where
1546 K: Ord + Clone,
1547 V: Clone, {
1548 map: &'a mut OrdMap<K, V>,
1549 key: K,
1550}
1551
1552impl<'a, K, V> VacantEntry<'a, K, V>
1553where
1554 K: 'a + Ord + Clone,
1555 V: 'a + Clone,
1556{
1557 #[must_use]
1559 pub fn key(&self) -> &K { &self.key }
1560
1561 #[must_use]
1563 pub fn into_key(self) -> K { self.key }
1564
1565 pub fn insert(self, value: V) -> &'a mut V {
1567 self.map.insert(self.key.clone(), value);
1568 self.map.get_mut(&self.key).unwrap()
1570 }
1571}
1572
1573impl<K, V> Clone for OrdMap<K, V> {
1576 #[inline]
1580 fn clone(&self) -> Self {
1581 OrdMap { size: self.size, pool: self.pool.clone(), root: self.root.clone() }
1582 }
1583}
1584
1585#[cfg(not(has_specialisation))]
1586impl<K, V> PartialEq for OrdMap<K, V>
1587where
1588 K: Ord + PartialEq,
1589 V: PartialEq,
1590{
1591 fn eq(&self, other: &Self) -> bool {
1592 self.len() == other.len() && self.diff(other).next().is_none()
1593 }
1594}
1595
1596#[cfg(has_specialisation)]
1597impl<K, V> PartialEq for OrdMap<K, V>
1598where
1599 K: Ord + PartialEq,
1600 V: PartialEq,
1601{
1602 default fn eq(&self, other: &Self) -> bool {
1603 self.len() == other.len() && self.diff(other).next().is_none()
1604 }
1605}
1606
1607#[cfg(has_specialisation)]
1608impl<K, V> PartialEq for OrdMap<K, V>
1609where
1610 K: Ord + Eq,
1611 V: Eq,
1612{
1613 fn eq(&self, other: &Self) -> bool {
1614 PoolRef::ptr_eq(&self.root, &other.root)
1615 || (self.len() == other.len() && self.diff(other).next().is_none())
1616 }
1617}
1618
1619impl<K: Ord + Eq, V: Eq> Eq for OrdMap<K, V> {}
1620
1621impl<K, V> PartialOrd for OrdMap<K, V>
1622where
1623 K: Ord,
1624 V: PartialOrd,
1625{
1626 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1627 self.iter().partial_cmp(other.iter())
1628 }
1629}
1630
1631impl<K, V> Ord for OrdMap<K, V>
1632where
1633 K: Ord,
1634 V: Ord,
1635{
1636 fn cmp(&self, other: &Self) -> Ordering { self.iter().cmp(other.iter()) }
1637}
1638
1639impl<K, V> Hash for OrdMap<K, V>
1640where
1641 K: Ord + Hash,
1642 V: Hash,
1643{
1644 fn hash<H>(&self, state: &mut H)
1645 where H: Hasher {
1646 for i in self.iter() {
1647 i.hash(state);
1648 }
1649 }
1650}
1651
1652impl<K, V> Default for OrdMap<K, V> {
1653 fn default() -> Self { Self::new() }
1654}
1655
1656impl<'a, K, V> Add for &'a OrdMap<K, V>
1657where
1658 K: Ord + Clone,
1659 V: Clone,
1660{
1661 type Output = OrdMap<K, V>;
1662
1663 fn add(self, other: Self) -> Self::Output {
1664 self.clone().union(other.clone())
1665 }
1666}
1667
1668impl<K, V> Add for OrdMap<K, V>
1669where
1670 K: Ord + Clone,
1671 V: Clone,
1672{
1673 type Output = OrdMap<K, V>;
1674
1675 fn add(self, other: Self) -> Self::Output { self.union(other) }
1676}
1677
1678impl<K, V> Sum for OrdMap<K, V>
1679where
1680 K: Ord + Clone,
1681 V: Clone,
1682{
1683 fn sum<I>(it: I) -> Self
1684 where I: Iterator<Item = Self> {
1685 it.fold(Self::default(), |a, b| a + b)
1686 }
1687}
1688
1689impl<K, V, RK, RV> Extend<(RK, RV)> for OrdMap<K, V>
1690where
1691 K: Ord + Clone + From<RK>,
1692 V: Clone + From<RV>,
1693{
1694 fn extend<I>(&mut self, iter: I)
1695 where I: IntoIterator<Item = (RK, RV)> {
1696 for (key, value) in iter {
1697 self.insert(From::from(key), From::from(value));
1698 }
1699 }
1700}
1701
1702impl<'a, BK, K, V> Index<&'a BK> for OrdMap<K, V>
1703where
1704 BK: Ord + ?Sized,
1705 K: Ord + Borrow<BK>,
1706{
1707 type Output = V;
1708
1709 fn index(&self, key: &BK) -> &Self::Output {
1710 match self.root.lookup(key) {
1711 None => panic!("OrdMap::index: invalid key"),
1712 Some(&(_, ref value)) => value,
1713 }
1714 }
1715}
1716
1717impl<'a, BK, K, V> IndexMut<&'a BK> for OrdMap<K, V>
1718where
1719 BK: Ord + ?Sized,
1720 K: Ord + Clone + Borrow<BK>,
1721 V: Clone,
1722{
1723 fn index_mut(&mut self, key: &BK) -> &mut Self::Output {
1724 let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
1725 match root.lookup_mut(&self.pool.0, key) {
1726 None => panic!("OrdMap::index: invalid key"),
1727 Some(&mut (_, ref mut value)) => value,
1728 }
1729 }
1730}
1731
1732impl<K, V> Debug for OrdMap<K, V>
1733where
1734 K: Ord + Debug,
1735 V: Debug,
1736{
1737 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
1738 let mut d = f.debug_map();
1739 for (k, v) in self.iter() {
1740 d.entry(k, v);
1741 }
1742 d.finish()
1743 }
1744}
1745
1746pub struct Iter<'a, K, V> {
1750 it: RangedIter<'a, (K, V)>,
1751}
1752
1753impl<'a, K, V> Iterator for Iter<'a, K, V>
1754where (K, V): 'a + BTreeValue
1755{
1756 type Item = (&'a K, &'a V);
1757
1758 fn next(&mut self) -> Option<Self::Item> {
1759 self.it.next().map(|(k, v)| (k, v))
1760 }
1761
1762 fn size_hint(&self) -> (usize, Option<usize>) {
1763 (self.it.remaining, Some(self.it.remaining))
1764 }
1765}
1766
1767impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V>
1768where (K, V): 'a + BTreeValue
1769{
1770 fn next_back(&mut self) -> Option<Self::Item> {
1771 self.it.next_back().map(|(k, v)| (k, v))
1772 }
1773}
1774
1775impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> where (K, V): 'a + BTreeValue {}
1776
1777pub struct DiffIter<'a, K, V> {
1779 it: NodeDiffIter<'a, (K, V)>,
1780}
1781
1782#[derive(PartialEq, Eq, Debug)]
1784pub enum DiffItem<'a, K, V> {
1785 Add(&'a K, &'a V),
1787 Update {
1789 old: (&'a K, &'a V),
1791 new: (&'a K, &'a V),
1793 },
1794 Remove(&'a K, &'a V),
1796}
1797
1798impl<'a, K, V> Iterator for DiffIter<'a, K, V>
1799where (K, V): 'a + BTreeValue + PartialEq
1800{
1801 type Item = DiffItem<'a, K, V>;
1802
1803 fn next(&mut self) -> Option<Self::Item> {
1804 self.it.next().map(|item| match item {
1805 NodeDiffItem::Add((k, v)) => DiffItem::Add(k, v),
1806 NodeDiffItem::Update { old: (oldk, oldv), new: (newk, newv) } => {
1807 DiffItem::Update { old: (oldk, oldv), new: (newk, newv) }
1808 }
1809 NodeDiffItem::Remove((k, v)) => DiffItem::Remove(k, v),
1810 })
1811 }
1812}
1813
1814pub struct Keys<'a, K, V> {
1816 it: Iter<'a, K, V>,
1817}
1818
1819impl<'a, K, V> Iterator for Keys<'a, K, V>
1820where
1821 K: 'a + Ord,
1822 V: 'a,
1823{
1824 type Item = &'a K;
1825
1826 fn next(&mut self) -> Option<Self::Item> { self.it.next().map(|(k, _)| k) }
1827
1828 fn size_hint(&self) -> (usize, Option<usize>) { self.it.size_hint() }
1829}
1830
1831impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V>
1832where
1833 K: 'a + Ord,
1834 V: 'a,
1835{
1836 fn next_back(&mut self) -> Option<Self::Item> {
1837 match self.it.next_back() {
1838 None => None,
1839 Some((k, _)) => Some(k),
1840 }
1841 }
1842}
1843
1844impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V>
1845where
1846 K: 'a + Ord,
1847 V: 'a,
1848{
1849}
1850
1851pub struct Values<'a, K, V> {
1853 it: Iter<'a, K, V>,
1854}
1855
1856impl<'a, K, V> Iterator for Values<'a, K, V>
1857where
1858 K: 'a + Ord,
1859 V: 'a,
1860{
1861 type Item = &'a V;
1862
1863 fn next(&mut self) -> Option<Self::Item> { self.it.next().map(|(_, v)| v) }
1864
1865 fn size_hint(&self) -> (usize, Option<usize>) { self.it.size_hint() }
1866}
1867
1868impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V>
1869where
1870 K: 'a + Ord,
1871 V: 'a,
1872{
1873 fn next_back(&mut self) -> Option<Self::Item> {
1874 match self.it.next_back() {
1875 None => None,
1876 Some((_, v)) => Some(v),
1877 }
1878 }
1879}
1880
1881impl<'a, K, V> ExactSizeIterator for Values<'a, K, V>
1882where
1883 K: 'a + Ord,
1884 V: 'a,
1885{
1886}
1887
1888impl<K, V, RK, RV> FromIterator<(RK, RV)> for OrdMap<K, V>
1889where
1890 K: Ord + Clone + From<RK>,
1891 V: Clone + From<RV>,
1892{
1893 fn from_iter<T>(i: T) -> Self
1894 where T: IntoIterator<Item = (RK, RV)> {
1895 let mut m = OrdMap::default();
1896 for (k, v) in i {
1897 m.insert(From::from(k), From::from(v));
1898 }
1899 m
1900 }
1901}
1902
1903impl<'a, K, V> IntoIterator for &'a OrdMap<K, V>
1904where K: Ord
1905{
1906 type IntoIter = Iter<'a, K, V>;
1907 type Item = (&'a K, &'a V);
1908
1909 fn into_iter(self) -> Self::IntoIter { self.iter() }
1910}
1911
1912impl<K, V> IntoIterator for OrdMap<K, V>
1913where
1914 K: Ord + Clone,
1915 V: Clone,
1916{
1917 type IntoIter = ConsumingIter<(K, V)>;
1918 type Item = (K, V);
1919
1920 fn into_iter(self) -> Self::IntoIter {
1921 ConsumingIter::new(&self.root, self.size)
1922 }
1923}
1924
1925impl<K, V> AsRef<OrdMap<K, V>> for OrdMap<K, V> {
1928 fn as_ref(&self) -> &Self { self }
1929}
1930
1931impl<'m, 'k, 'v, K, V, OK, OV> From<&'m OrdMap<&'k K, &'v V>> for OrdMap<OK, OV>
1932where
1933 K: Ord + ToOwned<Owned = OK> + ?Sized,
1934 V: ToOwned<Owned = OV> + ?Sized,
1935 OK: Ord + Clone + Borrow<K>,
1936 OV: Clone + Borrow<V>,
1937{
1938 fn from(m: &OrdMap<&K, &V>) -> Self {
1939 m.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect()
1940 }
1941}
1942
1943impl<'a, K, V, RK, RV, OK, OV> From<&'a [(RK, RV)]> for OrdMap<K, V>
1944where
1945 K: Ord + Clone + From<OK>,
1946 V: Clone + From<OV>,
1947 OK: Borrow<RK>,
1948 OV: Borrow<RV>,
1949 RK: ToOwned<Owned = OK>,
1950 RV: ToOwned<Owned = OV>,
1951{
1952 fn from(m: &'a [(RK, RV)]) -> OrdMap<K, V> {
1953 m.iter().map(|&(ref k, ref v)| (k.to_owned(), v.to_owned())).collect()
1954 }
1955}
1956
1957impl<K, V, RK, RV> From<Vec<(RK, RV)>> for OrdMap<K, V>
1958where
1959 K: Ord + Clone + From<RK>,
1960 V: Clone + From<RV>,
1961{
1962 fn from(m: Vec<(RK, RV)>) -> OrdMap<K, V> { m.into_iter().collect() }
1963}
1964
1965impl<'a, K: Ord, V, RK, RV, OK, OV> From<&'a Vec<(RK, RV)>> for OrdMap<K, V>
1966where
1967 K: Ord + Clone + From<OK>,
1968 V: Clone + From<OV>,
1969 OK: Borrow<RK>,
1970 OV: Borrow<RV>,
1971 RK: ToOwned<Owned = OK>,
1972 RV: ToOwned<Owned = OV>,
1973{
1974 fn from(m: &'a Vec<(RK, RV)>) -> OrdMap<K, V> {
1975 m.iter().map(|&(ref k, ref v)| (k.to_owned(), v.to_owned())).collect()
1976 }
1977}
1978
1979impl<K: Ord, V, RK, RV> From<BTreeMap<RK, RV>> for OrdMap<K, V>
1980where
1981 K: Ord + Clone + From<RK>,
1982 V: Clone + From<RV>,
1983{
1984 fn from(m: BTreeMap<RK, RV>) -> OrdMap<K, V> { m.into_iter().collect() }
1985}
1986
1987impl<'a, K: Ord, V, RK, RV, OK, OV> From<&'a btree_map::BTreeMap<RK, RV>>
1988 for OrdMap<K, V>
1989where
1990 K: Ord + Clone + From<OK>,
1991 V: Clone + From<OV>,
1992 OK: Borrow<RK>,
1993 OV: Borrow<RV>,
1994 RK: Ord + ToOwned<Owned = OK>,
1995 RV: ToOwned<Owned = OV>,
1996{
1997 fn from(m: &'a btree_map::BTreeMap<RK, RV>) -> OrdMap<K, V> {
1998 m.iter().map(|(k, v)| (k.to_owned(), v.to_owned())).collect()
1999 }
2000}
2001
2002#[cfg(test)]
2005mod test {
2006 use super::*;
2007 use crate::test::is_sorted;
2008 use rand::{
2009 random,
2010 seq::SliceRandom,
2011 thread_rng,
2012 Rng,
2013 };
2014 #[test]
2025 fn iterates_in_order() {
2026 let map = ordmap! {
2027 2 => 22,
2028 1 => 11,
2029 3 => 33,
2030 8 => 88,
2031 9 => 99,
2032 4 => 44,
2033 5 => 55,
2034 7 => 77,
2035 6 => 66
2036 };
2037 let mut it = map.iter();
2038 assert_eq!(it.next(), Some((&1, &11)));
2039 assert_eq!(it.next(), Some((&2, &22)));
2040 assert_eq!(it.next(), Some((&3, &33)));
2041 assert_eq!(it.next(), Some((&4, &44)));
2042 assert_eq!(it.next(), Some((&5, &55)));
2043 assert_eq!(it.next(), Some((&6, &66)));
2044 assert_eq!(it.next(), Some((&7, &77)));
2045 assert_eq!(it.next(), Some((&8, &88)));
2046 assert_eq!(it.next(), Some((&9, &99)));
2047 assert_eq!(it.next(), None);
2048 }
2049
2050 #[test]
2051 fn into_iter() {
2052 let map = ordmap! {
2053 2 => 22,
2054 1 => 11,
2055 3 => 33,
2056 8 => 88,
2057 9 => 99,
2058 4 => 44,
2059 5 => 55,
2060 7 => 77,
2061 6 => 66
2062 };
2063 let mut vec = vec![];
2064 for (k, v) in map {
2065 assert_eq!(k * 11, v);
2066 vec.push(k)
2067 }
2068 assert_eq!(vec, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]);
2069 }
2070
2071 #[test]
2072 fn deletes_correctly() {
2073 let map = ordmap! {
2074 2 => 22,
2075 1 => 11,
2076 3 => 33,
2077 8 => 88,
2078 9 => 99,
2079 4 => 44,
2080 5 => 55,
2081 7 => 77,
2082 6 => 66
2083 };
2084 assert_eq!(map.extract(&11), None);
2085 let (popped, less) = map.extract(&5).unwrap();
2086 assert_eq!(popped, 55);
2087 let mut it = less.iter();
2088 assert_eq!(it.next(), Some((&1, &11)));
2089 assert_eq!(it.next(), Some((&2, &22)));
2090 assert_eq!(it.next(), Some((&3, &33)));
2091 assert_eq!(it.next(), Some((&4, &44)));
2092 assert_eq!(it.next(), Some((&6, &66)));
2093 assert_eq!(it.next(), Some((&7, &77)));
2094 assert_eq!(it.next(), Some((&8, &88)));
2095 assert_eq!(it.next(), Some((&9, &99)));
2096 assert_eq!(it.next(), None);
2097 }
2098
2099 #[test]
2100 fn debug_output() {
2101 assert_eq!(
2102 format!("{:?}", ordmap! { 3 => 4, 5 => 6, 1 => 2 }),
2103 "{1: 2, 3: 4, 5: 6}"
2104 );
2105 }
2106
2107 #[test]
2108 fn equality2() {
2109 let v1 = "1".to_string();
2110 let v2 = "1".to_string();
2111 assert_eq!(v1, v2);
2112 let p1 = Vec::<String>::new();
2113 let p2 = Vec::<String>::new();
2114 assert_eq!(p1, p2);
2115 let c1 = OrdMap::unit(v1, p1);
2116 let c2 = OrdMap::unit(v2, p2);
2117 assert_eq!(c1, c2);
2118 }
2119
2120 #[test]
2121 fn insert_remove_single_mut() {
2122 let mut m = OrdMap::new();
2123 m.insert(0, 0);
2124 assert_eq!(OrdMap::unit(0, 0), m);
2125 m.remove(&0);
2126 assert_eq!(OrdMap::new(), m);
2127 }
2128
2129 #[test]
2130 fn double_ended_iterator_1() {
2131 let m = ordmap! {1 => 1, 2 => 2, 3 => 3, 4 => 4};
2132 let mut it = m.iter();
2133 assert_eq!(Some((&1, &1)), it.next());
2134 assert_eq!(Some((&4, &4)), it.next_back());
2135 assert_eq!(Some((&2, &2)), it.next());
2136 assert_eq!(Some((&3, &3)), it.next_back());
2137 assert_eq!(None, it.next());
2138 }
2139
2140 #[test]
2141 fn double_ended_iterator_2() {
2142 let m = ordmap! {1 => 1, 2 => 2, 3 => 3, 4 => 4};
2143 let mut it = m.iter();
2144 assert_eq!(Some((&1, &1)), it.next());
2145 assert_eq!(Some((&4, &4)), it.next_back());
2146 assert_eq!(Some((&2, &2)), it.next());
2147 assert_eq!(Some((&3, &3)), it.next_back());
2148 assert_eq!(None, it.next_back());
2149 }
2150
2151 #[test]
2152 fn safe_mutation() {
2153 let v1 = OrdMap::from_iter((0..131_072).map(|i| (i, i)));
2154 let mut v2 = v1.clone();
2155 v2.insert(131_000, 23);
2156 assert_eq!(Some(&23), v2.get(&131_000));
2157 assert_eq!(Some(&131_000), v1.get(&131_000));
2158 }
2159
2160 #[test]
2161 fn index_operator() {
2162 let mut map = ordmap! {1 => 2, 3 => 4, 5 => 6};
2163 assert_eq!(4, map[&3]);
2164 map[&3] = 8;
2165 assert_eq!(ordmap! {1 => 2, 3 => 8, 5 => 6}, map);
2166 }
2167
2168 #[test]
2169 fn entry_api() {
2170 let mut map = ordmap! {"bar" => 5};
2171 map.entry(&"foo").and_modify(|v| *v += 5).or_insert(1);
2172 assert_eq!(1, map[&"foo"]);
2173 map.entry(&"foo").and_modify(|v| *v += 5).or_insert(1);
2174 assert_eq!(6, map[&"foo"]);
2175 map.entry(&"bar").and_modify(|v| *v += 5).or_insert(1);
2176 assert_eq!(10, map[&"bar"]);
2177 assert_eq!(10, match map.entry(&"bar") {
2178 Entry::Occupied(entry) => entry.remove(),
2179 _ => panic!(),
2180 });
2181 assert!(!map.contains_key(&"bar"));
2182 }
2183
2184 #[test]
2185 fn match_string_keys_with_string_slices() {
2186 let mut map: OrdMap<String, i32> =
2187 From::from(ºap! { "foo" => &1, "bar" => &2, "baz" => &3 });
2188 assert_eq!(Some(&1), map.get("foo"));
2189 map = map.without("foo");
2190 assert_eq!(Some(3), map.remove("baz"));
2191 map["bar"] = 8;
2192 assert_eq!(8, map["bar"]);
2193 }
2194
2195 #[test]
2196 fn ranged_iter() {
2197 let map: OrdMap<i32, i32> = ordmap![1=>2, 2=>3, 3=>4, 4=>5, 5=>6, 7=>8];
2198 let range: Vec<(i32, i32)> = map.range(..).map(|(k, v)| (*k, *v)).collect();
2199 assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (7, 8)], range);
2200 let range: Vec<(i32, i32)> =
2201 map.range(..).rev().map(|(k, v)| (*k, *v)).collect();
2202 assert_eq!(vec![(7, 8), (5, 6), (4, 5), (3, 4), (2, 3), (1, 2)], range);
2203 let range: Vec<(i32, i32)> =
2204 map.range(2..5).map(|(k, v)| (*k, *v)).collect();
2205 assert_eq!(vec![(2, 3), (3, 4), (4, 5)], range);
2206 let range: Vec<(i32, i32)> =
2207 map.range(2..5).rev().map(|(k, v)| (*k, *v)).collect();
2208 assert_eq!(vec![(4, 5), (3, 4), (2, 3)], range);
2209 let range: Vec<(i32, i32)> =
2210 map.range(3..).map(|(k, v)| (*k, *v)).collect();
2211 assert_eq!(vec![(3, 4), (4, 5), (5, 6), (7, 8)], range);
2212 let range: Vec<(i32, i32)> =
2213 map.range(3..).rev().map(|(k, v)| (*k, *v)).collect();
2214 assert_eq!(vec![(7, 8), (5, 6), (4, 5), (3, 4)], range);
2215 let range: Vec<(i32, i32)> =
2216 map.range(..4).map(|(k, v)| (*k, *v)).collect();
2217 assert_eq!(vec![(1, 2), (2, 3), (3, 4)], range);
2218 let range: Vec<(i32, i32)> =
2219 map.range(..4).rev().map(|(k, v)| (*k, *v)).collect();
2220 assert_eq!(vec![(3, 4), (2, 3), (1, 2)], range);
2221 let range: Vec<(i32, i32)> =
2222 map.range(..=3).map(|(k, v)| (*k, *v)).collect();
2223 assert_eq!(vec![(1, 2), (2, 3), (3, 4)], range);
2224 let range: Vec<(i32, i32)> =
2225 map.range(..=3).rev().map(|(k, v)| (*k, *v)).collect();
2226 assert_eq!(vec![(3, 4), (2, 3), (1, 2)], range);
2227 let range: Vec<(i32, i32)> =
2228 map.range(..6).map(|(k, v)| (*k, *v)).collect();
2229 assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)], range);
2230 let range: Vec<(i32, i32)> =
2231 map.range(..=6).map(|(k, v)| (*k, *v)).collect();
2232 assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)], range);
2233 }
2234
2235 #[test]
2236 fn issue_124() {
2237 let mut map = OrdMap::new();
2238 let contents = include_str!("test-fixtures/issue_124.txt");
2239 for line in contents.lines() {
2240 if line.starts_with("insert ") {
2241 map.insert(line[7..].parse::<u32>().unwrap(), 0);
2242 }
2243 else if line.starts_with("remove ") {
2244 map.remove(&line[7..].parse::<u32>().unwrap());
2245 }
2246 }
2247 }
2248
2249 quickcheck! {
2250 fn length(input: btree_map::BTreeMap<i16, i16>) -> bool {
2251 let map: OrdMap<i32, i32> = OrdMap::from(input.clone());
2252 input.len() == map.len()
2253 }
2254
2255 fn order(input: btree_map::BTreeMap<i16, i16>) -> bool {
2256 let map: OrdMap<i32, i32> = OrdMap::from(input.clone());
2257 is_sorted(map.keys())
2258 }
2259
2260 fn overwrite_values(vec: Vec<(i16, i16)>) -> bool {
2261 if vec.len() == 0 {
2262 return true;
2263 }
2264
2265 let mut rng = thread_rng();
2266 let index_rand: i16 = rng.gen_range(0..vec.len()) as i16;
2267 let new_val: i16 = random();
2268 let map1 = OrdMap::from_iter(vec.clone());
2269 let map2 = map1.update(index_rand, new_val);
2270 let mut res = true;
2271 for (k, v) in map2 {
2272 if k == index_rand {
2273 res = res && v == new_val;
2274 } else {
2275 match map1.get(&k) {
2276 None => panic!("map1 didn't have key {:?}", k),
2277 Some(other_v) => {
2278 res = res && v == *other_v
2279 }
2280 }
2281 }
2282 }
2283 res
2284 }
2285
2286 fn delete_values(vec: Vec<(usize, usize)>) -> bool {
2287 if vec.len() == 0 {
2288 return true;
2289 }
2290
2291 let mut rng = thread_rng();
2292 let index = vec.choose(&mut rng).unwrap().0;
2293 let map1: OrdMap<usize, usize> = OrdMap::from_iter(vec.clone());
2294 let map2 = map1.without(&index);
2295 let mut res = true;
2296 res = res && map1.len() == map2.len() + 1;
2297 for k in map2.keys() {
2298 res = res && *k != index;
2299 }
2300 res
2301 }
2302
2303 fn insert_and_delete_values(
2304 input: OrdMap<usize,usize>,
2305 ops: Vec<(bool, usize, usize)>
2306 ) -> bool {
2307 let mut map = input.clone();
2308 let mut tree: btree_map::BTreeMap<usize, usize> = input.iter().map(|(k, v)| (*k, *v)).collect();
2309 for (ins, key, val) in &ops {
2310 if *ins {
2311 tree.insert(*key, *val);
2312 map = map.update(*key, *val)
2313 } else {
2314 tree.remove(key);
2315 map = map.without(key)
2316 }
2317 }
2318 map.iter().map(|(k, v)| (*k, *v)).eq(tree.iter().map(|(k, v)| (*k, *v)))
2319 }
2320
2321 fn insert_and_length(m: btree_map::BTreeMap<i16, i16>) -> bool {
2322 let mut map: OrdMap<i16, i16> = OrdMap::new();
2323 for (k, v) in m.iter() {
2324 map = map.update(*k, *v)
2325 }
2326 m.len() == map.len()
2327 }
2328
2329 fn from_iterator(m: BTreeMap<i16, i16>) -> bool {
2330 let map: OrdMap<i16, i16> =
2331 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2332 m.len() == map.len()
2333 }
2334
2335 fn iterate_over(m: BTreeMap<i16,i16>) -> bool {
2336 let map: OrdMap<i16, i16> =
2337 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2338 m.len() == map.iter().count()
2339 }
2340
2341 fn equality(m: BTreeMap<i16, i16>) -> bool {
2342 let map1: OrdMap<i16, i16> =
2343 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2344 let map2: OrdMap<i16, i16> =
2345 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2346 map1 == map2
2347 }
2348
2349 fn lookup(m: BTreeMap<i16, i16>) -> bool {
2350 let map: OrdMap<i16, i16> =
2351 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2352 for (k, v) in m.iter() {
2353 if Some(*v) != map.get(k).cloned() {
2354 return false;
2355 }
2356 }
2357 true
2358 }
2359
2360 fn remove(m: BTreeMap<i16, i16>) -> bool {
2361 let mut map: OrdMap<i16, i16> =
2362 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2363 let mut res = true;
2364 for k in m.keys() {
2365 let l = map.len();
2366 res = res && m.get(k).cloned() == map.get(k).cloned();
2367 map = map.without(k);
2368 res = res && None == map.get(k) && l - 1 == map.len();
2369 }
2370 res
2371 }
2372
2373 fn insert_mut(m: BTreeMap<i16, i16>) -> bool {
2374 let mut mut_map = OrdMap::new();
2375 let mut map = OrdMap::new();
2376 for (k, v) in m.iter() {
2377 map = map.update(*k, *v);
2378 mut_map.insert(*k, *v);
2379 }
2380 map == mut_map
2381 }
2382
2383 fn remove_mut(orig: BTreeMap<i16, i16>) -> bool {
2384 let mut map = orig.clone();
2385 let mut res = true;
2386 for key in orig.keys() {
2387 let len = map.len();
2388 res = res && orig.get(key) == map.get(key);
2389 res = res && orig.get(key).cloned() == map.remove(key);
2390 res = res && None == map.get(key);
2391 res = res && len - 1 == map.len();
2392 }
2393 res
2394 }
2395
2396 fn remove_alien(orig: BTreeMap<i16, i16>) -> bool {
2397 let mut map = OrdMap::<i16, i16>::from(orig.clone());
2398 let mut res = true;
2399 for key in orig.keys() {
2400 let len = map.len();
2401 res = orig.get(key) == map.get(key)
2402 && orig.get(key).cloned() == map.remove(key)
2403 && None == map.get(key)
2404 && len - 1 == map.len()
2405 }
2406 res
2407 }
2408
2409 fn delete_and_reinsert(
2410 input: BTreeMap<i16, i16>,
2411 index_rand: usize
2412 ) -> bool {
2413 if input.len() == 0 {
2414 return true;
2415 }
2416
2417 let index = *input.keys().nth(index_rand % input.len()).unwrap();
2418 let map1 = OrdMap::from_iter(input.clone());
2419 let (val, map2): (i16, _) = map1.extract(&index).unwrap();
2420 let map3 = map2.update(index, val);
2421 let mut res = true;
2422 for key in map2.keys() {
2423 res = res && *key != index;
2424 }
2425 res
2426 && map1.len() == map2.len() + 1
2427 && map1 == map3
2428 }
2429
2430 fn exact_size_iterator(m: OrdMap<i16, i16>) -> bool {
2431 let mut should_be = m.len();
2432 let mut it = m.iter();
2433 let mut res = true;
2434 loop {
2435 res = res && should_be == it.len();
2436 match it.next() {
2437 None => break,
2438 Some(_) => should_be -= 1,
2439 }
2440 }
2441 res && 0 == it.len()
2442 }
2443
2444 fn diff_all_values(a: Vec<(usize, usize)>, b: Vec<(usize, usize)>) -> bool {
2445 let a: OrdMap<usize, usize> = OrdMap::from(a);
2446 let b: OrdMap<usize, usize> = OrdMap::from(b);
2447
2448 let diff: Vec<_> = a.diff(&b).collect();
2449 let union = b.clone().union(a.clone());
2450 let expected: Vec<_> = union.iter().filter_map(|(k, v)| {
2451 if a.contains_key(&k) {
2452 if b.contains_key(&k) {
2453 let old = a.get(&k).unwrap();
2454 if old != v {
2455 Some(DiffItem::Update {
2456 old: (k, old),
2457 new: (k, v),
2458 })
2459 } else {
2460 None
2461 }
2462 } else {
2463 Some(DiffItem::Remove(k, v))
2464 }
2465 } else {
2466 Some(DiffItem::Add(k, v))
2467 }
2468 }).collect();
2469 expected == diff
2470 }
2471 }
2472}