1use std::borrow::Borrow;
21use std::cmp::Ordering;
22use std::collections;
23use std::fmt::{Debug, Error, Formatter};
24use std::hash::{BuildHasher, Hash, Hasher};
25use std::iter::{FromIterator, FusedIterator, Sum};
26use std::mem;
27use std::ops::{Add, Bound, Index, IndexMut, RangeBounds};
28
29use archery::{SharedPointer, SharedPointerKind};
30use equivalent::Comparable;
31
32use crate::hashmap::GenericHashMap;
33use crate::nodes::btree::{
34 ConsumingIter as NodeConsumingIter, Cursor, InsertAction, Iter as NodeIter, Node,
35};
36use crate::shared_ptr::DefaultSharedPtr;
37
38#[macro_export]
57macro_rules! ordmap {
58 () => { $crate::ordmap::OrdMap::new() };
59
60 ( $( $key:expr => $value:expr ),* ) => {{
61 let mut map = $crate::ordmap::OrdMap::new();
62 $({
63 map.insert($key, $value);
64 })*;
65 map
66 }};
67}
68
69pub type OrdMap<K, V> = GenericOrdMap<K, V, DefaultSharedPtr>;
74
75pub struct GenericOrdMap<K, V, P: SharedPointerKind> {
90 size: usize,
91 root: Option<Node<K, V, P>>,
92}
93
94impl<K, V, P: SharedPointerKind> GenericOrdMap<K, V, P> {
95 #[inline]
97 #[must_use]
98 pub fn new() -> Self {
99 GenericOrdMap {
100 size: 0,
101 root: None,
102 }
103 }
104
105 #[inline]
119 #[must_use]
120 pub fn unit(key: K, value: V) -> Self {
121 Self {
122 size: 1,
123 root: Some(Node::unit(key, value)),
124 }
125 }
126
127 #[inline]
144 #[must_use]
145 pub fn is_empty(&self) -> bool {
146 self.len() == 0
147 }
148
149 pub fn ptr_eq(&self, other: &Self) -> bool {
159 match (&self.root, &other.root) {
160 (Some(a), Some(b)) => a.ptr_eq(b),
161 (None, None) => true,
162 _ => false,
163 }
164 }
165
166 #[inline]
182 #[must_use]
183 pub fn len(&self) -> usize {
184 self.size
185 }
186
187 pub fn clear(&mut self) {
204 self.root = None;
205 self.size = 0;
206 }
207}
208
209impl<K, V, P> GenericOrdMap<K, V, P>
210where
211 K: Ord,
212 P: SharedPointerKind,
213{
214 #[must_use]
231 pub fn get_max(&self) -> Option<&(K, V)> {
232 self.root.as_ref().and_then(|root| root.max())
233 }
234
235 #[must_use]
252 pub fn get_min(&self) -> Option<&(K, V)> {
253 self.root.as_ref().and_then(|root| root.min())
254 }
255
256 #[must_use]
258 pub fn iter(&self) -> Iter<'_, K, V, P> {
259 Iter {
260 it: NodeIter::new::<_, K>(self.root.as_ref(), self.size, ..),
261 }
262 }
263
264 #[must_use]
266 pub fn range<R, Q>(&self, range: R) -> RangedIter<'_, K, V, P>
267 where
268 R: RangeBounds<Q>,
269 Q: Comparable<K> + ?Sized,
270 {
271 RangedIter {
272 it: NodeIter::new(self.root.as_ref(), self.size, range),
273 }
274 }
275
276 #[must_use]
278 pub fn keys(&self) -> Keys<'_, K, V, P> {
279 Keys { it: self.iter() }
280 }
281
282 #[must_use]
284 pub fn values(&self) -> Values<'_, K, V, P> {
285 Values { it: self.iter() }
286 }
287
288 #[must_use]
298 pub fn diff<'a, 'b>(&'a self, other: &'b Self) -> DiffIter<'a, 'b, K, V, P> {
299 let mut diff = DiffIter {
300 it1: Cursor::empty(),
301 it2: Cursor::empty(),
302 };
303 if self.ptr_eq(other) {
305 return diff;
306 }
307 diff.it1.init(self.root.as_ref());
308 diff.it2.init(other.root.as_ref());
309 diff.it1.seek_to_first();
310 diff.it2.seek_to_first();
311 diff
312 }
313
314 #[must_use]
330 pub fn get<Q>(&self, key: &Q) -> Option<&V>
331 where
332 Q: Comparable<K> + ?Sized,
333 {
334 self.root
335 .as_ref()
336 .and_then(|r| r.lookup(key).map(|(_, v)| v))
337 }
338
339 #[must_use]
355 pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
356 where
357 Q: Comparable<K> + ?Sized,
358 {
359 self.root
360 .as_ref()
361 .and_then(|r| r.lookup(key).map(|(k, v)| (k, v)))
362 }
363
364 #[must_use]
381 pub fn get_prev<Q>(&self, key: &Q) -> Option<(&K, &V)>
382 where
383 Q: Comparable<K> + ?Sized,
384 {
385 self.range::<_, Q>((Bound::Unbounded, Bound::Included(key)))
386 .next_back()
387 }
388
389 #[must_use]
406 pub fn get_next<Q>(&self, key: &Q) -> Option<(&K, &V)>
407 where
408 Q: Comparable<K> + ?Sized,
409 {
410 self.range::<_, Q>((Bound::Included(key), Bound::Unbounded))
411 .next()
412 }
413
414 #[must_use]
432 pub fn contains_key<Q>(&self, k: &Q) -> bool
433 where
434 Q: Comparable<K> + ?Sized,
435 {
436 self.get(k).is_some()
437 }
438
439 #[must_use]
447 pub fn is_submap_by<B, RM, F, P2>(&self, other: RM, mut cmp: F) -> bool
448 where
449 F: FnMut(&V, &B) -> bool,
450 RM: Borrow<GenericOrdMap<K, B, P2>>,
451 P2: SharedPointerKind,
452 {
453 self.iter()
454 .all(|(k, v)| other.borrow().get(k).map(|ov| cmp(v, ov)).unwrap_or(false))
455 }
456
457 #[must_use]
466 pub fn is_proper_submap_by<B, RM, F, P2>(&self, other: RM, cmp: F) -> bool
467 where
468 F: FnMut(&V, &B) -> bool,
469 RM: Borrow<GenericOrdMap<K, B, P2>>,
470 P2: SharedPointerKind,
471 {
472 self.len() != other.borrow().len() && self.is_submap_by(other, cmp)
473 }
474
475 #[must_use]
491 pub fn is_submap<RM>(&self, other: RM) -> bool
492 where
493 V: PartialEq,
494 RM: Borrow<Self>,
495 {
496 self.is_submap_by(other.borrow(), PartialEq::eq)
497 }
498
499 #[must_use]
520 pub fn is_proper_submap<RM>(&self, other: RM) -> bool
521 where
522 V: PartialEq,
523 RM: Borrow<Self>,
524 {
525 self.is_proper_submap_by(other.borrow(), PartialEq::eq)
526 }
527
528 #[cfg(any(test, fuzzing))]
530 #[allow(unreachable_pub)]
531 pub fn check_sane(&self)
532 where
533 K: std::fmt::Debug,
534 V: std::fmt::Debug,
535 {
536 let size = self
537 .root
538 .as_ref()
539 .map(|root| root.check_sane(true))
540 .unwrap_or(0);
541 assert_eq!(size, self.size);
542 }
543}
544
545impl<K, V, P> GenericOrdMap<K, V, P>
546where
547 K: Ord + Clone,
548 V: Clone,
549 P: SharedPointerKind,
550{
551 #[must_use]
570 pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
571 where
572 Q: Comparable<K> + ?Sized,
573 {
574 let root = self.root.as_mut()?;
575 root.lookup_mut(key).map(|(_, v)| v)
576 }
577
578 #[must_use]
594 pub fn get_key_value_mut<Q>(&mut self, key: &Q) -> Option<(&K, &mut V)>
595 where
596 Q: Comparable<K> + ?Sized,
597 {
598 self.root.as_mut()?.lookup_mut(key)
599 }
600
601 #[must_use]
621 pub fn get_prev_mut<Q>(&mut self, key: &Q) -> Option<(&K, &mut V)>
622 where
623 Q: Comparable<K> + ?Sized,
624 {
625 let prev = self.get_prev(key)?.0.clone();
626 let root = self.root.as_mut()?;
627 root.lookup_mut(prev.borrow())
628 }
629
630 #[must_use]
650 pub fn get_next_mut<Q>(&mut self, key: &Q) -> Option<(&K, &mut V)>
651 where
652 Q: Comparable<K> + ?Sized,
653 {
654 let next = self.get_next(key)?.0.clone();
655 let root = self.root.as_mut()?;
656 root.lookup_mut(next.borrow())
657 }
658
659 #[inline]
686 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
687 self.insert_key_value(key, value).map(|(_, v)| v)
688 }
689
690 #[inline]
699 pub(crate) fn insert_key_value(&mut self, key: K, value: V) -> Option<(K, V)> {
700 let root = self.root.get_or_insert_with(Node::default);
701 match root.insert(key, value) {
702 InsertAction::Replaced(old_key, old_value) => return Some((old_key, old_value)),
703 InsertAction::Inserted => (),
704 InsertAction::Split(separator, right) => {
705 let left = mem::take(root);
706 *root = Node::new_from_split(left, separator, right);
707 }
708 }
709 self.size += 1;
710 None
711 }
712
713 #[inline]
730 pub fn remove<Q>(&mut self, k: &Q) -> Option<V>
731 where
732 Q: Comparable<K> + ?Sized,
733 {
734 self.remove_with_key(k).map(|(_, v)| v)
735 }
736
737 pub fn remove_with_key<Q>(&mut self, k: &Q) -> Option<(K, V)>
742 where
743 Q: Comparable<K> + ?Sized,
744 {
745 let root = self.root.as_mut()?;
746 let mut removed = None;
747 if root.remove(k, &mut removed) {
748 if let Node::Branch(branch) = root {
749 if let Some(child) = SharedPointer::make_mut(branch).pop_single_child() {
750 self.root = Some(child);
751 }
752 }
753 }
756 self.size -= removed.is_some() as usize;
757 removed
758 }
759
760 #[must_use]
780 pub fn update(&self, key: K, value: V) -> Self {
781 let mut out = self.clone();
782 out.insert(key, value);
783 out
784 }
785
786 #[must_use]
795 pub fn update_with<F>(self, k: K, v: V, f: F) -> Self
796 where
797 F: FnOnce(V, V) -> V,
798 {
799 self.update_with_key(k, v, |_, v1, v2| f(v1, v2))
800 }
801
802 #[must_use]
811 pub fn update_with_key<F>(self, k: K, v: V, f: F) -> Self
812 where
813 F: FnOnce(&K, V, V) -> V,
814 {
815 match self.extract_with_key(&k) {
816 None => self.update(k, v),
817 Some((_, v2, m)) => {
818 let out_v = f(&k, v2, v);
819 m.update(k, out_v)
820 }
821 }
822 }
823
824 #[must_use]
834 pub fn update_lookup_with_key<F>(self, k: K, v: V, f: F) -> (Option<V>, Self)
835 where
836 F: FnOnce(&K, &V, V) -> V,
837 {
838 match self.extract_with_key(&k) {
839 None => (None, self.update(k, v)),
840 Some((_, v2, m)) => {
841 let out_v = f(&k, &v2, v);
842 (Some(v2), m.update(k, out_v))
843 }
844 }
845 }
846
847 #[must_use]
860 pub fn alter<F>(&self, f: F, k: K) -> Self
861 where
862 F: FnOnce(Option<V>) -> Option<V>,
863 {
864 let pop = self.extract_with_key(&k);
865 match (f(pop.as_ref().map(|(_, v, _)| v.clone())), pop) {
866 (None, None) => self.clone(),
867 (Some(v), None) => self.update(k, v),
868 (None, Some((_, _, m))) => m,
869 (Some(v), Some((_, _, m))) => m.update(k, v),
870 }
871 }
872
873 #[must_use]
877 pub fn without<Q>(&self, k: &Q) -> Self
878 where
879 Q: Comparable<K> + ?Sized,
880 {
881 self.extract(k)
882 .map(|(_, m)| m)
883 .unwrap_or_else(|| self.clone())
884 }
885
886 #[must_use]
891 pub fn extract<Q>(&self, k: &Q) -> Option<(V, Self)>
892 where
893 Q: Comparable<K> + ?Sized,
894 {
895 self.extract_with_key(k).map(|(_, v, m)| (v, m))
896 }
897
898 #[must_use]
903 pub fn extract_with_key<Q>(&self, k: &Q) -> Option<(K, V, Self)>
904 where
905 Q: Comparable<K> + ?Sized,
906 {
907 let mut out = self.clone();
908 let result = out.remove_with_key(k);
909 result.map(|(k, v)| (k, v, out))
910 }
911
912 #[inline]
928 #[must_use]
929 pub fn union(mut self, mut other: Self) -> Self {
930 if self.len() >= other.len() {
933 for (k, v) in other {
934 self.entry(k).or_insert(v);
935 }
936 self
937 } else {
938 for (k, v) in self {
939 other.insert(k, v);
940 }
941 other
942 }
943 }
944
945 #[inline]
955 #[must_use]
956 pub fn union_with<F>(self, other: Self, mut f: F) -> Self
957 where
958 F: FnMut(V, V) -> V,
959 {
960 self.union_with_key(other, |_, v1, v2| f(v1, v2))
961 }
962
963 #[must_use]
988 pub fn union_with_key<F>(self, other: Self, mut f: F) -> Self
989 where
990 F: FnMut(&K, V, V) -> V,
991 {
992 if self.len() >= other.len() {
993 self.union_with_key_inner(other, f)
994 } else {
995 other.union_with_key_inner(self, |key, other_value, self_value| {
996 f(key, self_value, other_value)
997 })
998 }
999 }
1000
1001 fn union_with_key_inner<F>(mut self, other: Self, mut f: F) -> Self
1002 where
1003 F: FnMut(&K, V, V) -> V,
1004 {
1005 for (key, right_value) in other {
1006 match self.remove(&key) {
1007 None => {
1008 self.insert(key, right_value);
1009 }
1010 Some(left_value) => {
1011 let final_value = f(&key, left_value, right_value);
1012 self.insert(key, final_value);
1013 }
1014 }
1015 }
1016 self
1017 }
1018
1019 #[must_use]
1035 pub fn unions<I>(i: I) -> Self
1036 where
1037 I: IntoIterator<Item = Self>,
1038 {
1039 i.into_iter().fold(Self::default(), Self::union)
1040 }
1041
1042 #[must_use]
1053 pub fn unions_with<I, F>(i: I, f: F) -> Self
1054 where
1055 I: IntoIterator<Item = Self>,
1056 F: Fn(V, V) -> V,
1057 {
1058 i.into_iter()
1059 .fold(Self::default(), |a, b| a.union_with(b, &f))
1060 }
1061
1062 #[must_use]
1074 pub fn unions_with_key<I, F>(i: I, f: F) -> Self
1075 where
1076 I: IntoIterator<Item = Self>,
1077 F: Fn(&K, V, V) -> V,
1078 {
1079 i.into_iter()
1080 .fold(Self::default(), |a, b| a.union_with_key(b, &f))
1081 }
1082
1083 #[deprecated(
1104 since = "2.0.1",
1105 note = "to avoid conflicting behaviors between std and imbl, the `difference` alias for `symmetric_difference` will be removed."
1106 )]
1107 #[inline]
1108 #[must_use]
1109 pub fn difference(self, other: Self) -> Self {
1110 self.symmetric_difference(other)
1111 }
1112
1113 #[inline]
1129 #[must_use]
1130 pub fn symmetric_difference(self, other: Self) -> Self {
1131 self.symmetric_difference_with_key(other, |_, _, _| None)
1132 }
1133
1134 #[deprecated(
1144 since = "2.0.1",
1145 note = "to avoid conflicting behaviors between std and imbl, the `difference_with` alias for `symmetric_difference_with` will be removed."
1146 )]
1147 #[inline]
1148 #[must_use]
1149 pub fn difference_with<F>(self, other: Self, f: F) -> Self
1150 where
1151 F: FnMut(V, V) -> Option<V>,
1152 {
1153 self.symmetric_difference_with(other, f)
1154 }
1155
1156 #[inline]
1161 #[must_use]
1162 pub fn symmetric_difference_with<F>(self, other: Self, mut f: F) -> Self
1163 where
1164 F: FnMut(V, V) -> Option<V>,
1165 {
1166 self.symmetric_difference_with_key(other, |_, a, b| f(a, b))
1167 }
1168
1169 #[deprecated(
1194 since = "2.0.1",
1195 note = "to avoid conflicting behaviors between std and imbl, the `difference_with_key` alias for `symmetric_difference_with_key` will be removed."
1196 )]
1197 #[must_use]
1198 pub fn difference_with_key<F>(self, other: Self, f: F) -> Self
1199 where
1200 F: FnMut(&K, V, V) -> Option<V>,
1201 {
1202 self.symmetric_difference_with_key(other, f)
1203 }
1204
1205 #[must_use]
1225 pub fn symmetric_difference_with_key<F>(mut self, other: Self, mut f: F) -> Self
1226 where
1227 F: FnMut(&K, V, V) -> Option<V>,
1228 {
1229 let mut out = Self::default();
1230 for (key, right_value) in other {
1231 match self.remove(&key) {
1232 None => {
1233 out.insert(key, right_value);
1234 }
1235 Some(left_value) => {
1236 if let Some(final_value) = f(&key, left_value, right_value) {
1237 out.insert(key, final_value);
1238 }
1239 }
1240 }
1241 }
1242 out.union(self)
1243 }
1244
1245 #[inline]
1261 #[must_use]
1262 pub fn relative_complement(mut self, other: Self) -> Self {
1263 for (key, _) in other {
1264 let _ = self.remove(&key);
1265 }
1266 self
1267 }
1268
1269 #[inline]
1285 #[must_use]
1286 pub fn intersection(self, other: Self) -> Self {
1287 self.intersection_with_key(other, |_, v, _| v)
1288 }
1289
1290 #[inline]
1296 #[must_use]
1297 pub fn intersection_with<B, C, F, P2, P3>(
1298 self,
1299 other: GenericOrdMap<K, B, P2>,
1300 mut f: F,
1301 ) -> GenericOrdMap<K, C, P3>
1302 where
1303 B: Clone,
1304 C: Clone,
1305 F: FnMut(V, B) -> C,
1306 P2: SharedPointerKind,
1307 P3: SharedPointerKind,
1308 {
1309 self.intersection_with_key(other, |_, v1, v2| f(v1, v2))
1310 }
1311
1312 #[must_use]
1332 pub fn intersection_with_key<B, C, F, P2, P3>(
1333 mut self,
1334 other: GenericOrdMap<K, B, P2>,
1335 mut f: F,
1336 ) -> GenericOrdMap<K, C, P3>
1337 where
1338 B: Clone,
1339 C: Clone,
1340 F: FnMut(&K, V, B) -> C,
1341 P2: SharedPointerKind,
1342 P3: SharedPointerKind,
1343 {
1344 let mut out = GenericOrdMap::<K, C, P3>::default();
1345 for (key, right_value) in other {
1346 match self.remove(&key) {
1347 None => (),
1348 Some(left_value) => {
1349 let result = f(&key, left_value, right_value);
1350 out.insert(key, result);
1351 }
1352 }
1353 }
1354 out
1355 }
1356
1357 #[must_use]
1363 pub fn split<Q>(&self, split: &Q) -> (Self, Self)
1364 where
1365 Q: Comparable<K> + ?Sized,
1366 {
1367 let (l, _, r) = self.split_lookup(split);
1368 (l, r)
1369 }
1370
1371 #[must_use]
1377 pub fn split_lookup<Q>(&self, split: &Q) -> (Self, Option<V>, Self)
1378 where
1379 Q: Comparable<K> + ?Sized,
1380 {
1381 self.iter().fold(
1383 (GenericOrdMap::new(), None, GenericOrdMap::new()),
1384 |(l, m, r), (k, v)| match split.compare(k).reverse() {
1385 Ordering::Less => (l.update(k.clone(), v.clone()), m, r),
1386 Ordering::Equal => (l, Some(v.clone()), r),
1387 Ordering::Greater => (l, m, r.update(k.clone(), v.clone())),
1388 },
1389 )
1390 }
1391
1392 #[must_use]
1395 pub fn take(&self, n: usize) -> Self {
1396 self.iter()
1397 .take(n)
1398 .map(|(k, v)| (k.clone(), v.clone()))
1399 .collect()
1400 }
1401
1402 #[must_use]
1405 pub fn skip(&self, n: usize) -> Self {
1406 self.iter()
1407 .skip(n)
1408 .map(|(k, v)| (k.clone(), v.clone()))
1409 .collect()
1410 }
1411
1412 #[must_use]
1415 pub fn without_min(&self) -> (Option<V>, Self) {
1416 let (pop, next) = self.without_min_with_key();
1417 (pop.map(|(_, v)| v), next)
1418 }
1419
1420 #[must_use]
1423 pub fn without_min_with_key(&self) -> (Option<(K, V)>, Self) {
1424 match self.get_min() {
1425 None => (None, self.clone()),
1426 Some((k, _)) => {
1427 let (key, value, next) = self.extract_with_key(k).unwrap();
1428 (Some((key, value)), next)
1429 }
1430 }
1431 }
1432
1433 #[must_use]
1436 pub fn without_max(&self) -> (Option<V>, Self) {
1437 let (pop, next) = self.without_max_with_key();
1438 (pop.map(|(_, v)| v), next)
1439 }
1440
1441 #[must_use]
1444 pub fn without_max_with_key(&self) -> (Option<(K, V)>, Self) {
1445 match self.get_max() {
1446 None => (None, self.clone()),
1447 Some((k, _)) => {
1448 let (key, value, next) = self.extract_with_key(k).unwrap();
1449 (Some((key, value)), next)
1450 }
1451 }
1452 }
1453
1454 #[must_use]
1460 pub fn entry(&mut self, key: K) -> Entry<'_, K, V, P> {
1461 if self.contains_key(&key) {
1462 Entry::Occupied(OccupiedEntry { map: self, key })
1463 } else {
1464 Entry::Vacant(VacantEntry { map: self, key })
1465 }
1466 }
1467}
1468
1469pub enum Entry<'a, K, V, P>
1473where
1474 K: Ord + Clone,
1475 V: Clone,
1476 P: SharedPointerKind,
1477{
1478 Occupied(OccupiedEntry<'a, K, V, P>),
1480 Vacant(VacantEntry<'a, K, V, P>),
1482}
1483
1484impl<'a, K, V, P> Entry<'a, K, V, P>
1485where
1486 K: Ord + Clone,
1487 V: Clone,
1488 P: SharedPointerKind,
1489{
1490 pub fn or_insert(self, default: V) -> &'a mut V {
1493 self.or_insert_with(|| default)
1494 }
1495
1496 pub fn or_insert_with<F>(self, default: F) -> &'a mut V
1500 where
1501 F: FnOnce() -> V,
1502 {
1503 match self {
1504 Entry::Occupied(entry) => entry.into_mut(),
1505 Entry::Vacant(entry) => entry.insert(default()),
1506 }
1507 }
1508
1509 pub fn or_default(self) -> &'a mut V
1512 where
1513 V: Default,
1514 {
1515 #[allow(clippy::unwrap_or_default)]
1516 self.or_insert_with(Default::default)
1517 }
1518
1519 #[must_use]
1521 pub fn key(&self) -> &K {
1522 match self {
1523 Entry::Occupied(entry) => entry.key(),
1524 Entry::Vacant(entry) => entry.key(),
1525 }
1526 }
1527
1528 #[must_use]
1531 pub fn and_modify<F>(mut self, f: F) -> Self
1532 where
1533 F: FnOnce(&mut V),
1534 {
1535 match &mut self {
1536 Entry::Occupied(ref mut entry) => f(entry.get_mut()),
1537 Entry::Vacant(_) => (),
1538 }
1539 self
1540 }
1541}
1542
1543pub struct OccupiedEntry<'a, K, V, P>
1545where
1546 K: Ord + Clone,
1547 V: Clone,
1548 P: SharedPointerKind,
1549{
1550 map: &'a mut GenericOrdMap<K, V, P>,
1551 key: K,
1552}
1553
1554impl<'a, K, V, P> OccupiedEntry<'a, K, V, P>
1555where
1556 K: 'a + Ord + Clone,
1557 V: 'a + Clone,
1558 P: SharedPointerKind,
1559{
1560 #[must_use]
1562 pub fn key(&self) -> &K {
1563 &self.key
1564 }
1565
1566 pub fn remove_entry(self) -> (K, V) {
1568 self.map
1569 .remove_with_key(&self.key)
1570 .expect("ordmap::OccupiedEntry::remove_entry: key has vanished!")
1571 }
1572
1573 #[must_use]
1575 pub fn get(&self) -> &V {
1576 self.map.get(&self.key).unwrap()
1577 }
1578
1579 #[must_use]
1581 pub fn get_mut(&mut self) -> &mut V {
1582 self.map.get_mut(&self.key).unwrap()
1583 }
1584
1585 #[must_use]
1587 pub fn into_mut(self) -> &'a mut V {
1588 self.map.get_mut(&self.key).unwrap()
1589 }
1590
1591 pub fn insert(&mut self, value: V) -> V {
1593 mem::replace(self.get_mut(), value)
1594 }
1595
1596 pub fn remove(self) -> V {
1598 self.remove_entry().1
1599 }
1600}
1601
1602pub struct VacantEntry<'a, K, V, P>
1604where
1605 K: Ord + Clone,
1606 V: Clone,
1607 P: SharedPointerKind,
1608{
1609 map: &'a mut GenericOrdMap<K, V, P>,
1610 key: K,
1611}
1612
1613impl<'a, K, V, P> VacantEntry<'a, K, V, P>
1614where
1615 K: 'a + Ord + Clone,
1616 V: 'a + Clone,
1617 P: SharedPointerKind,
1618{
1619 #[must_use]
1621 pub fn key(&self) -> &K {
1622 &self.key
1623 }
1624
1625 #[must_use]
1627 pub fn into_key(self) -> K {
1628 self.key
1629 }
1630
1631 pub fn insert(self, value: V) -> &'a mut V {
1633 self.map.insert(self.key.clone(), value);
1634 self.map.get_mut(&self.key).unwrap()
1636 }
1637}
1638
1639impl<K, V, P: SharedPointerKind> Clone for GenericOrdMap<K, V, P> {
1642 #[inline]
1646 fn clone(&self) -> Self {
1647 GenericOrdMap {
1648 size: self.size,
1649 root: self.root.clone(),
1650 }
1651 }
1652}
1653
1654impl<K, V, P> PartialEq for GenericOrdMap<K, V, P>
1656where
1657 K: Ord + PartialEq,
1658 V: PartialEq,
1659 P: SharedPointerKind,
1660{
1661 fn eq(&self, other: &GenericOrdMap<K, V, P>) -> bool {
1662 self.len() == other.len() && self.diff(other).next().is_none()
1663 }
1664}
1665
1666impl<K: Ord + Eq, V: Eq, P: SharedPointerKind> Eq for GenericOrdMap<K, V, P> {}
1667
1668impl<K, V, P> PartialOrd for GenericOrdMap<K, V, P>
1670where
1671 K: Ord,
1672 V: PartialOrd,
1673 P: SharedPointerKind,
1674{
1675 fn partial_cmp(&self, other: &GenericOrdMap<K, V, P>) -> Option<Ordering> {
1676 self.iter().partial_cmp(other.iter())
1677 }
1678}
1679
1680impl<K, V, P> Ord for GenericOrdMap<K, V, P>
1681where
1682 K: Ord,
1683 V: Ord,
1684 P: SharedPointerKind,
1685{
1686 fn cmp(&self, other: &Self) -> Ordering {
1687 self.iter().cmp(other.iter())
1688 }
1689}
1690
1691impl<K, V, P> Hash for GenericOrdMap<K, V, P>
1692where
1693 K: Ord + Hash,
1694 V: Hash,
1695 P: SharedPointerKind,
1696{
1697 fn hash<H>(&self, state: &mut H)
1698 where
1699 H: Hasher,
1700 {
1701 for i in self.iter() {
1702 i.hash(state);
1703 }
1704 }
1705}
1706
1707impl<K, V, P: SharedPointerKind> Default for GenericOrdMap<K, V, P> {
1708 fn default() -> Self {
1709 Self::new()
1710 }
1711}
1712
1713impl<K, V, P> Add for &GenericOrdMap<K, V, P>
1714where
1715 K: Ord + Clone,
1716 V: Clone,
1717 P: SharedPointerKind,
1718{
1719 type Output = GenericOrdMap<K, V, P>;
1720
1721 fn add(self, other: Self) -> Self::Output {
1722 self.clone().union(other.clone())
1723 }
1724}
1725
1726impl<K, V, P> Add for GenericOrdMap<K, V, P>
1727where
1728 K: Ord + Clone,
1729 V: Clone,
1730 P: SharedPointerKind,
1731{
1732 type Output = GenericOrdMap<K, V, P>;
1733
1734 fn add(self, other: Self) -> Self::Output {
1735 self.union(other)
1736 }
1737}
1738
1739impl<K, V, P> Sum for GenericOrdMap<K, V, P>
1740where
1741 K: Ord + Clone,
1742 V: Clone,
1743 P: SharedPointerKind,
1744{
1745 fn sum<I>(it: I) -> Self
1746 where
1747 I: Iterator<Item = Self>,
1748 {
1749 it.fold(Self::default(), |a, b| a + b)
1750 }
1751}
1752
1753impl<K, V, RK, RV, P> Extend<(RK, RV)> for GenericOrdMap<K, V, P>
1754where
1755 K: Ord + Clone + From<RK>,
1756 V: Clone + From<RV>,
1757 P: SharedPointerKind,
1758{
1759 fn extend<I>(&mut self, iter: I)
1760 where
1761 I: IntoIterator<Item = (RK, RV)>,
1762 {
1763 for (key, value) in iter {
1764 self.insert(From::from(key), From::from(value));
1765 }
1766 }
1767}
1768
1769impl<Q, K, V, P: SharedPointerKind> Index<&Q> for GenericOrdMap<K, V, P>
1770where
1771 Q: Comparable<K> + ?Sized,
1772 K: Ord,
1773{
1774 type Output = V;
1775
1776 fn index(&self, key: &Q) -> &Self::Output {
1777 match self.get(key) {
1778 None => panic!("OrdMap::index: invalid key"),
1779 Some(value) => value,
1780 }
1781 }
1782}
1783
1784impl<Q, K, V, P> IndexMut<&Q> for GenericOrdMap<K, V, P>
1785where
1786 Q: Comparable<K> + ?Sized,
1787 K: Ord + Clone,
1788 V: Clone,
1789 P: SharedPointerKind,
1790{
1791 fn index_mut(&mut self, key: &Q) -> &mut Self::Output {
1792 match self.get_mut(key) {
1793 None => panic!("OrdMap::index: invalid key"),
1794 Some(value) => value,
1795 }
1796 }
1797}
1798
1799impl<K, V, P> Debug for GenericOrdMap<K, V, P>
1800where
1801 K: Ord + Debug,
1802 V: Debug,
1803 P: SharedPointerKind,
1804{
1805 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
1806 let mut d = f.debug_map();
1807 for (k, v) in self.iter() {
1808 d.entry(k, v);
1809 }
1810 d.finish()
1811 }
1812}
1813
1814pub struct Iter<'a, K, V, P: SharedPointerKind> {
1818 it: NodeIter<'a, K, V, P>,
1819}
1820
1821impl<'a, K, V, P: SharedPointerKind> Clone for Iter<'a, K, V, P> {
1823 fn clone(&self) -> Self {
1824 Iter {
1825 it: self.it.clone(),
1826 }
1827 }
1828}
1829
1830impl<'a, K, V, P> Iterator for Iter<'a, K, V, P>
1831where
1832 P: SharedPointerKind,
1833{
1834 type Item = (&'a K, &'a V);
1835
1836 fn next(&mut self) -> Option<Self::Item> {
1837 self.it.next()
1838 }
1839
1840 fn size_hint(&self) -> (usize, Option<usize>) {
1843 self.it.size_hint()
1844 }
1845}
1846
1847impl<'a, K, V, P> DoubleEndedIterator for Iter<'a, K, V, P>
1848where
1849 P: SharedPointerKind,
1850{
1851 fn next_back(&mut self) -> Option<Self::Item> {
1852 self.it.next_back()
1853 }
1854}
1855
1856impl<'a, K, V, P> ExactSizeIterator for Iter<'a, K, V, P> where P: SharedPointerKind {}
1857impl<'a, K, V, P> FusedIterator for Iter<'a, K, V, P> where P: SharedPointerKind {}
1858
1859#[derive(Debug)]
1861pub struct RangedIter<'a, K, V, P: SharedPointerKind> {
1862 it: NodeIter<'a, K, V, P>,
1863}
1864
1865impl<'a, K, V, P: SharedPointerKind> Clone for RangedIter<'a, K, V, P> {
1867 fn clone(&self) -> Self {
1868 RangedIter {
1869 it: self.it.clone(),
1870 }
1871 }
1872}
1873
1874impl<'a, K, V, P> Iterator for RangedIter<'a, K, V, P>
1875where
1876 P: SharedPointerKind,
1877{
1878 type Item = (&'a K, &'a V);
1879
1880 fn next(&mut self) -> Option<Self::Item> {
1881 self.it.next()
1882 }
1883
1884 fn size_hint(&self) -> (usize, Option<usize>) {
1885 self.it.size_hint()
1886 }
1887}
1888
1889impl<'a, K, V, P> DoubleEndedIterator for RangedIter<'a, K, V, P>
1890where
1891 P: SharedPointerKind,
1892{
1893 fn next_back(&mut self) -> Option<Self::Item> {
1894 self.it.next_back()
1895 }
1896}
1897impl<'a, K, V, P> FusedIterator for RangedIter<'a, K, V, P> where P: SharedPointerKind {}
1898
1899pub struct DiffIter<'a, 'b, K, V, P: SharedPointerKind> {
1901 it1: Cursor<'a, K, V, P>,
1902 it2: Cursor<'b, K, V, P>,
1903}
1904
1905#[derive(PartialEq, Eq, Debug)]
1907pub enum DiffItem<'a, 'b, K, V> {
1908 Add(&'b K, &'b V),
1910 Update {
1912 old: (&'a K, &'a V),
1914 new: (&'b K, &'b V),
1916 },
1917 Remove(&'a K, &'a V),
1919}
1920
1921impl<'a, 'b, K, V, P> Iterator for DiffIter<'a, 'b, K, V, P>
1922where
1923 K: Ord,
1924 V: PartialEq,
1925 P: SharedPointerKind,
1926{
1927 type Item = DiffItem<'a, 'b, K, V>;
1928
1929 fn next(&mut self) -> Option<Self::Item> {
1930 loop {
1931 match (self.it1.peek(), self.it2.peek()) {
1932 (Some((k1, v1)), Some((k2, v2))) => match k1.cmp(k2) {
1933 Ordering::Less => {
1934 self.it1.next();
1935 break Some(DiffItem::Remove(k1, v1));
1936 }
1937 Ordering::Equal => {
1938 self.it1.advance_skipping_shared(&mut self.it2);
1940 if v1 != v2 {
1941 break Some(DiffItem::Update {
1942 old: (k1, v1),
1943 new: (k2, v2),
1944 });
1945 }
1946 }
1947 Ordering::Greater => {
1948 self.it2.next();
1949 break Some(DiffItem::Add(k2, v2));
1950 }
1951 },
1952 (Some((k1, v1)), None) => {
1953 self.it1.next();
1954 break Some(DiffItem::Remove(k1, v1));
1955 }
1956 (None, Some((k2, v2))) => {
1957 self.it2.next();
1958 break Some(DiffItem::Add(k2, v2));
1959 }
1960 (None, None) => break None,
1961 }
1962 }
1963 }
1964}
1965
1966impl<'a, 'b, K, V, P> FusedIterator for DiffIter<'a, 'b, K, V, P>
1967where
1968 K: Ord,
1969 V: PartialEq,
1970 P: SharedPointerKind,
1971{
1972}
1973
1974pub struct Keys<'a, K, V, P: SharedPointerKind> {
1976 it: Iter<'a, K, V, P>,
1977}
1978
1979impl<'a, K, V, P> Iterator for Keys<'a, K, V, P>
1980where
1981 K: 'a + Ord,
1982 V: 'a,
1983 P: SharedPointerKind,
1984{
1985 type Item = &'a K;
1986
1987 fn next(&mut self) -> Option<Self::Item> {
1988 self.it.next().map(|(k, _)| k)
1989 }
1990
1991 fn size_hint(&self) -> (usize, Option<usize>) {
1992 self.it.size_hint()
1993 }
1994}
1995
1996impl<'a, K, V, P> DoubleEndedIterator for Keys<'a, K, V, P>
1997where
1998 K: 'a + Ord,
1999 V: 'a,
2000 P: SharedPointerKind,
2001{
2002 fn next_back(&mut self) -> Option<Self::Item> {
2003 match self.it.next_back() {
2004 None => None,
2005 Some((k, _)) => Some(k),
2006 }
2007 }
2008}
2009
2010impl<'a, K, V, P> ExactSizeIterator for Keys<'a, K, V, P>
2011where
2012 K: 'a + Ord,
2013 V: 'a,
2014 P: SharedPointerKind,
2015{
2016}
2017
2018impl<'a, K, V, P> FusedIterator for Keys<'a, K, V, P>
2019where
2020 K: 'a + Ord,
2021 V: 'a,
2022 P: SharedPointerKind,
2023{
2024}
2025
2026pub struct Values<'a, K, V, P: SharedPointerKind> {
2028 it: Iter<'a, K, V, P>,
2029}
2030
2031impl<'a, K, V, P> Iterator for Values<'a, K, V, P>
2032where
2033 K: 'a + Ord,
2034 V: 'a,
2035 P: SharedPointerKind,
2036{
2037 type Item = &'a V;
2038
2039 fn next(&mut self) -> Option<Self::Item> {
2040 self.it.next().map(|(_, v)| v)
2041 }
2042
2043 fn size_hint(&self) -> (usize, Option<usize>) {
2044 self.it.size_hint()
2045 }
2046}
2047
2048impl<'a, K, V, P> DoubleEndedIterator for Values<'a, K, V, P>
2049where
2050 K: 'a + Ord,
2051 V: 'a,
2052 P: SharedPointerKind,
2053{
2054 fn next_back(&mut self) -> Option<Self::Item> {
2055 match self.it.next_back() {
2056 None => None,
2057 Some((_, v)) => Some(v),
2058 }
2059 }
2060}
2061
2062impl<'a, K, V, P> FusedIterator for Values<'a, K, V, P>
2063where
2064 K: 'a + Ord,
2065 V: 'a,
2066 P: SharedPointerKind,
2067{
2068}
2069
2070impl<'a, K, V, P> ExactSizeIterator for Values<'a, K, V, P>
2071where
2072 K: 'a + Ord,
2073 V: 'a,
2074 P: SharedPointerKind,
2075{
2076}
2077
2078impl<K, V, RK, RV, P> FromIterator<(RK, RV)> for GenericOrdMap<K, V, P>
2079where
2080 K: Ord + Clone + From<RK>,
2081 V: Clone + From<RV>,
2082 P: SharedPointerKind,
2083{
2084 fn from_iter<T>(i: T) -> Self
2085 where
2086 T: IntoIterator<Item = (RK, RV)>,
2087 {
2088 let mut m = GenericOrdMap::default();
2089 for (k, v) in i {
2090 m.insert(From::from(k), From::from(v));
2091 }
2092 m
2093 }
2094}
2095
2096impl<'a, K, V, P> IntoIterator for &'a GenericOrdMap<K, V, P>
2097where
2098 K: Ord,
2099 P: SharedPointerKind,
2100{
2101 type Item = (&'a K, &'a V);
2102 type IntoIter = Iter<'a, K, V, P>;
2103
2104 fn into_iter(self) -> Self::IntoIter {
2105 self.iter()
2106 }
2107}
2108
2109impl<K, V, P> IntoIterator for GenericOrdMap<K, V, P>
2110where
2111 K: Clone,
2112 V: Clone,
2113 P: SharedPointerKind,
2114{
2115 type Item = (K, V);
2116 type IntoIter = ConsumingIter<K, V, P>;
2117
2118 fn into_iter(self) -> Self::IntoIter {
2119 ConsumingIter {
2120 it: NodeConsumingIter::new(self.root, self.size),
2121 }
2122 }
2123}
2124
2125pub struct ConsumingIter<K, V, P: SharedPointerKind> {
2127 it: NodeConsumingIter<K, V, P>,
2128}
2129
2130impl<K, V, P> Iterator for ConsumingIter<K, V, P>
2131where
2132 K: Clone,
2133 V: Clone,
2134 P: SharedPointerKind,
2135{
2136 type Item = (K, V);
2137 fn next(&mut self) -> Option<Self::Item> {
2138 self.it.next()
2139 }
2140 fn size_hint(&self) -> (usize, Option<usize>) {
2141 self.it.size_hint()
2142 }
2143}
2144
2145impl<K: Clone, V: Clone, P: SharedPointerKind> DoubleEndedIterator for ConsumingIter<K, V, P> {
2146 fn next_back(&mut self) -> Option<Self::Item> {
2147 self.it.next_back()
2148 }
2149}
2150
2151impl<K, V, P> ExactSizeIterator for ConsumingIter<K, V, P>
2152where
2153 K: Clone,
2154 V: Clone,
2155 P: SharedPointerKind,
2156{
2157}
2158impl<K, V, P> FusedIterator for ConsumingIter<K, V, P>
2159where
2160 K: Clone,
2161 V: Clone,
2162 P: SharedPointerKind,
2163{
2164}
2165
2166impl<K, V, P: SharedPointerKind> AsRef<GenericOrdMap<K, V, P>> for GenericOrdMap<K, V, P> {
2169 fn as_ref(&self) -> &Self {
2170 self
2171 }
2172}
2173
2174impl<K, V, OK, OV, P1, P2> From<&GenericOrdMap<&K, &V, P2>> for GenericOrdMap<OK, OV, P1>
2175where
2176 K: Ord + ToOwned<Owned = OK> + ?Sized,
2177 V: ToOwned<Owned = OV> + ?Sized,
2178 OK: Ord + Clone,
2179 OV: Clone + Borrow<V>,
2180 P1: SharedPointerKind,
2181 P2: SharedPointerKind,
2182{
2183 fn from(m: &GenericOrdMap<&K, &V, P2>) -> Self {
2184 m.iter()
2185 .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
2186 .collect()
2187 }
2188}
2189
2190impl<'a, K, V, RK, RV, OK, OV, P> From<&'a [(RK, RV)]> for GenericOrdMap<K, V, P>
2191where
2192 K: Ord + Clone + From<OK>,
2193 V: Clone + From<OV>,
2194 OV: Borrow<RV>,
2195 RK: ToOwned<Owned = OK>,
2196 RV: ToOwned<Owned = OV>,
2197 P: SharedPointerKind,
2198{
2199 fn from(m: &'a [(RK, RV)]) -> GenericOrdMap<K, V, P> {
2200 m.iter()
2201 .map(|(k, v)| (k.to_owned(), v.to_owned()))
2202 .collect()
2203 }
2204}
2205
2206impl<K, V, RK, RV, P> From<Vec<(RK, RV)>> for GenericOrdMap<K, V, P>
2207where
2208 K: Ord + Clone + From<RK>,
2209 V: Clone + From<RV>,
2210 P: SharedPointerKind,
2211{
2212 fn from(m: Vec<(RK, RV)>) -> GenericOrdMap<K, V, P> {
2213 m.into_iter().collect()
2214 }
2215}
2216
2217impl<'a, K, V, RK, RV, OK, OV, P> From<&'a Vec<(RK, RV)>> for GenericOrdMap<K, V, P>
2218where
2219 K: Ord + Clone + From<OK>,
2220 V: Clone + From<OV>,
2221 OV: Borrow<RV>,
2222 RK: ToOwned<Owned = OK>,
2223 RV: ToOwned<Owned = OV>,
2224 P: SharedPointerKind,
2225{
2226 fn from(m: &'a Vec<(RK, RV)>) -> GenericOrdMap<K, V, P> {
2227 m.iter()
2228 .map(|(k, v)| (k.to_owned(), v.to_owned()))
2229 .collect()
2230 }
2231}
2232
2233impl<K, V, RK, RV, P> From<collections::HashMap<RK, RV>> for GenericOrdMap<K, V, P>
2234where
2235 K: Ord + Clone + From<RK>,
2236 V: Clone + From<RV>,
2237 P: SharedPointerKind,
2238 RK: Eq + Hash,
2239{
2240 fn from(m: collections::HashMap<RK, RV>) -> GenericOrdMap<K, V, P> {
2241 m.into_iter().collect()
2242 }
2243}
2244
2245impl<'a, K, V, OK, OV, RK, RV, P> From<&'a collections::HashMap<RK, RV>> for GenericOrdMap<K, V, P>
2246where
2247 K: Ord + Clone + From<OK>,
2248 V: Clone + From<OV>,
2249 OV: Borrow<RV>,
2250 RK: Hash + Eq + ToOwned<Owned = OK>,
2251 RV: ToOwned<Owned = OV>,
2252 P: SharedPointerKind,
2253{
2254 fn from(m: &'a collections::HashMap<RK, RV>) -> GenericOrdMap<K, V, P> {
2255 m.iter()
2256 .map(|(k, v)| (k.to_owned(), v.to_owned()))
2257 .collect()
2258 }
2259}
2260
2261impl<K, V, RK, RV, P> From<collections::BTreeMap<RK, RV>> for GenericOrdMap<K, V, P>
2262where
2263 K: Ord + Clone + From<RK>,
2264 V: Clone + From<RV>,
2265 P: SharedPointerKind,
2266{
2267 fn from(m: collections::BTreeMap<RK, RV>) -> GenericOrdMap<K, V, P> {
2268 m.into_iter().collect()
2269 }
2270}
2271
2272impl<'a, K, V, RK, RV, OK, OV, P> From<&'a collections::BTreeMap<RK, RV>> for GenericOrdMap<K, V, P>
2273where
2274 K: Ord + Clone + From<OK>,
2275 V: Clone + From<OV>,
2276 OV: Borrow<RV>,
2277 RK: Comparable<OK> + ToOwned<Owned = OK>,
2278 RV: ToOwned<Owned = OV>,
2279 P: SharedPointerKind,
2280{
2281 fn from(m: &'a collections::BTreeMap<RK, RV>) -> GenericOrdMap<K, V, P> {
2282 m.iter()
2283 .map(|(k, v)| (k.to_owned(), v.to_owned()))
2284 .collect()
2285 }
2286}
2287
2288impl<K, V, S, P1, P2> From<GenericHashMap<K, V, S, P2>> for GenericOrdMap<K, V, P1>
2289where
2290 K: Ord + Hash + Eq + Clone,
2291 V: Clone,
2292 S: BuildHasher + Clone,
2293 P1: SharedPointerKind,
2294 P2: SharedPointerKind,
2295{
2296 fn from(m: GenericHashMap<K, V, S, P2>) -> Self {
2297 m.into_iter().collect()
2298 }
2299}
2300
2301impl<'a, K, V, S, P1, P2> From<&'a GenericHashMap<K, V, S, P2>> for GenericOrdMap<K, V, P1>
2302where
2303 K: Ord + Hash + Eq + Clone,
2304 V: Clone,
2305 S: BuildHasher + Clone,
2306 P1: SharedPointerKind,
2307 P2: SharedPointerKind,
2308{
2309 fn from(m: &'a GenericHashMap<K, V, S, P2>) -> Self {
2310 m.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
2311 }
2312}
2313
2314#[cfg(any(test, feature = "proptest"))]
2316#[doc(hidden)]
2317pub mod proptest {
2318 #[deprecated(
2319 since = "14.3.0",
2320 note = "proptest strategies have moved to imbl::proptest"
2321 )]
2322 pub use crate::proptest::ord_map;
2323}
2324
2325#[cfg(test)]
2328mod test {
2329 use std::collections::BTreeMap;
2330
2331 use super::*;
2332 use crate::proptest::*;
2333 #[rustfmt::skip]
2334 use ::proptest::num::{i16, usize};
2335 #[rustfmt::skip]
2336 use ::proptest::{bool, collection, proptest};
2337 use static_assertions::{assert_impl_all, assert_not_impl_any};
2338
2339 assert_impl_all!(OrdMap<i32, i32>: Send, Sync);
2340 assert_not_impl_any!(OrdMap<i32, *const i32>: Send, Sync);
2341 assert_not_impl_any!(OrdMap<*const i32, i32>: Send, Sync);
2342 assert_covariant!(OrdMap<T, i32> in T);
2343 assert_covariant!(OrdMap<i32, T> in T);
2344
2345 #[test]
2346 fn iterates_in_order() {
2347 let map = ordmap! {
2348 2 => 22,
2349 1 => 11,
2350 3 => 33,
2351 8 => 88,
2352 9 => 99,
2353 4 => 44,
2354 5 => 55,
2355 7 => 77,
2356 6 => 66
2357 };
2358 let mut it = map.iter();
2359 assert_eq!(it.next(), Some((&1, &11)));
2360 assert_eq!(it.next(), Some((&2, &22)));
2361 assert_eq!(it.next(), Some((&3, &33)));
2362 assert_eq!(it.next(), Some((&4, &44)));
2363 assert_eq!(it.next(), Some((&5, &55)));
2364 assert_eq!(it.next(), Some((&6, &66)));
2365 assert_eq!(it.next(), Some((&7, &77)));
2366 assert_eq!(it.next(), Some((&8, &88)));
2367 assert_eq!(it.next(), Some((&9, &99)));
2368 assert_eq!(it.next(), None);
2369 }
2370
2371 #[test]
2372 fn into_iter() {
2373 let map = ordmap! {
2374 2 => 22,
2375 1 => 11,
2376 3 => 33,
2377 8 => 88,
2378 9 => 99,
2379 4 => 44,
2380 5 => 55,
2381 7 => 77,
2382 6 => 66
2383 };
2384 let mut vec = vec![];
2385 for (k, v) in map {
2386 assert_eq!(k * 11, v);
2387 vec.push(k)
2388 }
2389 assert_eq!(vec, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]);
2390 }
2391
2392 struct PanicOnClone;
2393
2394 impl Clone for PanicOnClone {
2395 fn clone(&self) -> Self {
2396 panic!("PanicOnClone::clone called")
2397 }
2398 }
2399
2400 #[test]
2401 fn into_iter_no_clone() {
2402 let mut map = OrdMap::new();
2403 let mut map_rev = OrdMap::new();
2404 for i in 0..10_000 {
2405 map.insert(i, PanicOnClone);
2406 map_rev.insert(i, PanicOnClone);
2407 }
2408 let _ = map.into_iter().collect::<Vec<_>>();
2409 let _ = map_rev.into_iter().rev().collect::<Vec<_>>();
2410 }
2411
2412 #[test]
2413 fn iter_no_clone() {
2414 let mut map = OrdMap::new();
2415 for i in 0..10_000 {
2416 map.insert(i, PanicOnClone);
2417 }
2418 let _ = map.iter().collect::<Vec<_>>();
2419 let _ = map.iter().rev().collect::<Vec<_>>();
2420 }
2421
2422 #[test]
2423 fn deletes_correctly() {
2424 let map = ordmap! {
2425 2 => 22,
2426 1 => 11,
2427 3 => 33,
2428 8 => 88,
2429 9 => 99,
2430 4 => 44,
2431 5 => 55,
2432 7 => 77,
2433 6 => 66
2434 };
2435 assert_eq!(map.extract(&11), None);
2436 let (popped, less) = map.extract(&5).unwrap();
2437 assert_eq!(popped, 55);
2438 let mut it = less.iter();
2439 assert_eq!(it.next(), Some((&1, &11)));
2440 assert_eq!(it.next(), Some((&2, &22)));
2441 assert_eq!(it.next(), Some((&3, &33)));
2442 assert_eq!(it.next(), Some((&4, &44)));
2443 assert_eq!(it.next(), Some((&6, &66)));
2444 assert_eq!(it.next(), Some((&7, &77)));
2445 assert_eq!(it.next(), Some((&8, &88)));
2446 assert_eq!(it.next(), Some((&9, &99)));
2447 assert_eq!(it.next(), None);
2448 }
2449
2450 #[test]
2451 fn debug_output() {
2452 assert_eq!(
2453 format!("{:?}", ordmap! { 3 => 4, 5 => 6, 1 => 2 }),
2454 "{1: 2, 3: 4, 5: 6}"
2455 );
2456 }
2457
2458 #[test]
2459 fn equality2() {
2460 let v1 = "1".to_string();
2461 let v2 = "1".to_string();
2462 assert_eq!(v1, v2);
2463 let p1 = Vec::<String>::new();
2464 let p2 = Vec::<String>::new();
2465 assert_eq!(p1, p2);
2466 let c1: OrdMap<_, _> = OrdMap::unit(v1, p1);
2467 let c2: OrdMap<_, _> = OrdMap::unit(v2, p2);
2468 assert_eq!(c1, c2);
2469 }
2470
2471 #[test]
2472 fn insert_remove_single_mut() {
2473 let mut m = OrdMap::new();
2474 m.insert(0, 0);
2475 assert_eq!(OrdMap::<_, _>::unit(0, 0), m);
2476 m.remove(&0);
2477 assert_eq!(OrdMap::new(), m);
2478 }
2479
2480 #[test]
2481 fn double_ended_iterator_1() {
2482 let m = ordmap! {1 => 1, 2 => 2, 3 => 3, 4 => 4};
2483 let mut it = m.iter();
2484 assert_eq!(Some((&1, &1)), it.next());
2485 assert_eq!(Some((&4, &4)), it.next_back());
2486 assert_eq!(Some((&2, &2)), it.next());
2487 assert_eq!(Some((&3, &3)), it.next_back());
2488 assert_eq!(None, it.next());
2489 }
2490
2491 #[test]
2492 fn double_ended_iterator_2() {
2493 let m = ordmap! {1 => 1, 2 => 2, 3 => 3, 4 => 4};
2494 let mut it = m.iter();
2495 assert_eq!(Some((&1, &1)), it.next());
2496 assert_eq!(Some((&4, &4)), it.next_back());
2497 assert_eq!(Some((&2, &2)), it.next());
2498 assert_eq!(Some((&3, &3)), it.next_back());
2499 assert_eq!(None, it.next_back());
2500 }
2501
2502 #[test]
2503 fn safe_mutation() {
2504 let v1 = OrdMap::<_, _>::from_iter((0..131_072).map(|i| (i, i)));
2505 let mut v2 = v1.clone();
2506 v2.insert(131_000, 23);
2507 assert_eq!(Some(&23), v2.get(&131_000));
2508 assert_eq!(Some(&131_000), v1.get(&131_000));
2509 }
2510
2511 #[test]
2512 fn index_operator() {
2513 let mut map = ordmap! {1 => 2, 3 => 4, 5 => 6};
2514 assert_eq!(4, map[&3]);
2515 map[&3] = 8;
2516 assert_eq!(ordmap! {1 => 2, 3 => 8, 5 => 6}, map);
2517 }
2518
2519 #[test]
2520 fn entry_api() {
2521 let mut map = ordmap! {"bar" => 5};
2522 map.entry("foo").and_modify(|v| *v += 5).or_insert(1);
2523 assert_eq!(1, map[&"foo"]);
2524 map.entry("foo").and_modify(|v| *v += 5).or_insert(1);
2525 assert_eq!(6, map[&"foo"]);
2526 map.entry("bar").and_modify(|v| *v += 5).or_insert(1);
2527 assert_eq!(10, map[&"bar"]);
2528 assert_eq!(
2529 10,
2530 match map.entry("bar") {
2531 Entry::Occupied(entry) => entry.remove(),
2532 _ => panic!(),
2533 }
2534 );
2535 assert!(!map.contains_key(&"bar"));
2536 }
2537
2538 #[test]
2539 fn match_string_keys_with_string_slices() {
2540 let mut map: OrdMap<String, i32> =
2541 From::from(ºap! { "foo" => &1, "bar" => &2, "baz" => &3 });
2542 assert_eq!(Some(&1), map.get("foo"));
2543 map = map.without("foo");
2544 assert_eq!(Some(3), map.remove("baz"));
2545 map["bar"] = 8;
2546 assert_eq!(8, map["bar"]);
2547 }
2548
2549 #[test]
2550 fn ranged_iter() {
2551 let map: OrdMap<i32, i32> = ordmap![1=>2, 2=>3, 3=>4, 4=>5, 5=>6, 7=>8];
2552 let range: Vec<(i32, i32)> = map.range::<_, i32>(..).map(|(k, v)| (*k, *v)).collect();
2553 assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (7, 8)], range);
2554 let range: Vec<(i32, i32)> = map
2555 .range::<_, i32>(..)
2556 .rev()
2557 .map(|(k, v)| (*k, *v))
2558 .collect();
2559 assert_eq!(vec![(7, 8), (5, 6), (4, 5), (3, 4), (2, 3), (1, 2)], range);
2560 let range: Vec<(i32, i32)> = map.range(2..5).map(|(k, v)| (*k, *v)).collect();
2561 assert_eq!(vec![(2, 3), (3, 4), (4, 5)], range);
2562 let range: Vec<(i32, i32)> = map.range(2..5).rev().map(|(k, v)| (*k, *v)).collect();
2563 assert_eq!(vec![(4, 5), (3, 4), (2, 3)], range);
2564 let range: Vec<(i32, i32)> = map.range(3..).map(|(k, v)| (*k, *v)).collect();
2565 assert_eq!(vec![(3, 4), (4, 5), (5, 6), (7, 8)], range);
2566 let range: Vec<(i32, i32)> = map.range(3..).rev().map(|(k, v)| (*k, *v)).collect();
2567 assert_eq!(vec![(7, 8), (5, 6), (4, 5), (3, 4)], range);
2568 let range: Vec<(i32, i32)> = map.range(..4).map(|(k, v)| (*k, *v)).collect();
2569 assert_eq!(vec![(1, 2), (2, 3), (3, 4)], range);
2570 let range: Vec<(i32, i32)> = map.range(..4).rev().map(|(k, v)| (*k, *v)).collect();
2571 assert_eq!(vec![(3, 4), (2, 3), (1, 2)], range);
2572 let range: Vec<(i32, i32)> = map.range(..=3).map(|(k, v)| (*k, *v)).collect();
2573 assert_eq!(vec![(1, 2), (2, 3), (3, 4)], range);
2574 let range: Vec<(i32, i32)> = map.range(..=3).rev().map(|(k, v)| (*k, *v)).collect();
2575 assert_eq!(vec![(3, 4), (2, 3), (1, 2)], range);
2576 let range: Vec<(i32, i32)> = map.range(..6).map(|(k, v)| (*k, *v)).collect();
2577 assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)], range);
2578 let range: Vec<(i32, i32)> = map.range(..=6).map(|(k, v)| (*k, *v)).collect();
2579 assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)], range);
2580
2581 assert_eq!(map.range(2..5).size_hint(), (0, Some(6)));
2582 let mut iter = map.range(2..5);
2583 iter.next();
2584 assert_eq!(iter.size_hint(), (0, Some(5)));
2585 }
2586
2587 #[test]
2588 fn range_iter_big() {
2589 use crate::nodes::btree::NODE_SIZE;
2590 use std::ops::Bound::Included;
2591 const N: usize = NODE_SIZE * NODE_SIZE * NODE_SIZE / 2; let data = (1usize..N).filter(|i| i % 2 == 0).map(|i| (i, ()));
2594 let bmap = data
2595 .clone()
2596 .collect::<std::collections::BTreeMap<usize, ()>>();
2597 let omap = data.collect::<OrdMap<usize, ()>>();
2598 assert_eq!(bmap.len(), omap.len());
2599
2600 for i in (0..NODE_SIZE * 5).chain(N - NODE_SIZE * 5..=N + 1) {
2601 assert_eq!(omap.range(i..).count(), bmap.range(i..).count());
2602 assert_eq!(omap.range(..i).count(), bmap.range(..i).count());
2603 assert_eq!(
2604 omap.range(i..(i + 7)).count(),
2605 bmap.range(i..(i + 7)).count()
2606 );
2607 assert_eq!(
2608 omap.range(i..=(i + 7)).count(),
2609 bmap.range(i..=(i + 7)).count()
2610 );
2611 assert_eq!(
2612 omap.range((Included(i), Included(i + 7))).count(),
2613 bmap.range((Included(i), Included(i + 7))).count(),
2614 );
2615 assert_eq!(omap.range(..=i).next_back(), omap.get_prev(&i));
2616 assert_eq!(omap.range(i..).next(), omap.get_next(&i));
2617 }
2618 }
2619
2620 #[test]
2621 fn issue_124() {
2622 let mut map = OrdMap::new();
2623 let contents = include_str!("test-fixtures/issue_124.txt");
2624 for line in contents.lines() {
2625 if let Some(tail) = line.strip_prefix("insert ") {
2626 map.insert(tail.parse::<u32>().unwrap(), 0);
2627 } else if let Some(tail) = line.strip_prefix("remove ") {
2628 map.remove(&tail.parse::<u32>().unwrap());
2629 }
2630 }
2631 }
2632
2633 fn expected_diff<'a, K, V, P>(
2634 a: &'a GenericOrdMap<K, V, P>,
2635 b: &'a GenericOrdMap<K, V, P>,
2636 ) -> Vec<DiffItem<'a, 'a, K, V>>
2637 where
2638 K: Ord + Clone,
2639 V: PartialEq + Clone,
2640 P: SharedPointerKind,
2641 {
2642 let mut diff = Vec::new();
2643 for (k, v) in a.iter() {
2644 if let Some(v2) = b.get(k) {
2645 if v != v2 {
2646 diff.push(DiffItem::Update {
2647 old: (k, v),
2648 new: (k, v2),
2649 });
2650 }
2651 } else {
2652 diff.push(DiffItem::Remove(k, v));
2653 }
2654 }
2655 for (k, v) in b.iter() {
2656 if a.get(k).is_none() {
2657 diff.push(DiffItem::Add(k, v));
2658 }
2659 }
2660 fn diff_item_key<'b, K, V>(di: &DiffItem<'b, 'b, K, V>) -> &'b K {
2661 match di {
2662 DiffItem::Add(k, _) => k,
2663 DiffItem::Remove(k, _) => k,
2664 DiffItem::Update { old: (k, _), .. } => k,
2665 }
2666 }
2667 diff.sort_unstable_by(|a, b| diff_item_key(a).cmp(diff_item_key(b)));
2668 diff
2669 }
2670
2671 proptest! {
2672 #[test]
2673 fn length(ref input in collection::btree_map(i16::ANY, i16::ANY, 0..1000)) {
2674 let map: OrdMap<i16, i16> = OrdMap::from(input.clone());
2675 assert_eq!(input.len(), map.len());
2676 }
2677
2678 #[test]
2679 fn order(ref input in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2680 let map: OrdMap<i16, i16> = OrdMap::from(input.clone());
2681 let keys = map.keys().cloned().collect::<Vec<_>>();
2682 let mut expected_keys = input.keys().cloned().collect::<Vec<_>>();
2683 expected_keys.sort();
2684 assert_eq!(keys, expected_keys);
2685 }
2686
2687 #[test]
2688 fn overwrite_values(ref vec in collection::vec((i16::ANY, i16::ANY), 1..1000), index_rand in usize::ANY, new_val in i16::ANY) {
2689 let index = vec[index_rand % vec.len()].0;
2690 let map1 = OrdMap::<_, _>::from_iter(vec.clone());
2691 let map2 = map1.update(index, new_val);
2692 for (k, v) in map2 {
2693 if k == index {
2694 assert_eq!(v, new_val);
2695 } else {
2696 match map1.get(&k) {
2697 None => panic!("map1 didn't have key {:?}", k),
2698 Some(other_v) => {
2699 assert_eq!(v, *other_v);
2700 }
2701 }
2702 }
2703 }
2704 }
2705
2706 #[test]
2707 fn delete_values(ref vec in collection::vec((usize::ANY, usize::ANY), 1..1000), index_rand in usize::ANY) {
2708 let index = vec[index_rand % vec.len()].0;
2709 let map1: OrdMap<usize, usize> = OrdMap::from_iter(vec.clone());
2710 let map2 = map1.without(&index);
2711 assert_eq!(map1.len(), map2.len() + 1);
2712 for k in map2.keys() {
2713 assert_ne!(*k, index);
2714 }
2715 }
2716
2717 #[test]
2718 fn insert_and_delete_values(
2719 ref input in ord_map(0usize..64, 0usize..64, 1..1000),
2720 ref ops in collection::vec((bool::ANY, usize::ANY, usize::ANY), 1..1000)
2721 ) {
2722 let mut map = input.clone();
2723 let mut tree: collections::BTreeMap<usize, usize> = input.iter().map(|(k, v)| (*k, *v)).collect();
2724 for (ins, key, val) in ops {
2725 if *ins {
2726 tree.insert(*key, *val);
2727 map = map.update(*key, *val)
2728 } else {
2729 tree.remove(key);
2730 map = map.without(key)
2731 }
2732 }
2733 assert!(map.iter().map(|(k, v)| (*k, *v)).eq(tree.iter().map(|(k, v)| (*k, *v))));
2734 }
2735
2736 #[test]
2737 fn proptest_works(ref m in ord_map(0..9999, ".*", 10..100)) {
2738 assert!(m.len() < 100);
2739 assert!(m.len() >= 10);
2740 }
2741
2742 #[test]
2743 fn insert_and_length(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2744 let mut map = OrdMap::new();
2745 for (k, v) in m.iter() {
2746 map = map.update(*k, *v)
2747 }
2748 assert_eq!(m.len(), map.len());
2749 }
2750
2751 #[test]
2752 fn from_iterator(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2753 let map: OrdMap<i16, i16> =
2754 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2755 assert_eq!(m.len(), map.len());
2756 }
2757
2758 #[test]
2759 fn iterate_over(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2760 let map: OrdMap<i16, i16> =
2761 OrdMap::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2762 let expected = m.iter().map(|(k, v)| (*k, *v)).collect::<BTreeMap<_, _>>();
2763 assert!(map.iter().eq(expected.iter()));
2764 }
2765
2766 #[test]
2767 fn iterate_over_rev(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2768 let map: OrdMap<i16, i16> =
2769 OrdMap::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2770 let expected = m.iter().map(|(k, v)| (*k, *v)).collect::<BTreeMap<_, _>>();
2771 assert!(map.iter().rev().eq(expected.iter().rev()));
2772 }
2773
2774 #[test]
2775 fn equality(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2776 let map1: OrdMap<i16, i16> =
2777 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2778 let map2: OrdMap<i16, i16> =
2779 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2780 assert_eq!(map1, map2);
2781 }
2782
2783 #[test]
2784 fn lookup(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2785 let map: OrdMap<i16, i16> =
2786 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2787 for (k, v) in m.iter() {
2788 assert_eq!(Some(*v), map.get(k).cloned());
2789 }
2790 }
2791
2792 #[test]
2793 fn remove(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2794 let mut map: OrdMap<i16, i16> =
2795 OrdMap::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2796 for k in m.keys() {
2797 let l = map.len();
2798 assert_eq!(m.get(k).cloned(), map.get(k).cloned());
2799 map = map.without(k);
2800 assert_eq!(None, map.get(k));
2801 assert_eq!(l - 1, map.len());
2802 }
2803 }
2804
2805 #[test]
2806 fn insert_mut(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2807 let mut mut_map = OrdMap::new();
2808 let mut map = OrdMap::new();
2809 for (k, v) in m.iter() {
2810 map = map.update(*k, *v);
2811 mut_map.insert(*k, *v);
2812 }
2813 assert_eq!(map, mut_map);
2814 }
2815
2816 #[test]
2817 fn remove_mut(ref orig in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2818 let mut map = orig.clone();
2819 for key in orig.keys() {
2820 let len = map.len();
2821 assert_eq!(orig.get(key), map.get(key));
2822 assert_eq!(orig.get(key).cloned(), map.remove(key));
2823 assert_eq!(None, map.get(key));
2824 assert_eq!(len - 1, map.len());
2825 }
2826 }
2827
2828 #[test]
2829 fn remove_alien(ref orig in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2830 let mut map: OrdMap<i16, i16> = OrdMap::from(orig.clone());
2831 for key in orig.keys() {
2832 let len = map.len();
2833 assert_eq!(orig.get(key), map.get(key));
2834 assert_eq!(orig.get(key).cloned(), map.remove(key));
2835 assert_eq!(None, map.get(key));
2836 assert_eq!(len - 1, map.len());
2837 }
2838 }
2839
2840 #[test]
2841 fn delete_and_reinsert(
2842 ref input in collection::hash_map(i16::ANY, i16::ANY, 1..1000),
2843 index_rand in usize::ANY
2844 ) {
2845 let index = *input.keys().nth(index_rand % input.len()).unwrap();
2846 let map1 = OrdMap::from_iter(input.clone());
2847 let (val, map2): (i16, _) = map1.extract(&index).unwrap();
2848 let map3 = map2.update(index, val);
2849 for key in map2.keys() {
2850 assert!(*key != index);
2851 }
2852 assert_eq!(map1.len(), map2.len() + 1);
2853 assert_eq!(map1, map3);
2854 }
2855
2856 #[test]
2857 fn exact_size_iterator(ref m in ord_map(i16::ANY, i16::ANY, 1..1000)) {
2858 let mut should_be = m.len();
2859 let mut it = m.iter();
2860 loop {
2861 assert_eq!(should_be, it.len());
2862 match it.next() {
2863 None => break,
2864 Some(_) => should_be -= 1,
2865 }
2866 }
2867 assert_eq!(0, it.len());
2868 }
2869
2870 #[test]
2871 fn diff_all_values(a in collection::vec((usize::ANY, usize::ANY), 1..1000), b in collection::vec((usize::ANY, usize::ANY), 1..1000)) {
2872 let a: OrdMap<usize, usize> = OrdMap::from(a);
2873 let b: OrdMap<usize, usize> = OrdMap::from(b);
2874
2875 let diff: Vec<_> = a.diff(&b).collect();
2876 let expected = expected_diff(&a, &b);
2877 assert_eq!(expected, diff);
2878 }
2879
2880 #[test]
2881 fn diff_all_values_shared(a in collection::vec((usize::ANY, usize::ANY), 1..1000), ops in collection::vec((usize::ANY, usize::ANY), 1..1000)) {
2882 let a: OrdMap<usize, usize> = OrdMap::from(a);
2883 let mut b = a.clone();
2884 for (k, v) in ops {
2885 b.insert(k, v);
2886 }
2887
2888 let diff: Vec<_> = a.diff(&b).collect();
2889 let expected = expected_diff(&a, &b);
2890 assert_eq!(expected, diff);
2891 }
2892
2893 #[test]
2894 fn union(ref map1 in ord_map(i16::ANY, i16::ANY, 0..100),
2895 ref map2 in ord_map(i16::ANY, i16::ANY, 0..100)) {
2896 let union_map = map1.clone().union(map2.clone());
2897
2898 for k in map1.keys() {
2899 assert!(union_map.contains_key(k));
2900 }
2901
2902 for k in map2.keys() {
2903 assert!(union_map.contains_key(k));
2904 }
2905
2906 for (k, v) in union_map.iter() {
2907 assert_eq!(v, map1.get(k).or_else(|| map2.get(k)).unwrap());
2908 }
2909 }
2910 }
2911}