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};
30
31use crate::hashmap::GenericHashMap;
32use crate::nodes::btree::{
33 ConsumingIter as NodeConsumingIter, Cursor, InsertAction, Iter as NodeIter, Node,
34};
35use crate::shared_ptr::DefaultSharedPtr;
36
37#[macro_export]
56macro_rules! ordmap {
57 () => { $crate::ordmap::OrdMap::new() };
58
59 ( $( $key:expr => $value:expr ),* ) => {{
60 let mut map = $crate::ordmap::OrdMap::new();
61 $({
62 map.insert($key, $value);
63 })*;
64 map
65 }};
66}
67
68pub type OrdMap<K, V> = GenericOrdMap<K, V, DefaultSharedPtr>;
73
74pub struct GenericOrdMap<K, V, P: SharedPointerKind> {
89 size: usize,
90 root: Option<Node<K, V, P>>,
91}
92
93impl<K, V, P: SharedPointerKind> GenericOrdMap<K, V, P> {
94 #[inline]
96 #[must_use]
97 pub fn new() -> Self {
98 GenericOrdMap {
99 size: 0,
100 root: None,
101 }
102 }
103
104 #[inline]
118 #[must_use]
119 pub fn unit(key: K, value: V) -> Self {
120 Self {
121 size: 1,
122 root: Some(Node::unit(key, value)),
123 }
124 }
125
126 #[inline]
143 #[must_use]
144 pub fn is_empty(&self) -> bool {
145 self.len() == 0
146 }
147
148 pub fn ptr_eq(&self, other: &Self) -> bool {
158 match (&self.root, &other.root) {
159 (Some(a), Some(b)) => a.ptr_eq(&b),
160 (None, None) => true,
161 _ => false,
162 }
163 }
164
165 #[inline]
181 #[must_use]
182 pub fn len(&self) -> usize {
183 self.size
184 }
185
186 pub fn clear(&mut self) {
203 self.root = None;
204 self.size = 0;
205 }
206}
207
208impl<K, V, P> GenericOrdMap<K, V, P>
209where
210 K: Ord,
211 P: SharedPointerKind,
212{
213 #[must_use]
230 pub fn get_max(&self) -> Option<&(K, V)> {
231 self.root.as_ref().and_then(|root| root.max())
232 }
233
234 #[must_use]
251 pub fn get_min(&self) -> Option<&(K, V)> {
252 self.root.as_ref().and_then(|root| root.min())
253 }
254
255 #[must_use]
257 pub fn iter(&self) -> Iter<'_, K, V, P> {
258 Iter {
259 it: NodeIter::new(self.root.as_ref(), self.size, ..),
260 }
261 }
262
263 #[must_use]
265 pub fn range<R, BK>(&self, range: R) -> RangedIter<'_, K, V, P>
266 where
267 R: RangeBounds<BK>,
268 K: Borrow<BK>,
269 BK: Ord + ?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<BK>(&self, key: &BK) -> Option<&V>
331 where
332 BK: Ord + ?Sized,
333 K: Borrow<BK>,
334 {
335 self.root
336 .as_ref()
337 .and_then(|r| r.lookup(key).map(|(_, v)| v))
338 }
339
340 #[must_use]
356 pub fn get_key_value<BK>(&self, key: &BK) -> Option<(&K, &V)>
357 where
358 BK: Ord + ?Sized,
359 K: Borrow<BK>,
360 {
361 self.root
362 .as_ref()
363 .and_then(|r| r.lookup(key).map(|(k, v)| (k, v)))
364 }
365
366 #[must_use]
383 pub fn get_prev<BK>(&self, key: &BK) -> Option<(&K, &V)>
384 where
385 BK: Ord + ?Sized,
386 K: Borrow<BK>,
387 {
388 self.range((Bound::Unbounded, Bound::Included(key)))
389 .next_back()
390 }
391
392 #[must_use]
409 pub fn get_next<BK>(&self, key: &BK) -> Option<(&K, &V)>
410 where
411 BK: Ord + ?Sized,
412 K: Borrow<BK>,
413 {
414 self.range((Bound::Included(key), Bound::Unbounded)).next()
415 }
416
417 #[must_use]
435 pub fn contains_key<BK>(&self, k: &BK) -> bool
436 where
437 BK: Ord + ?Sized,
438 K: Borrow<BK>,
439 {
440 self.get(k).is_some()
441 }
442
443 #[must_use]
451 pub fn is_submap_by<B, RM, F, P2>(&self, other: RM, mut cmp: F) -> bool
452 where
453 F: FnMut(&V, &B) -> bool,
454 RM: Borrow<GenericOrdMap<K, B, P2>>,
455 P2: SharedPointerKind,
456 {
457 self.iter()
458 .all(|(k, v)| other.borrow().get(k).map(|ov| cmp(v, ov)).unwrap_or(false))
459 }
460
461 #[must_use]
470 pub fn is_proper_submap_by<B, RM, F, P2>(&self, other: RM, cmp: F) -> bool
471 where
472 F: FnMut(&V, &B) -> bool,
473 RM: Borrow<GenericOrdMap<K, B, P2>>,
474 P2: SharedPointerKind,
475 {
476 self.len() != other.borrow().len() && self.is_submap_by(other, cmp)
477 }
478
479 #[must_use]
495 pub fn is_submap<RM>(&self, other: RM) -> bool
496 where
497 V: PartialEq,
498 RM: Borrow<Self>,
499 {
500 self.is_submap_by(other.borrow(), PartialEq::eq)
501 }
502
503 #[must_use]
524 pub fn is_proper_submap<RM>(&self, other: RM) -> bool
525 where
526 V: PartialEq,
527 RM: Borrow<Self>,
528 {
529 self.is_proper_submap_by(other.borrow(), PartialEq::eq)
530 }
531
532 #[cfg(any(test, fuzzing))]
534 #[allow(unreachable_pub)]
535 pub fn check_sane(&self)
536 where
537 K: std::fmt::Debug,
538 V: std::fmt::Debug,
539 {
540 let size = self
541 .root
542 .as_ref()
543 .map(|root| root.check_sane(true))
544 .unwrap_or(0);
545 assert_eq!(size, self.size);
546 }
547}
548
549impl<K, V, P> GenericOrdMap<K, V, P>
550where
551 K: Ord + Clone,
552 V: Clone,
553 P: SharedPointerKind,
554{
555 #[must_use]
574 pub fn get_mut<BK>(&mut self, key: &BK) -> Option<&mut V>
575 where
576 BK: Ord + ?Sized,
577 K: Borrow<BK>,
578 {
579 let root = self.root.as_mut()?;
580 root.lookup_mut(key).map(|(_, v)| v)
581 }
582
583 #[must_use]
599 pub fn get_key_value_mut<BK>(&mut self, key: &BK) -> Option<(&K, &mut V)>
600 where
601 BK: Ord + ?Sized,
602 K: Borrow<BK>,
603 {
604 self.root.as_mut()?.lookup_mut(key)
605 }
606
607 #[must_use]
627 pub fn get_prev_mut<BK>(&mut self, key: &BK) -> Option<(&K, &mut V)>
628 where
629 BK: Ord + ?Sized,
630 K: Borrow<BK>,
631 {
632 let prev = self.get_prev(key)?.0.clone();
633 let root = self.root.as_mut()?;
634 root.lookup_mut(prev.borrow())
635 }
636
637 #[must_use]
657 pub fn get_next_mut<BK>(&mut self, key: &BK) -> Option<(&K, &mut V)>
658 where
659 BK: Ord + ?Sized,
660 K: Borrow<BK>,
661 {
662 let next = self.get_next(key)?.0.clone();
663 let root = self.root.as_mut()?;
664 root.lookup_mut(next.borrow())
665 }
666
667 #[inline]
694 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
695 self.insert_key_value(key, value).map(|(_, v)| v)
696 }
697
698 #[inline]
707 pub(crate) fn insert_key_value(&mut self, key: K, value: V) -> Option<(K, V)> {
708 let root = self.root.get_or_insert_with(Node::default);
709 match root.insert(key, value) {
710 InsertAction::Replaced(old_key, old_value) => return Some((old_key, old_value)),
711 InsertAction::Inserted => (),
712 InsertAction::Split(separator, right) => {
713 let left = mem::take(root);
714 *root = Node::new_from_split(left, separator, right);
715 }
716 }
717 self.size += 1;
718 None
719 }
720
721 #[inline]
738 pub fn remove<BK>(&mut self, k: &BK) -> Option<V>
739 where
740 BK: Ord + ?Sized,
741 K: Borrow<BK>,
742 {
743 self.remove_with_key(k).map(|(_, v)| v)
744 }
745
746 pub fn remove_with_key<BK>(&mut self, k: &BK) -> Option<(K, V)>
751 where
752 BK: Ord + ?Sized,
753 K: Borrow<BK>,
754 {
755 let root = self.root.as_mut()?;
756 let mut removed = None;
757 if root.remove(k, &mut removed) {
758 if let Node::Branch(branch) = root {
759 if let Some(child) = SharedPointer::make_mut(branch).pop_single_child() {
760 self.root = Some(child);
761 }
762 }
763 }
766 self.size -= removed.is_some() as usize;
767 removed
768 }
769
770 #[must_use]
790 pub fn update(&self, key: K, value: V) -> Self {
791 let mut out = self.clone();
792 out.insert(key, value);
793 out
794 }
795
796 #[must_use]
805 pub fn update_with<F>(self, k: K, v: V, f: F) -> Self
806 where
807 F: FnOnce(V, V) -> V,
808 {
809 self.update_with_key(k, v, |_, v1, v2| f(v1, v2))
810 }
811
812 #[must_use]
821 pub fn update_with_key<F>(self, k: K, v: V, f: F) -> Self
822 where
823 F: FnOnce(&K, V, V) -> V,
824 {
825 match self.extract_with_key(&k) {
826 None => self.update(k, v),
827 Some((_, v2, m)) => {
828 let out_v = f(&k, v2, v);
829 m.update(k, out_v)
830 }
831 }
832 }
833
834 #[must_use]
844 pub fn update_lookup_with_key<F>(self, k: K, v: V, f: F) -> (Option<V>, Self)
845 where
846 F: FnOnce(&K, &V, V) -> V,
847 {
848 match self.extract_with_key(&k) {
849 None => (None, self.update(k, v)),
850 Some((_, v2, m)) => {
851 let out_v = f(&k, &v2, v);
852 (Some(v2), m.update(k, out_v))
853 }
854 }
855 }
856
857 #[must_use]
870 pub fn alter<F>(&self, f: F, k: K) -> Self
871 where
872 F: FnOnce(Option<V>) -> Option<V>,
873 {
874 let pop = self.extract_with_key(&k);
875 match (f(pop.as_ref().map(|(_, v, _)| v.clone())), pop) {
876 (None, None) => self.clone(),
877 (Some(v), None) => self.update(k, v),
878 (None, Some((_, _, m))) => m,
879 (Some(v), Some((_, _, m))) => m.update(k, v),
880 }
881 }
882
883 #[must_use]
887 pub fn without<BK>(&self, k: &BK) -> Self
888 where
889 BK: Ord + ?Sized,
890 K: Borrow<BK>,
891 {
892 self.extract(k)
893 .map(|(_, m)| m)
894 .unwrap_or_else(|| self.clone())
895 }
896
897 #[must_use]
902 pub fn extract<BK>(&self, k: &BK) -> Option<(V, Self)>
903 where
904 BK: Ord + ?Sized,
905 K: Borrow<BK>,
906 {
907 self.extract_with_key(k).map(|(_, v, m)| (v, m))
908 }
909
910 #[must_use]
915 pub fn extract_with_key<BK>(&self, k: &BK) -> Option<(K, V, Self)>
916 where
917 BK: Ord + ?Sized,
918 K: Borrow<BK>,
919 {
920 let mut out = self.clone();
921 let result = out.remove_with_key(k);
922 result.map(|(k, v)| (k, v, out))
923 }
924
925 #[inline]
941 #[must_use]
942 pub fn union(mut self, mut other: Self) -> Self {
943 if self.len() >= other.len() {
946 for (k, v) in other {
947 self.entry(k).or_insert(v);
948 }
949 self
950 } else {
951 for (k, v) in self {
952 other.insert(k, v);
953 }
954 other
955 }
956 }
957
958 #[inline]
968 #[must_use]
969 pub fn union_with<F>(self, other: Self, mut f: F) -> Self
970 where
971 F: FnMut(V, V) -> V,
972 {
973 self.union_with_key(other, |_, v1, v2| f(v1, v2))
974 }
975
976 #[must_use]
1001 pub fn union_with_key<F>(self, other: Self, mut f: F) -> Self
1002 where
1003 F: FnMut(&K, V, V) -> V,
1004 {
1005 if self.len() >= other.len() {
1006 self.union_with_key_inner(other, f)
1007 } else {
1008 other.union_with_key_inner(self, |key, other_value, self_value| {
1009 f(key, self_value, other_value)
1010 })
1011 }
1012 }
1013
1014 fn union_with_key_inner<F>(mut self, other: Self, mut f: F) -> Self
1015 where
1016 F: FnMut(&K, V, V) -> V,
1017 {
1018 for (key, right_value) in other {
1019 match self.remove(&key) {
1020 None => {
1021 self.insert(key, right_value);
1022 }
1023 Some(left_value) => {
1024 let final_value = f(&key, left_value, right_value);
1025 self.insert(key, final_value);
1026 }
1027 }
1028 }
1029 self
1030 }
1031
1032 #[must_use]
1048 pub fn unions<I>(i: I) -> Self
1049 where
1050 I: IntoIterator<Item = Self>,
1051 {
1052 i.into_iter().fold(Self::default(), Self::union)
1053 }
1054
1055 #[must_use]
1066 pub fn unions_with<I, F>(i: I, f: F) -> Self
1067 where
1068 I: IntoIterator<Item = Self>,
1069 F: Fn(V, V) -> V,
1070 {
1071 i.into_iter()
1072 .fold(Self::default(), |a, b| a.union_with(b, &f))
1073 }
1074
1075 #[must_use]
1087 pub fn unions_with_key<I, F>(i: I, f: F) -> Self
1088 where
1089 I: IntoIterator<Item = Self>,
1090 F: Fn(&K, V, V) -> V,
1091 {
1092 i.into_iter()
1093 .fold(Self::default(), |a, b| a.union_with_key(b, &f))
1094 }
1095
1096 #[deprecated(
1117 since = "2.0.1",
1118 note = "to avoid conflicting behaviors between std and imbl, the `difference` alias for `symmetric_difference` will be removed."
1119 )]
1120 #[inline]
1121 #[must_use]
1122 pub fn difference(self, other: Self) -> Self {
1123 self.symmetric_difference(other)
1124 }
1125
1126 #[inline]
1142 #[must_use]
1143 pub fn symmetric_difference(self, other: Self) -> Self {
1144 self.symmetric_difference_with_key(other, |_, _, _| None)
1145 }
1146
1147 #[deprecated(
1157 since = "2.0.1",
1158 note = "to avoid conflicting behaviors between std and imbl, the `difference_with` alias for `symmetric_difference_with` will be removed."
1159 )]
1160 #[inline]
1161 #[must_use]
1162 pub fn difference_with<F>(self, other: Self, f: F) -> Self
1163 where
1164 F: FnMut(V, V) -> Option<V>,
1165 {
1166 self.symmetric_difference_with(other, f)
1167 }
1168
1169 #[inline]
1174 #[must_use]
1175 pub fn symmetric_difference_with<F>(self, other: Self, mut f: F) -> Self
1176 where
1177 F: FnMut(V, V) -> Option<V>,
1178 {
1179 self.symmetric_difference_with_key(other, |_, a, b| f(a, b))
1180 }
1181
1182 #[deprecated(
1207 since = "2.0.1",
1208 note = "to avoid conflicting behaviors between std and imbl, the `difference_with_key` alias for `symmetric_difference_with_key` will be removed."
1209 )]
1210 #[must_use]
1211 pub fn difference_with_key<F>(self, other: Self, f: F) -> Self
1212 where
1213 F: FnMut(&K, V, V) -> Option<V>,
1214 {
1215 self.symmetric_difference_with_key(other, f)
1216 }
1217
1218 #[must_use]
1238 pub fn symmetric_difference_with_key<F>(mut self, other: Self, mut f: F) -> Self
1239 where
1240 F: FnMut(&K, V, V) -> Option<V>,
1241 {
1242 let mut out = Self::default();
1243 for (key, right_value) in other {
1244 match self.remove(&key) {
1245 None => {
1246 out.insert(key, right_value);
1247 }
1248 Some(left_value) => {
1249 if let Some(final_value) = f(&key, left_value, right_value) {
1250 out.insert(key, final_value);
1251 }
1252 }
1253 }
1254 }
1255 out.union(self)
1256 }
1257
1258 #[inline]
1274 #[must_use]
1275 pub fn relative_complement(mut self, other: Self) -> Self {
1276 for (key, _) in other {
1277 let _ = self.remove(&key);
1278 }
1279 self
1280 }
1281
1282 #[inline]
1298 #[must_use]
1299 pub fn intersection(self, other: Self) -> Self {
1300 self.intersection_with_key(other, |_, v, _| v)
1301 }
1302
1303 #[inline]
1309 #[must_use]
1310 pub fn intersection_with<B, C, F, P2, P3>(
1311 self,
1312 other: GenericOrdMap<K, B, P2>,
1313 mut f: F,
1314 ) -> GenericOrdMap<K, C, P3>
1315 where
1316 B: Clone,
1317 C: Clone,
1318 F: FnMut(V, B) -> C,
1319 P2: SharedPointerKind,
1320 P3: SharedPointerKind,
1321 {
1322 self.intersection_with_key(other, |_, v1, v2| f(v1, v2))
1323 }
1324
1325 #[must_use]
1345 pub fn intersection_with_key<B, C, F, P2, P3>(
1346 mut self,
1347 other: GenericOrdMap<K, B, P2>,
1348 mut f: F,
1349 ) -> GenericOrdMap<K, C, P3>
1350 where
1351 B: Clone,
1352 C: Clone,
1353 F: FnMut(&K, V, B) -> C,
1354 P2: SharedPointerKind,
1355 P3: SharedPointerKind,
1356 {
1357 let mut out = GenericOrdMap::<K, C, P3>::default();
1358 for (key, right_value) in other {
1359 match self.remove(&key) {
1360 None => (),
1361 Some(left_value) => {
1362 let result = f(&key, left_value, right_value);
1363 out.insert(key, result);
1364 }
1365 }
1366 }
1367 out
1368 }
1369
1370 #[must_use]
1376 pub fn split<BK>(&self, split: &BK) -> (Self, Self)
1377 where
1378 BK: Ord + ?Sized,
1379 K: Borrow<BK>,
1380 {
1381 let (l, _, r) = self.split_lookup(split);
1382 (l, r)
1383 }
1384
1385 #[must_use]
1391 pub fn split_lookup<BK>(&self, split: &BK) -> (Self, Option<V>, Self)
1392 where
1393 BK: Ord + ?Sized,
1394 K: Borrow<BK>,
1395 {
1396 self.iter().fold(
1398 (GenericOrdMap::new(), None, GenericOrdMap::new()),
1399 |(l, m, r), (k, v)| match k.borrow().cmp(split) {
1400 Ordering::Less => (l.update(k.clone(), v.clone()), m, r),
1401 Ordering::Equal => (l, Some(v.clone()), r),
1402 Ordering::Greater => (l, m, r.update(k.clone(), v.clone())),
1403 },
1404 )
1405 }
1406
1407 #[must_use]
1410 pub fn take(&self, n: usize) -> Self {
1411 self.iter()
1412 .take(n)
1413 .map(|(k, v)| (k.clone(), v.clone()))
1414 .collect()
1415 }
1416
1417 #[must_use]
1420 pub fn skip(&self, n: usize) -> Self {
1421 self.iter()
1422 .skip(n)
1423 .map(|(k, v)| (k.clone(), v.clone()))
1424 .collect()
1425 }
1426
1427 #[must_use]
1430 pub fn without_min(&self) -> (Option<V>, Self) {
1431 let (pop, next) = self.without_min_with_key();
1432 (pop.map(|(_, v)| v), next)
1433 }
1434
1435 #[must_use]
1438 pub fn without_min_with_key(&self) -> (Option<(K, V)>, Self) {
1439 match self.get_min() {
1440 None => (None, self.clone()),
1441 Some((k, _)) => {
1442 let (key, value, next) = self.extract_with_key(k).unwrap();
1443 (Some((key, value)), next)
1444 }
1445 }
1446 }
1447
1448 #[must_use]
1451 pub fn without_max(&self) -> (Option<V>, Self) {
1452 let (pop, next) = self.without_max_with_key();
1453 (pop.map(|(_, v)| v), next)
1454 }
1455
1456 #[must_use]
1459 pub fn without_max_with_key(&self) -> (Option<(K, V)>, Self) {
1460 match self.get_max() {
1461 None => (None, self.clone()),
1462 Some((k, _)) => {
1463 let (key, value, next) = self.extract_with_key(k).unwrap();
1464 (Some((key, value)), next)
1465 }
1466 }
1467 }
1468
1469 #[must_use]
1475 pub fn entry(&mut self, key: K) -> Entry<'_, K, V, P> {
1476 if self.contains_key(&key) {
1477 Entry::Occupied(OccupiedEntry { map: self, key })
1478 } else {
1479 Entry::Vacant(VacantEntry { map: self, key })
1480 }
1481 }
1482}
1483
1484pub enum Entry<'a, K, V, P>
1488where
1489 K: Ord + Clone,
1490 V: Clone,
1491 P: SharedPointerKind,
1492{
1493 Occupied(OccupiedEntry<'a, K, V, P>),
1495 Vacant(VacantEntry<'a, K, V, P>),
1497}
1498
1499impl<'a, K, V, P> Entry<'a, K, V, P>
1500where
1501 K: Ord + Clone,
1502 V: Clone,
1503 P: SharedPointerKind,
1504{
1505 pub fn or_insert(self, default: V) -> &'a mut V {
1508 self.or_insert_with(|| default)
1509 }
1510
1511 pub fn or_insert_with<F>(self, default: F) -> &'a mut V
1515 where
1516 F: FnOnce() -> V,
1517 {
1518 match self {
1519 Entry::Occupied(entry) => entry.into_mut(),
1520 Entry::Vacant(entry) => entry.insert(default()),
1521 }
1522 }
1523
1524 pub fn or_default(self) -> &'a mut V
1527 where
1528 V: Default,
1529 {
1530 #[allow(clippy::unwrap_or_default)]
1531 self.or_insert_with(Default::default)
1532 }
1533
1534 #[must_use]
1536 pub fn key(&self) -> &K {
1537 match self {
1538 Entry::Occupied(entry) => entry.key(),
1539 Entry::Vacant(entry) => entry.key(),
1540 }
1541 }
1542
1543 #[must_use]
1546 pub fn and_modify<F>(mut self, f: F) -> Self
1547 where
1548 F: FnOnce(&mut V),
1549 {
1550 match &mut self {
1551 Entry::Occupied(ref mut entry) => f(entry.get_mut()),
1552 Entry::Vacant(_) => (),
1553 }
1554 self
1555 }
1556}
1557
1558pub struct OccupiedEntry<'a, K, V, P>
1560where
1561 K: Ord + Clone,
1562 V: Clone,
1563 P: SharedPointerKind,
1564{
1565 map: &'a mut GenericOrdMap<K, V, P>,
1566 key: K,
1567}
1568
1569impl<'a, K, V, P> OccupiedEntry<'a, K, V, P>
1570where
1571 K: 'a + Ord + Clone,
1572 V: 'a + Clone,
1573 P: SharedPointerKind,
1574{
1575 #[must_use]
1577 pub fn key(&self) -> &K {
1578 &self.key
1579 }
1580
1581 pub fn remove_entry(self) -> (K, V) {
1583 self.map
1584 .remove_with_key(&self.key)
1585 .expect("ordmap::OccupiedEntry::remove_entry: key has vanished!")
1586 }
1587
1588 #[must_use]
1590 pub fn get(&self) -> &V {
1591 self.map.get(&self.key).unwrap()
1592 }
1593
1594 #[must_use]
1596 pub fn get_mut(&mut self) -> &mut V {
1597 self.map.get_mut(&self.key).unwrap()
1598 }
1599
1600 #[must_use]
1602 pub fn into_mut(self) -> &'a mut V {
1603 self.map.get_mut(&self.key).unwrap()
1604 }
1605
1606 pub fn insert(&mut self, value: V) -> V {
1608 mem::replace(self.get_mut(), value)
1609 }
1610
1611 pub fn remove(self) -> V {
1613 self.remove_entry().1
1614 }
1615}
1616
1617pub struct VacantEntry<'a, K, V, P>
1619where
1620 K: Ord + Clone,
1621 V: Clone,
1622 P: SharedPointerKind,
1623{
1624 map: &'a mut GenericOrdMap<K, V, P>,
1625 key: K,
1626}
1627
1628impl<'a, K, V, P> VacantEntry<'a, K, V, P>
1629where
1630 K: 'a + Ord + Clone,
1631 V: 'a + Clone,
1632 P: SharedPointerKind,
1633{
1634 #[must_use]
1636 pub fn key(&self) -> &K {
1637 &self.key
1638 }
1639
1640 #[must_use]
1642 pub fn into_key(self) -> K {
1643 self.key
1644 }
1645
1646 pub fn insert(self, value: V) -> &'a mut V {
1648 self.map.insert(self.key.clone(), value);
1649 self.map.get_mut(&self.key).unwrap()
1651 }
1652}
1653
1654impl<K, V, P: SharedPointerKind> Clone for GenericOrdMap<K, V, P> {
1657 #[inline]
1661 fn clone(&self) -> Self {
1662 GenericOrdMap {
1663 size: self.size,
1664 root: self.root.clone(),
1665 }
1666 }
1667}
1668
1669impl<K, V, P> PartialEq for GenericOrdMap<K, V, P>
1671where
1672 K: Ord + PartialEq,
1673 V: PartialEq,
1674 P: SharedPointerKind,
1675{
1676 fn eq(&self, other: &GenericOrdMap<K, V, P>) -> bool {
1677 self.len() == other.len() && self.diff(other).next().is_none()
1678 }
1679}
1680
1681impl<K: Ord + Eq, V: Eq, P: SharedPointerKind> Eq for GenericOrdMap<K, V, P> {}
1682
1683impl<K, V, P> PartialOrd for GenericOrdMap<K, V, P>
1685where
1686 K: Ord,
1687 V: PartialOrd,
1688 P: SharedPointerKind,
1689{
1690 fn partial_cmp(&self, other: &GenericOrdMap<K, V, P>) -> Option<Ordering> {
1691 self.iter().partial_cmp(other.iter())
1692 }
1693}
1694
1695impl<K, V, P> Ord for GenericOrdMap<K, V, P>
1696where
1697 K: Ord,
1698 V: Ord,
1699 P: SharedPointerKind,
1700{
1701 fn cmp(&self, other: &Self) -> Ordering {
1702 self.iter().cmp(other.iter())
1703 }
1704}
1705
1706impl<K, V, P> Hash for GenericOrdMap<K, V, P>
1707where
1708 K: Ord + Hash,
1709 V: Hash,
1710 P: SharedPointerKind,
1711{
1712 fn hash<H>(&self, state: &mut H)
1713 where
1714 H: Hasher,
1715 {
1716 for i in self.iter() {
1717 i.hash(state);
1718 }
1719 }
1720}
1721
1722impl<K, V, P: SharedPointerKind> Default for GenericOrdMap<K, V, P> {
1723 fn default() -> Self {
1724 Self::new()
1725 }
1726}
1727
1728impl<K, V, P> Add for &GenericOrdMap<K, V, P>
1729where
1730 K: Ord + Clone,
1731 V: Clone,
1732 P: SharedPointerKind,
1733{
1734 type Output = GenericOrdMap<K, V, P>;
1735
1736 fn add(self, other: Self) -> Self::Output {
1737 self.clone().union(other.clone())
1738 }
1739}
1740
1741impl<K, V, P> Add for GenericOrdMap<K, V, P>
1742where
1743 K: Ord + Clone,
1744 V: Clone,
1745 P: SharedPointerKind,
1746{
1747 type Output = GenericOrdMap<K, V, P>;
1748
1749 fn add(self, other: Self) -> Self::Output {
1750 self.union(other)
1751 }
1752}
1753
1754impl<K, V, P> Sum for GenericOrdMap<K, V, P>
1755where
1756 K: Ord + Clone,
1757 V: Clone,
1758 P: SharedPointerKind,
1759{
1760 fn sum<I>(it: I) -> Self
1761 where
1762 I: Iterator<Item = Self>,
1763 {
1764 it.fold(Self::default(), |a, b| a + b)
1765 }
1766}
1767
1768impl<K, V, RK, RV, P> Extend<(RK, RV)> for GenericOrdMap<K, V, P>
1769where
1770 K: Ord + Clone + From<RK>,
1771 V: Clone + From<RV>,
1772 P: SharedPointerKind,
1773{
1774 fn extend<I>(&mut self, iter: I)
1775 where
1776 I: IntoIterator<Item = (RK, RV)>,
1777 {
1778 for (key, value) in iter {
1779 self.insert(From::from(key), From::from(value));
1780 }
1781 }
1782}
1783
1784impl<BK, K, V, P: SharedPointerKind> Index<&BK> for GenericOrdMap<K, V, P>
1785where
1786 BK: Ord + ?Sized,
1787 K: Ord + Borrow<BK>,
1788{
1789 type Output = V;
1790
1791 fn index(&self, key: &BK) -> &Self::Output {
1792 match self.get(key) {
1793 None => panic!("OrdMap::index: invalid key"),
1794 Some(value) => value,
1795 }
1796 }
1797}
1798
1799impl<BK, K, V, P> IndexMut<&BK> for GenericOrdMap<K, V, P>
1800where
1801 BK: Ord + ?Sized,
1802 K: Ord + Clone + Borrow<BK>,
1803 V: Clone,
1804 P: SharedPointerKind,
1805{
1806 fn index_mut(&mut self, key: &BK) -> &mut Self::Output {
1807 match self.get_mut(key) {
1808 None => panic!("OrdMap::index: invalid key"),
1809 Some(value) => value,
1810 }
1811 }
1812}
1813
1814impl<K, V, P> Debug for GenericOrdMap<K, V, P>
1815where
1816 K: Ord + Debug,
1817 V: Debug,
1818 P: SharedPointerKind,
1819{
1820 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
1821 let mut d = f.debug_map();
1822 for (k, v) in self.iter() {
1823 d.entry(k, v);
1824 }
1825 d.finish()
1826 }
1827}
1828
1829pub struct Iter<'a, K, V, P: SharedPointerKind> {
1833 it: NodeIter<'a, K, V, P>,
1834}
1835
1836impl<'a, K, V, P: SharedPointerKind> Clone for Iter<'a, K, V, P> {
1838 fn clone(&self) -> Self {
1839 Iter {
1840 it: self.it.clone(),
1841 }
1842 }
1843}
1844
1845impl<'a, K, V, P> Iterator for Iter<'a, K, V, P>
1846where
1847 P: SharedPointerKind,
1848{
1849 type Item = (&'a K, &'a V);
1850
1851 fn next(&mut self) -> Option<Self::Item> {
1852 self.it.next()
1853 }
1854
1855 fn size_hint(&self) -> (usize, Option<usize>) {
1858 self.it.size_hint()
1859 }
1860}
1861
1862impl<'a, K, V, P> DoubleEndedIterator for Iter<'a, K, V, P>
1863where
1864 P: SharedPointerKind,
1865{
1866 fn next_back(&mut self) -> Option<Self::Item> {
1867 self.it.next_back()
1868 }
1869}
1870
1871impl<'a, K, V, P> ExactSizeIterator for Iter<'a, K, V, P> where P: SharedPointerKind {}
1872impl<'a, K, V, P> FusedIterator for Iter<'a, K, V, P> where P: SharedPointerKind {}
1873
1874#[derive(Debug)]
1876pub struct RangedIter<'a, K, V, P: SharedPointerKind> {
1877 it: NodeIter<'a, K, V, P>,
1878}
1879
1880impl<'a, K, V, P: SharedPointerKind> Clone for RangedIter<'a, K, V, P> {
1882 fn clone(&self) -> Self {
1883 RangedIter {
1884 it: self.it.clone(),
1885 }
1886 }
1887}
1888
1889impl<'a, K, V, P> Iterator for RangedIter<'a, K, V, P>
1890where
1891 P: SharedPointerKind,
1892{
1893 type Item = (&'a K, &'a V);
1894
1895 fn next(&mut self) -> Option<Self::Item> {
1896 self.it.next()
1897 }
1898
1899 fn size_hint(&self) -> (usize, Option<usize>) {
1900 self.it.size_hint()
1901 }
1902}
1903
1904impl<'a, K, V, P> DoubleEndedIterator for RangedIter<'a, K, V, P>
1905where
1906 P: SharedPointerKind,
1907{
1908 fn next_back(&mut self) -> Option<Self::Item> {
1909 self.it.next_back()
1910 }
1911}
1912impl<'a, K, V, P> FusedIterator for RangedIter<'a, K, V, P> where P: SharedPointerKind {}
1913
1914pub struct DiffIter<'a, 'b, K, V, P: SharedPointerKind> {
1916 it1: Cursor<'a, K, V, P>,
1917 it2: Cursor<'b, K, V, P>,
1918}
1919
1920#[derive(PartialEq, Eq, Debug)]
1922pub enum DiffItem<'a, 'b, K, V> {
1923 Add(&'b K, &'b V),
1925 Update {
1927 old: (&'a K, &'a V),
1929 new: (&'b K, &'b V),
1931 },
1932 Remove(&'a K, &'a V),
1934}
1935
1936impl<'a, 'b, K, V, P> Iterator for DiffIter<'a, 'b, K, V, P>
1937where
1938 K: Ord,
1939 V: PartialEq,
1940 P: SharedPointerKind,
1941{
1942 type Item = DiffItem<'a, 'b, K, V>;
1943
1944 fn next(&mut self) -> Option<Self::Item> {
1945 loop {
1946 match (self.it1.peek(), self.it2.peek()) {
1947 (Some((k1, v1)), Some((k2, v2))) => match k1.cmp(k2) {
1948 Ordering::Less => {
1949 self.it1.next();
1950 break Some(DiffItem::Remove(k1, v1));
1951 }
1952 Ordering::Equal => {
1953 self.it1.advance_skipping_shared(&mut self.it2);
1955 if v1 != v2 {
1956 break Some(DiffItem::Update {
1957 old: (k1, v1),
1958 new: (k2, v2),
1959 });
1960 }
1961 }
1962 Ordering::Greater => {
1963 self.it2.next();
1964 break Some(DiffItem::Add(k2, v2));
1965 }
1966 },
1967 (Some((k1, v1)), None) => {
1968 self.it1.next();
1969 break Some(DiffItem::Remove(k1, v1));
1970 }
1971 (None, Some((k2, v2))) => {
1972 self.it2.next();
1973 break Some(DiffItem::Add(k2, v2));
1974 }
1975 (None, None) => break None,
1976 }
1977 }
1978 }
1979}
1980
1981impl<'a, 'b, K, V, P> FusedIterator for DiffIter<'a, 'b, K, V, P>
1982where
1983 K: Ord,
1984 V: PartialEq,
1985 P: SharedPointerKind,
1986{
1987}
1988
1989pub struct Keys<'a, K, V, P: SharedPointerKind> {
1991 it: Iter<'a, K, V, P>,
1992}
1993
1994impl<'a, K, V, P> Iterator for Keys<'a, K, V, P>
1995where
1996 K: 'a + Ord,
1997 V: 'a,
1998 P: SharedPointerKind,
1999{
2000 type Item = &'a K;
2001
2002 fn next(&mut self) -> Option<Self::Item> {
2003 self.it.next().map(|(k, _)| k)
2004 }
2005
2006 fn size_hint(&self) -> (usize, Option<usize>) {
2007 self.it.size_hint()
2008 }
2009}
2010
2011impl<'a, K, V, P> DoubleEndedIterator for Keys<'a, K, V, P>
2012where
2013 K: 'a + Ord,
2014 V: 'a,
2015 P: SharedPointerKind,
2016{
2017 fn next_back(&mut self) -> Option<Self::Item> {
2018 match self.it.next_back() {
2019 None => None,
2020 Some((k, _)) => Some(k),
2021 }
2022 }
2023}
2024
2025impl<'a, K, V, P> ExactSizeIterator for Keys<'a, K, V, P>
2026where
2027 K: 'a + Ord,
2028 V: 'a,
2029 P: SharedPointerKind,
2030{
2031}
2032
2033impl<'a, K, V, P> FusedIterator for Keys<'a, K, V, P>
2034where
2035 K: 'a + Ord,
2036 V: 'a,
2037 P: SharedPointerKind,
2038{
2039}
2040
2041pub struct Values<'a, K, V, P: SharedPointerKind> {
2043 it: Iter<'a, K, V, P>,
2044}
2045
2046impl<'a, K, V, P> Iterator for Values<'a, K, V, P>
2047where
2048 K: 'a + Ord,
2049 V: 'a,
2050 P: SharedPointerKind,
2051{
2052 type Item = &'a V;
2053
2054 fn next(&mut self) -> Option<Self::Item> {
2055 self.it.next().map(|(_, v)| v)
2056 }
2057
2058 fn size_hint(&self) -> (usize, Option<usize>) {
2059 self.it.size_hint()
2060 }
2061}
2062
2063impl<'a, K, V, P> DoubleEndedIterator for Values<'a, K, V, P>
2064where
2065 K: 'a + Ord,
2066 V: 'a,
2067 P: SharedPointerKind,
2068{
2069 fn next_back(&mut self) -> Option<Self::Item> {
2070 match self.it.next_back() {
2071 None => None,
2072 Some((_, v)) => Some(v),
2073 }
2074 }
2075}
2076
2077impl<'a, K, V, P> FusedIterator for Values<'a, K, V, P>
2078where
2079 K: 'a + Ord,
2080 V: 'a,
2081 P: SharedPointerKind,
2082{
2083}
2084
2085impl<'a, K, V, P> ExactSizeIterator for Values<'a, K, V, P>
2086where
2087 K: 'a + Ord,
2088 V: 'a,
2089 P: SharedPointerKind,
2090{
2091}
2092
2093impl<K, V, RK, RV, P> FromIterator<(RK, RV)> for GenericOrdMap<K, V, P>
2094where
2095 K: Ord + Clone + From<RK>,
2096 V: Clone + From<RV>,
2097 P: SharedPointerKind,
2098{
2099 fn from_iter<T>(i: T) -> Self
2100 where
2101 T: IntoIterator<Item = (RK, RV)>,
2102 {
2103 let mut m = GenericOrdMap::default();
2104 for (k, v) in i {
2105 m.insert(From::from(k), From::from(v));
2106 }
2107 m
2108 }
2109}
2110
2111impl<'a, K, V, P> IntoIterator for &'a GenericOrdMap<K, V, P>
2112where
2113 K: Ord,
2114 P: SharedPointerKind,
2115{
2116 type Item = (&'a K, &'a V);
2117 type IntoIter = Iter<'a, K, V, P>;
2118
2119 fn into_iter(self) -> Self::IntoIter {
2120 self.iter()
2121 }
2122}
2123
2124impl<K, V, P> IntoIterator for GenericOrdMap<K, V, P>
2125where
2126 K: Clone,
2127 V: Clone,
2128 P: SharedPointerKind,
2129{
2130 type Item = (K, V);
2131 type IntoIter = ConsumingIter<K, V, P>;
2132
2133 fn into_iter(self) -> Self::IntoIter {
2134 ConsumingIter {
2135 it: NodeConsumingIter::new(self.root, self.size),
2136 }
2137 }
2138}
2139
2140pub struct ConsumingIter<K, V, P: SharedPointerKind> {
2142 it: NodeConsumingIter<K, V, P>,
2143}
2144
2145impl<K, V, P> Iterator for ConsumingIter<K, V, P>
2146where
2147 K: Clone,
2148 V: Clone,
2149 P: SharedPointerKind,
2150{
2151 type Item = (K, V);
2152 fn next(&mut self) -> Option<Self::Item> {
2153 self.it.next()
2154 }
2155 fn size_hint(&self) -> (usize, Option<usize>) {
2156 self.it.size_hint()
2157 }
2158}
2159
2160impl<K: Clone, V: Clone, P: SharedPointerKind> DoubleEndedIterator for ConsumingIter<K, V, P> {
2161 fn next_back(&mut self) -> Option<Self::Item> {
2162 self.it.next_back()
2163 }
2164}
2165
2166impl<K, V, P> ExactSizeIterator for ConsumingIter<K, V, P>
2167where
2168 K: Clone,
2169 V: Clone,
2170 P: SharedPointerKind,
2171{
2172}
2173impl<K, V, P> FusedIterator for ConsumingIter<K, V, P>
2174where
2175 K: Clone,
2176 V: Clone,
2177 P: SharedPointerKind,
2178{
2179}
2180
2181impl<K, V, P: SharedPointerKind> AsRef<GenericOrdMap<K, V, P>> for GenericOrdMap<K, V, P> {
2184 fn as_ref(&self) -> &Self {
2185 self
2186 }
2187}
2188
2189impl<K, V, OK, OV, P1, P2> From<&GenericOrdMap<&K, &V, P2>> for GenericOrdMap<OK, OV, P1>
2190where
2191 K: Ord + ToOwned<Owned = OK> + ?Sized,
2192 V: ToOwned<Owned = OV> + ?Sized,
2193 OK: Ord + Clone + Borrow<K>,
2194 OV: Clone + Borrow<V>,
2195 P1: SharedPointerKind,
2196 P2: SharedPointerKind,
2197{
2198 fn from(m: &GenericOrdMap<&K, &V, P2>) -> Self {
2199 m.iter()
2200 .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
2201 .collect()
2202 }
2203}
2204
2205impl<'a, K, V, RK, RV, OK, OV, P> From<&'a [(RK, RV)]> for GenericOrdMap<K, V, P>
2206where
2207 K: Ord + Clone + From<OK>,
2208 V: Clone + From<OV>,
2209 OK: Borrow<RK>,
2210 OV: Borrow<RV>,
2211 RK: ToOwned<Owned = OK>,
2212 RV: ToOwned<Owned = OV>,
2213 P: SharedPointerKind,
2214{
2215 fn from(m: &'a [(RK, RV)]) -> GenericOrdMap<K, V, P> {
2216 m.iter()
2217 .map(|(k, v)| (k.to_owned(), v.to_owned()))
2218 .collect()
2219 }
2220}
2221
2222impl<K, V, RK, RV, P> From<Vec<(RK, RV)>> for GenericOrdMap<K, V, P>
2223where
2224 K: Ord + Clone + From<RK>,
2225 V: Clone + From<RV>,
2226 P: SharedPointerKind,
2227{
2228 fn from(m: Vec<(RK, RV)>) -> GenericOrdMap<K, V, P> {
2229 m.into_iter().collect()
2230 }
2231}
2232
2233impl<'a, K: Ord, V, RK, RV, OK, OV, P> From<&'a Vec<(RK, RV)>> for GenericOrdMap<K, V, P>
2234where
2235 K: Ord + Clone + From<OK>,
2236 V: Clone + From<OV>,
2237 OK: Borrow<RK>,
2238 OV: Borrow<RV>,
2239 RK: ToOwned<Owned = OK>,
2240 RV: ToOwned<Owned = OV>,
2241 P: SharedPointerKind,
2242{
2243 fn from(m: &'a Vec<(RK, RV)>) -> GenericOrdMap<K, V, P> {
2244 m.iter()
2245 .map(|(k, v)| (k.to_owned(), v.to_owned()))
2246 .collect()
2247 }
2248}
2249
2250impl<K: Ord, V, RK: Eq + Hash, RV, P> From<collections::HashMap<RK, RV>> for GenericOrdMap<K, V, P>
2251where
2252 K: Ord + Clone + From<RK>,
2253 V: Clone + From<RV>,
2254 P: SharedPointerKind,
2255{
2256 fn from(m: collections::HashMap<RK, RV>) -> GenericOrdMap<K, V, P> {
2257 m.into_iter().collect()
2258 }
2259}
2260
2261impl<'a, K, V, OK, OV, RK, RV, P> From<&'a collections::HashMap<RK, RV>> for GenericOrdMap<K, V, P>
2262where
2263 K: Ord + Clone + From<OK>,
2264 V: Clone + From<OV>,
2265 OK: Borrow<RK>,
2266 OV: Borrow<RV>,
2267 RK: Hash + Eq + ToOwned<Owned = OK>,
2268 RV: ToOwned<Owned = OV>,
2269 P: SharedPointerKind,
2270{
2271 fn from(m: &'a collections::HashMap<RK, RV>) -> GenericOrdMap<K, V, P> {
2272 m.iter()
2273 .map(|(k, v)| (k.to_owned(), v.to_owned()))
2274 .collect()
2275 }
2276}
2277
2278impl<K: Ord, V, RK, RV, P> From<collections::BTreeMap<RK, RV>> for GenericOrdMap<K, V, P>
2279where
2280 K: Ord + Clone + From<RK>,
2281 V: Clone + From<RV>,
2282 P: SharedPointerKind,
2283{
2284 fn from(m: collections::BTreeMap<RK, RV>) -> GenericOrdMap<K, V, P> {
2285 m.into_iter().collect()
2286 }
2287}
2288
2289impl<'a, K: Ord, V, RK, RV, OK, OV, P> From<&'a collections::BTreeMap<RK, RV>>
2290 for GenericOrdMap<K, V, P>
2291where
2292 K: Ord + Clone + From<OK>,
2293 V: Clone + From<OV>,
2294 OK: Borrow<RK>,
2295 OV: Borrow<RV>,
2296 RK: Ord + ToOwned<Owned = OK>,
2297 RV: ToOwned<Owned = OV>,
2298 P: SharedPointerKind,
2299{
2300 fn from(m: &'a collections::BTreeMap<RK, RV>) -> GenericOrdMap<K, V, P> {
2301 m.iter()
2302 .map(|(k, v)| (k.to_owned(), v.to_owned()))
2303 .collect()
2304 }
2305}
2306
2307impl<
2308 K: Ord + Hash + Eq + Clone,
2309 V: Clone,
2310 S: BuildHasher + Clone,
2311 P1: SharedPointerKind,
2312 P2: SharedPointerKind,
2313 > From<GenericHashMap<K, V, S, P2>> for GenericOrdMap<K, V, P1>
2314{
2315 fn from(m: GenericHashMap<K, V, S, P2>) -> Self {
2316 m.into_iter().collect()
2317 }
2318}
2319
2320impl<
2321 'a,
2322 K: Ord + Hash + Eq + Clone,
2323 V: Clone,
2324 S: BuildHasher + Clone,
2325 P1: SharedPointerKind,
2326 P2: SharedPointerKind,
2327 > From<&'a GenericHashMap<K, V, S, P2>> for GenericOrdMap<K, V, P1>
2328{
2329 fn from(m: &'a GenericHashMap<K, V, S, P2>) -> Self {
2330 m.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
2331 }
2332}
2333
2334#[cfg(any(test, feature = "proptest"))]
2336#[doc(hidden)]
2337pub mod proptest {
2338 #[deprecated(
2339 since = "14.3.0",
2340 note = "proptest strategies have moved to imbl::proptest"
2341 )]
2342 pub use crate::proptest::ord_map;
2343}
2344
2345#[cfg(test)]
2348mod test {
2349 use std::collections::BTreeMap;
2350
2351 use super::*;
2352 use crate::proptest::*;
2353 #[rustfmt::skip]
2354 use ::proptest::num::{i16, usize};
2355 #[rustfmt::skip]
2356 use ::proptest::{bool, collection, proptest};
2357 use static_assertions::{assert_impl_all, assert_not_impl_any};
2358
2359 assert_impl_all!(OrdMap<i32, i32>: Send, Sync);
2360 assert_not_impl_any!(OrdMap<i32, *const i32>: Send, Sync);
2361 assert_not_impl_any!(OrdMap<*const i32, i32>: Send, Sync);
2362 assert_covariant!(OrdMap<T, i32> in T);
2363 assert_covariant!(OrdMap<i32, T> in T);
2364
2365 #[test]
2366 fn iterates_in_order() {
2367 let map = ordmap! {
2368 2 => 22,
2369 1 => 11,
2370 3 => 33,
2371 8 => 88,
2372 9 => 99,
2373 4 => 44,
2374 5 => 55,
2375 7 => 77,
2376 6 => 66
2377 };
2378 let mut it = map.iter();
2379 assert_eq!(it.next(), Some((&1, &11)));
2380 assert_eq!(it.next(), Some((&2, &22)));
2381 assert_eq!(it.next(), Some((&3, &33)));
2382 assert_eq!(it.next(), Some((&4, &44)));
2383 assert_eq!(it.next(), Some((&5, &55)));
2384 assert_eq!(it.next(), Some((&6, &66)));
2385 assert_eq!(it.next(), Some((&7, &77)));
2386 assert_eq!(it.next(), Some((&8, &88)));
2387 assert_eq!(it.next(), Some((&9, &99)));
2388 assert_eq!(it.next(), None);
2389 }
2390
2391 #[test]
2392 fn into_iter() {
2393 let map = ordmap! {
2394 2 => 22,
2395 1 => 11,
2396 3 => 33,
2397 8 => 88,
2398 9 => 99,
2399 4 => 44,
2400 5 => 55,
2401 7 => 77,
2402 6 => 66
2403 };
2404 let mut vec = vec![];
2405 for (k, v) in map {
2406 assert_eq!(k * 11, v);
2407 vec.push(k)
2408 }
2409 assert_eq!(vec, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]);
2410 }
2411
2412 struct PanicOnClone;
2413
2414 impl Clone for PanicOnClone {
2415 fn clone(&self) -> Self {
2416 panic!("PanicOnClone::clone called")
2417 }
2418 }
2419
2420 #[test]
2421 fn into_iter_no_clone() {
2422 let mut map = OrdMap::new();
2423 let mut map_rev = OrdMap::new();
2424 for i in 0..10_000 {
2425 map.insert(i, PanicOnClone);
2426 map_rev.insert(i, PanicOnClone);
2427 }
2428 let _ = map.into_iter().collect::<Vec<_>>();
2429 let _ = map_rev.into_iter().rev().collect::<Vec<_>>();
2430 }
2431
2432 #[test]
2433 fn iter_no_clone() {
2434 let mut map = OrdMap::new();
2435 for i in 0..10_000 {
2436 map.insert(i, PanicOnClone);
2437 }
2438 let _ = map.iter().collect::<Vec<_>>();
2439 let _ = map.iter().rev().collect::<Vec<_>>();
2440 }
2441
2442 #[test]
2443 fn deletes_correctly() {
2444 let map = ordmap! {
2445 2 => 22,
2446 1 => 11,
2447 3 => 33,
2448 8 => 88,
2449 9 => 99,
2450 4 => 44,
2451 5 => 55,
2452 7 => 77,
2453 6 => 66
2454 };
2455 assert_eq!(map.extract(&11), None);
2456 let (popped, less) = map.extract(&5).unwrap();
2457 assert_eq!(popped, 55);
2458 let mut it = less.iter();
2459 assert_eq!(it.next(), Some((&1, &11)));
2460 assert_eq!(it.next(), Some((&2, &22)));
2461 assert_eq!(it.next(), Some((&3, &33)));
2462 assert_eq!(it.next(), Some((&4, &44)));
2463 assert_eq!(it.next(), Some((&6, &66)));
2464 assert_eq!(it.next(), Some((&7, &77)));
2465 assert_eq!(it.next(), Some((&8, &88)));
2466 assert_eq!(it.next(), Some((&9, &99)));
2467 assert_eq!(it.next(), None);
2468 }
2469
2470 #[test]
2471 fn debug_output() {
2472 assert_eq!(
2473 format!("{:?}", ordmap! { 3 => 4, 5 => 6, 1 => 2 }),
2474 "{1: 2, 3: 4, 5: 6}"
2475 );
2476 }
2477
2478 #[test]
2479 fn equality2() {
2480 let v1 = "1".to_string();
2481 let v2 = "1".to_string();
2482 assert_eq!(v1, v2);
2483 let p1 = Vec::<String>::new();
2484 let p2 = Vec::<String>::new();
2485 assert_eq!(p1, p2);
2486 let c1: OrdMap<_, _> = OrdMap::unit(v1, p1);
2487 let c2: OrdMap<_, _> = OrdMap::unit(v2, p2);
2488 assert_eq!(c1, c2);
2489 }
2490
2491 #[test]
2492 fn insert_remove_single_mut() {
2493 let mut m = OrdMap::new();
2494 m.insert(0, 0);
2495 assert_eq!(OrdMap::<_, _>::unit(0, 0), m);
2496 m.remove(&0);
2497 assert_eq!(OrdMap::new(), m);
2498 }
2499
2500 #[test]
2501 fn double_ended_iterator_1() {
2502 let m = ordmap! {1 => 1, 2 => 2, 3 => 3, 4 => 4};
2503 let mut it = m.iter();
2504 assert_eq!(Some((&1, &1)), it.next());
2505 assert_eq!(Some((&4, &4)), it.next_back());
2506 assert_eq!(Some((&2, &2)), it.next());
2507 assert_eq!(Some((&3, &3)), it.next_back());
2508 assert_eq!(None, it.next());
2509 }
2510
2511 #[test]
2512 fn double_ended_iterator_2() {
2513 let m = ordmap! {1 => 1, 2 => 2, 3 => 3, 4 => 4};
2514 let mut it = m.iter();
2515 assert_eq!(Some((&1, &1)), it.next());
2516 assert_eq!(Some((&4, &4)), it.next_back());
2517 assert_eq!(Some((&2, &2)), it.next());
2518 assert_eq!(Some((&3, &3)), it.next_back());
2519 assert_eq!(None, it.next_back());
2520 }
2521
2522 #[test]
2523 fn safe_mutation() {
2524 let v1 = OrdMap::<_, _>::from_iter((0..131_072).map(|i| (i, i)));
2525 let mut v2 = v1.clone();
2526 v2.insert(131_000, 23);
2527 assert_eq!(Some(&23), v2.get(&131_000));
2528 assert_eq!(Some(&131_000), v1.get(&131_000));
2529 }
2530
2531 #[test]
2532 fn index_operator() {
2533 let mut map = ordmap! {1 => 2, 3 => 4, 5 => 6};
2534 assert_eq!(4, map[&3]);
2535 map[&3] = 8;
2536 assert_eq!(ordmap! {1 => 2, 3 => 8, 5 => 6}, map);
2537 }
2538
2539 #[test]
2540 fn entry_api() {
2541 let mut map = ordmap! {"bar" => 5};
2542 map.entry("foo").and_modify(|v| *v += 5).or_insert(1);
2543 assert_eq!(1, map[&"foo"]);
2544 map.entry("foo").and_modify(|v| *v += 5).or_insert(1);
2545 assert_eq!(6, map[&"foo"]);
2546 map.entry("bar").and_modify(|v| *v += 5).or_insert(1);
2547 assert_eq!(10, map[&"bar"]);
2548 assert_eq!(
2549 10,
2550 match map.entry("bar") {
2551 Entry::Occupied(entry) => entry.remove(),
2552 _ => panic!(),
2553 }
2554 );
2555 assert!(!map.contains_key(&"bar"));
2556 }
2557
2558 #[test]
2559 fn match_string_keys_with_string_slices() {
2560 let mut map: OrdMap<String, i32> =
2561 From::from(ºap! { "foo" => &1, "bar" => &2, "baz" => &3 });
2562 assert_eq!(Some(&1), map.get("foo"));
2563 map = map.without("foo");
2564 assert_eq!(Some(3), map.remove("baz"));
2565 map["bar"] = 8;
2566 assert_eq!(8, map["bar"]);
2567 }
2568
2569 #[test]
2570 fn ranged_iter() {
2571 let map: OrdMap<i32, i32> = ordmap![1=>2, 2=>3, 3=>4, 4=>5, 5=>6, 7=>8];
2572 let range: Vec<(i32, i32)> = map.range(..).map(|(k, v)| (*k, *v)).collect();
2573 assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (7, 8)], range);
2574 let range: Vec<(i32, i32)> = map.range(..).rev().map(|(k, v)| (*k, *v)).collect();
2575 assert_eq!(vec![(7, 8), (5, 6), (4, 5), (3, 4), (2, 3), (1, 2)], range);
2576 let range: Vec<(i32, i32)> = map.range(&2..&5).map(|(k, v)| (*k, *v)).collect();
2577 assert_eq!(vec![(2, 3), (3, 4), (4, 5)], range);
2578 let range: Vec<(i32, i32)> = map.range(&2..&5).rev().map(|(k, v)| (*k, *v)).collect();
2579 assert_eq!(vec![(4, 5), (3, 4), (2, 3)], range);
2580 let range: Vec<(i32, i32)> = map.range(&3..).map(|(k, v)| (*k, *v)).collect();
2581 assert_eq!(vec![(3, 4), (4, 5), (5, 6), (7, 8)], range);
2582 let range: Vec<(i32, i32)> = map.range(&3..).rev().map(|(k, v)| (*k, *v)).collect();
2583 assert_eq!(vec![(7, 8), (5, 6), (4, 5), (3, 4)], range);
2584 let range: Vec<(i32, i32)> = map.range(..4).map(|(k, v)| (*k, *v)).collect();
2585 assert_eq!(vec![(1, 2), (2, 3), (3, 4)], range);
2586 let range: Vec<(i32, i32)> = map.range(..&4).rev().map(|(k, v)| (*k, *v)).collect();
2587 assert_eq!(vec![(3, 4), (2, 3), (1, 2)], range);
2588 let range: Vec<(i32, i32)> = map.range(..=&3).map(|(k, v)| (*k, *v)).collect();
2589 assert_eq!(vec![(1, 2), (2, 3), (3, 4)], range);
2590 let range: Vec<(i32, i32)> = map.range(..=&3).rev().map(|(k, v)| (*k, *v)).collect();
2591 assert_eq!(vec![(3, 4), (2, 3), (1, 2)], range);
2592 let range: Vec<(i32, i32)> = map.range(..&6).map(|(k, v)| (*k, *v)).collect();
2593 assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)], range);
2594 let range: Vec<(i32, i32)> = map.range(..=&6).map(|(k, v)| (*k, *v)).collect();
2595 assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)], range);
2596
2597 assert_eq!(map.range(&2..&5).size_hint(), (0, Some(6)));
2598 let mut iter = map.range(&2..&5);
2599 iter.next();
2600 assert_eq!(iter.size_hint(), (0, Some(5)));
2601 }
2602
2603 #[test]
2604 fn range_iter_big() {
2605 use crate::nodes::btree::NODE_SIZE;
2606 use std::ops::Bound::Included;
2607 const N: usize = NODE_SIZE * NODE_SIZE * NODE_SIZE / 2; let data = (1usize..N).filter(|i| i % 2 == 0).map(|i| (i, ()));
2610 let bmap = data
2611 .clone()
2612 .collect::<std::collections::BTreeMap<usize, ()>>();
2613 let omap = data.collect::<OrdMap<usize, ()>>();
2614 assert_eq!(bmap.len(), omap.len());
2615
2616 for i in (0..NODE_SIZE * 5).chain(N - NODE_SIZE * 5..=N + 1) {
2617 assert_eq!(omap.range(i..).count(), bmap.range(i..).count());
2618 assert_eq!(omap.range(..i).count(), bmap.range(..i).count());
2619 assert_eq!(
2620 omap.range(i..(i + 7)).count(),
2621 bmap.range(i..(i + 7)).count()
2622 );
2623 assert_eq!(
2624 omap.range(i..=(i + 7)).count(),
2625 bmap.range(i..=(i + 7)).count()
2626 );
2627 assert_eq!(
2628 omap.range((Included(i), Included(i + 7))).count(),
2629 bmap.range((Included(i), Included(i + 7))).count(),
2630 );
2631 assert_eq!(omap.range(..=i).next_back(), omap.get_prev(&i));
2632 assert_eq!(omap.range(i..).next(), omap.get_next(&i));
2633 }
2634 }
2635
2636 #[test]
2637 fn issue_124() {
2638 let mut map = OrdMap::new();
2639 let contents = include_str!("test-fixtures/issue_124.txt");
2640 for line in contents.lines() {
2641 if let Some(tail) = line.strip_prefix("insert ") {
2642 map.insert(tail.parse::<u32>().unwrap(), 0);
2643 } else if let Some(tail) = line.strip_prefix("remove ") {
2644 map.remove(&tail.parse::<u32>().unwrap());
2645 }
2646 }
2647 }
2648
2649 fn expected_diff<'a, K, V, P>(
2650 a: &'a GenericOrdMap<K, V, P>,
2651 b: &'a GenericOrdMap<K, V, P>,
2652 ) -> Vec<DiffItem<'a, 'a, K, V>>
2653 where
2654 K: Ord + Clone,
2655 V: PartialEq + Clone,
2656 P: SharedPointerKind,
2657 {
2658 let mut diff = Vec::new();
2659 for (k, v) in a.iter() {
2660 if let Some(v2) = b.get(k) {
2661 if v != v2 {
2662 diff.push(DiffItem::Update {
2663 old: (k, v),
2664 new: (k, v2),
2665 });
2666 }
2667 } else {
2668 diff.push(DiffItem::Remove(k, v));
2669 }
2670 }
2671 for (k, v) in b.iter() {
2672 if a.get(k).is_none() {
2673 diff.push(DiffItem::Add(k, v));
2674 }
2675 }
2676 fn diff_item_key<'a, 'b, K, V>(di: &'a DiffItem<'b, 'b, K, V>) -> &'b K {
2677 match di {
2678 DiffItem::Add(k, _) => k,
2679 DiffItem::Remove(k, _) => k,
2680 DiffItem::Update { old: (k, _), .. } => k,
2681 }
2682 }
2683 diff.sort_unstable_by(|a, b| diff_item_key(a).cmp(diff_item_key(b)));
2684 diff
2685 }
2686
2687 proptest! {
2688 #[test]
2689 fn length(ref input in collection::btree_map(i16::ANY, i16::ANY, 0..1000)) {
2690 let map: OrdMap<i16, i16> = OrdMap::from(input.clone());
2691 assert_eq!(input.len(), map.len());
2692 }
2693
2694 #[test]
2695 fn order(ref input in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2696 let map: OrdMap<i16, i16> = OrdMap::from(input.clone());
2697 let keys = map.keys().cloned().collect::<Vec<_>>();
2698 let mut expected_keys = input.keys().cloned().collect::<Vec<_>>();
2699 expected_keys.sort();
2700 assert_eq!(keys, expected_keys);
2701 }
2702
2703 #[test]
2704 fn overwrite_values(ref vec in collection::vec((i16::ANY, i16::ANY), 1..1000), index_rand in usize::ANY, new_val in i16::ANY) {
2705 let index = vec[index_rand % vec.len()].0;
2706 let map1 = OrdMap::<_, _>::from_iter(vec.clone());
2707 let map2 = map1.update(index, new_val);
2708 for (k, v) in map2 {
2709 if k == index {
2710 assert_eq!(v, new_val);
2711 } else {
2712 match map1.get(&k) {
2713 None => panic!("map1 didn't have key {:?}", k),
2714 Some(other_v) => {
2715 assert_eq!(v, *other_v);
2716 }
2717 }
2718 }
2719 }
2720 }
2721
2722 #[test]
2723 fn delete_values(ref vec in collection::vec((usize::ANY, usize::ANY), 1..1000), index_rand in usize::ANY) {
2724 let index = vec[index_rand % vec.len()].0;
2725 let map1: OrdMap<usize, usize> = OrdMap::from_iter(vec.clone());
2726 let map2 = map1.without(&index);
2727 assert_eq!(map1.len(), map2.len() + 1);
2728 for k in map2.keys() {
2729 assert_ne!(*k, index);
2730 }
2731 }
2732
2733 #[test]
2734 fn insert_and_delete_values(
2735 ref input in ord_map(0usize..64, 0usize..64, 1..1000),
2736 ref ops in collection::vec((bool::ANY, usize::ANY, usize::ANY), 1..1000)
2737 ) {
2738 let mut map = input.clone();
2739 let mut tree: collections::BTreeMap<usize, usize> = input.iter().map(|(k, v)| (*k, *v)).collect();
2740 for (ins, key, val) in ops {
2741 if *ins {
2742 tree.insert(*key, *val);
2743 map = map.update(*key, *val)
2744 } else {
2745 tree.remove(key);
2746 map = map.without(key)
2747 }
2748 }
2749 assert!(map.iter().map(|(k, v)| (*k, *v)).eq(tree.iter().map(|(k, v)| (*k, *v))));
2750 }
2751
2752 #[test]
2753 fn proptest_works(ref m in ord_map(0..9999, ".*", 10..100)) {
2754 assert!(m.len() < 100);
2755 assert!(m.len() >= 10);
2756 }
2757
2758 #[test]
2759 fn insert_and_length(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2760 let mut map = OrdMap::new();
2761 for (k, v) in m.iter() {
2762 map = map.update(*k, *v)
2763 }
2764 assert_eq!(m.len(), map.len());
2765 }
2766
2767 #[test]
2768 fn from_iterator(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2769 let map: OrdMap<i16, i16> =
2770 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2771 assert_eq!(m.len(), map.len());
2772 }
2773
2774 #[test]
2775 fn iterate_over(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2776 let map: OrdMap<i16, i16> =
2777 OrdMap::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2778 let expected = m.iter().map(|(k, v)| (*k, *v)).collect::<BTreeMap<_, _>>();
2779 assert!(map.iter().eq(expected.iter()));
2780 }
2781
2782 #[test]
2783 fn iterate_over_rev(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2784 let map: OrdMap<i16, i16> =
2785 OrdMap::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2786 let expected = m.iter().map(|(k, v)| (*k, *v)).collect::<BTreeMap<_, _>>();
2787 assert!(map.iter().rev().eq(expected.iter().rev()));
2788 }
2789
2790 #[test]
2791 fn equality(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2792 let map1: OrdMap<i16, i16> =
2793 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2794 let map2: OrdMap<i16, i16> =
2795 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2796 assert_eq!(map1, map2);
2797 }
2798
2799 #[test]
2800 fn lookup(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2801 let map: OrdMap<i16, i16> =
2802 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2803 for (k, v) in m.iter() {
2804 assert_eq!(Some(*v), map.get(k).cloned());
2805 }
2806 }
2807
2808 #[test]
2809 fn remove(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2810 let mut map: OrdMap<i16, i16> =
2811 OrdMap::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2812 for k in m.keys() {
2813 let l = map.len();
2814 assert_eq!(m.get(k).cloned(), map.get(k).cloned());
2815 map = map.without(k);
2816 assert_eq!(None, map.get(k));
2817 assert_eq!(l - 1, map.len());
2818 }
2819 }
2820
2821 #[test]
2822 fn insert_mut(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2823 let mut mut_map = OrdMap::new();
2824 let mut map = OrdMap::new();
2825 for (k, v) in m.iter() {
2826 map = map.update(*k, *v);
2827 mut_map.insert(*k, *v);
2828 }
2829 assert_eq!(map, mut_map);
2830 }
2831
2832 #[test]
2833 fn remove_mut(ref orig in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2834 let mut map = orig.clone();
2835 for key in orig.keys() {
2836 let len = map.len();
2837 assert_eq!(orig.get(key), map.get(key));
2838 assert_eq!(orig.get(key).cloned(), map.remove(key));
2839 assert_eq!(None, map.get(key));
2840 assert_eq!(len - 1, map.len());
2841 }
2842 }
2843
2844 #[test]
2845 fn remove_alien(ref orig in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2846 let mut map: OrdMap<i16, i16> = OrdMap::from(orig.clone());
2847 for key in orig.keys() {
2848 let len = map.len();
2849 assert_eq!(orig.get(key), map.get(key));
2850 assert_eq!(orig.get(key).cloned(), map.remove(key));
2851 assert_eq!(None, map.get(key));
2852 assert_eq!(len - 1, map.len());
2853 }
2854 }
2855
2856 #[test]
2857 fn delete_and_reinsert(
2858 ref input in collection::hash_map(i16::ANY, i16::ANY, 1..1000),
2859 index_rand in usize::ANY
2860 ) {
2861 let index = *input.keys().nth(index_rand % input.len()).unwrap();
2862 let map1 = OrdMap::from_iter(input.clone());
2863 let (val, map2): (i16, _) = map1.extract(&index).unwrap();
2864 let map3 = map2.update(index, val);
2865 for key in map2.keys() {
2866 assert!(*key != index);
2867 }
2868 assert_eq!(map1.len(), map2.len() + 1);
2869 assert_eq!(map1, map3);
2870 }
2871
2872 #[test]
2873 fn exact_size_iterator(ref m in ord_map(i16::ANY, i16::ANY, 1..1000)) {
2874 let mut should_be = m.len();
2875 let mut it = m.iter();
2876 loop {
2877 assert_eq!(should_be, it.len());
2878 match it.next() {
2879 None => break,
2880 Some(_) => should_be -= 1,
2881 }
2882 }
2883 assert_eq!(0, it.len());
2884 }
2885
2886 #[test]
2887 fn diff_all_values(a in collection::vec((usize::ANY, usize::ANY), 1..1000), b in collection::vec((usize::ANY, usize::ANY), 1..1000)) {
2888 let a: OrdMap<usize, usize> = OrdMap::from(a);
2889 let b: OrdMap<usize, usize> = OrdMap::from(b);
2890
2891 let diff: Vec<_> = a.diff(&b).collect();
2892 let expected = expected_diff(&a, &b);
2893 assert_eq!(expected, diff);
2894 }
2895
2896 #[test]
2897 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)) {
2898 let a: OrdMap<usize, usize> = OrdMap::from(a);
2899 let mut b = a.clone();
2900 for (k, v) in ops {
2901 b.insert(k, v);
2902 }
2903
2904 let diff: Vec<_> = a.diff(&b).collect();
2905 let expected = expected_diff(&a, &b);
2906 assert_eq!(expected, diff);
2907 }
2908
2909 #[test]
2910 fn union(ref map1 in ord_map(i16::ANY, i16::ANY, 0..100),
2911 ref map2 in ord_map(i16::ANY, i16::ANY, 0..100)) {
2912 let union_map = map1.clone().union(map2.clone());
2913
2914 for k in map1.keys() {
2915 assert!(union_map.contains_key(k));
2916 }
2917
2918 for k in map2.keys() {
2919 assert!(union_map.contains_key(k));
2920 }
2921
2922 for (k, v) in union_map.iter() {
2923 assert_eq!(v, map1.get(k).or_else(|| map2.get(k)).unwrap());
2924 }
2925 }
2926 }
2927}