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, Iterator, Sum};
26use std::mem;
27use std::ops::{Add, Index, IndexMut, RangeBounds};
28
29use crate::hashmap::HashMap;
30use crate::nodes::btree::{BTreeValue, Insert, Node, Remove};
31#[cfg(has_specialisation)]
32use crate::util::linear_search_by;
33use crate::util::{Pool, PoolRef};
34
35pub use crate::nodes::btree::{
36 ConsumingIter, DiffItem as NodeDiffItem, DiffIter as NodeDiffIter, Iter as RangedIter,
37};
38
39#[macro_export]
58macro_rules! ordmap {
59 () => { $crate::ordmap::OrdMap::new() };
60
61 ( $( $key:expr => $value:expr ),* ) => {{
62 let mut map = $crate::ordmap::OrdMap::new();
63 $({
64 map.insert($key, $value);
65 })*;
66 map
67 }};
68}
69
70#[cfg(not(has_specialisation))]
71impl<K: Ord, V> BTreeValue for (K, V) {
72 type Key = K;
73
74 fn ptr_eq(&self, _other: &Self) -> bool {
75 false
76 }
77
78 fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
79 where
80 BK: Ord + ?Sized,
81 Self::Key: Borrow<BK>,
82 {
83 slice.binary_search_by(|value| Self::Key::borrow(&value.0).cmp(key))
84 }
85
86 fn search_value(slice: &[Self], key: &Self) -> Result<usize, usize> {
87 slice.binary_search_by(|value| value.0.cmp(&key.0))
88 }
89
90 fn cmp_keys<BK>(&self, other: &BK) -> Ordering
91 where
92 BK: Ord + ?Sized,
93 Self::Key: Borrow<BK>,
94 {
95 Self::Key::borrow(&self.0).cmp(other)
96 }
97
98 fn cmp_values(&self, other: &Self) -> Ordering {
99 self.0.cmp(&other.0)
100 }
101}
102
103#[cfg(has_specialisation)]
104impl<K: Ord, V> BTreeValue for (K, V) {
105 type Key = K;
106
107 fn ptr_eq(&self, _other: &Self) -> bool {
108 false
109 }
110
111 default fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
112 where
113 BK: Ord + ?Sized,
114 Self::Key: Borrow<BK>,
115 {
116 slice.binary_search_by(|value| Self::Key::borrow(&value.0).cmp(key))
117 }
118
119 default fn search_value(slice: &[Self], key: &Self) -> Result<usize, usize> {
120 slice.binary_search_by(|value| value.0.cmp(&key.0))
121 }
122
123 fn cmp_keys<BK>(&self, other: &BK) -> Ordering
124 where
125 BK: Ord + ?Sized,
126 Self::Key: Borrow<BK>,
127 {
128 Self::Key::borrow(&self.0).cmp(other)
129 }
130
131 fn cmp_values(&self, other: &Self) -> Ordering {
132 self.0.cmp(&other.0)
133 }
134}
135
136#[cfg(has_specialisation)]
137impl<K: Ord + Copy, V> BTreeValue for (K, V) {
138 fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
139 where
140 BK: Ord + ?Sized,
141 Self::Key: Borrow<BK>,
142 {
143 linear_search_by(slice, |value| Self::Key::borrow(&value.0).cmp(key))
144 }
145
146 fn search_value(slice: &[Self], key: &Self) -> Result<usize, usize> {
147 linear_search_by(slice, |value| value.0.cmp(&key.0))
148 }
149}
150
151def_pool!(OrdMapPool<K, V>, Node<(K, V)>);
152
153pub struct OrdMap<K, V> {
167 size: usize,
168 pool: OrdMapPool<K, V>,
169 root: PoolRef<Node<(K, V)>>,
170}
171
172impl<K, V> OrdMap<K, V> {
173 #[must_use]
175 pub fn new() -> Self {
176 let pool = OrdMapPool::default();
177 let root = PoolRef::default(&pool.0);
178 OrdMap {
179 size: 0,
180 pool,
181 root,
182 }
183 }
184
185 #[cfg(feature = "pool")]
187 #[must_use]
188 pub fn with_pool(pool: &OrdMapPool<K, V>) -> Self {
189 let root = PoolRef::default(&pool.0);
190 OrdMap {
191 size: 0,
192 pool: pool.clone(),
193 root,
194 }
195 }
196
197 #[inline]
211 #[must_use]
212 pub fn unit(key: K, value: V) -> Self {
213 let pool = OrdMapPool::default();
214 let root = PoolRef::new(&pool.0, Node::unit((key, value)));
215 OrdMap {
216 size: 1,
217 pool,
218 root,
219 }
220 }
221
222 #[inline]
239 #[must_use]
240 pub fn is_empty(&self) -> bool {
241 self.len() == 0
242 }
243
244 pub fn ptr_eq(&self, other: &Self) -> bool {
254 std::ptr::eq(self, other) || PoolRef::ptr_eq(&self.root, &other.root)
255 }
256
257 #[inline]
273 #[must_use]
274 pub fn len(&self) -> usize {
275 self.size
276 }
277
278 #[cfg(feature = "pool")]
283 pub fn pool(&self) -> &OrdMapPool<K, V> {
284 &self.pool
285 }
286
287 pub fn clear(&mut self) {
304 if !self.is_empty() {
305 self.root = PoolRef::default(&self.pool.0);
306 self.size = 0;
307 }
308 }
309}
310
311impl<K, V> OrdMap<K, V>
312where
313 K: Ord,
314{
315 #[must_use]
332 pub fn get_max(&self) -> Option<&(K, V)> {
333 self.root.max()
334 }
335
336 #[must_use]
353 pub fn get_min(&self) -> Option<&(K, V)> {
354 self.root.min()
355 }
356
357 #[must_use]
359 pub fn iter(&self) -> Iter<'_, K, V> {
360 Iter {
361 it: RangedIter::new(&self.root, self.size, ..),
362 }
363 }
364
365 #[must_use]
367 pub fn range<R, BK>(&self, range: R) -> Iter<'_, K, V>
368 where
369 R: RangeBounds<BK>,
370 K: Borrow<BK>,
371 BK: Ord + ?Sized,
372 {
373 Iter {
374 it: RangedIter::new(&self.root, self.size, range),
375 }
376 }
377
378 #[must_use]
380 pub fn keys(&self) -> Keys<'_, K, V> {
381 Keys { it: self.iter() }
382 }
383
384 #[must_use]
386 pub fn values(&self) -> Values<'_, K, V> {
387 Values { it: self.iter() }
388 }
389
390 #[must_use]
402 pub fn diff<'a>(&'a self, other: &'a Self) -> DiffIter<'a, K, V> {
403 DiffIter {
404 it: NodeDiffIter::new(&self.root, &other.root),
405 }
406 }
407
408 #[must_use]
424 pub fn get<BK>(&self, key: &BK) -> Option<&V>
425 where
426 BK: Ord + ?Sized,
427 K: Borrow<BK>,
428 {
429 self.root.lookup(key).map(|(_, v)| v)
430 }
431
432 #[must_use]
448 pub fn get_key_value<BK>(&self, key: &BK) -> Option<(&K, &V)>
449 where
450 BK: Ord + ?Sized,
451 K: Borrow<BK>,
452 {
453 self.root.lookup(key).map(|&(ref k, ref v)| (k, v))
454 }
455
456 #[must_use]
473 pub fn get_prev<BK>(&self, key: &BK) -> Option<(&K, &V)>
474 where
475 BK: Ord + ?Sized,
476 K: Borrow<BK>,
477 {
478 self.root.lookup_prev(key).map(|(k, v)| (k, v))
479 }
480
481 #[must_use]
498 pub fn get_next<BK>(&self, key: &BK) -> Option<(&K, &V)>
499 where
500 BK: Ord + ?Sized,
501 K: Borrow<BK>,
502 {
503 self.root.lookup_next(key).map(|(k, v)| (k, v))
504 }
505
506 #[must_use]
524 pub fn contains_key<BK>(&self, k: &BK) -> bool
525 where
526 BK: Ord + ?Sized,
527 K: Borrow<BK>,
528 {
529 self.get(k).is_some()
530 }
531
532 #[must_use]
540 pub fn is_submap_by<B, RM, F>(&self, other: RM, mut cmp: F) -> bool
541 where
542 F: FnMut(&V, &B) -> bool,
543 RM: Borrow<OrdMap<K, B>>,
544 {
545 self.iter()
546 .all(|(k, v)| other.borrow().get(k).map(|ov| cmp(v, ov)).unwrap_or(false))
547 }
548
549 #[must_use]
558 pub fn is_proper_submap_by<B, RM, F>(&self, other: RM, cmp: F) -> bool
559 where
560 F: FnMut(&V, &B) -> bool,
561 RM: Borrow<OrdMap<K, B>>,
562 {
563 self.len() != other.borrow().len() && self.is_submap_by(other, cmp)
564 }
565
566 #[must_use]
582 pub fn is_submap<RM>(&self, other: RM) -> bool
583 where
584 V: PartialEq,
585 RM: Borrow<Self>,
586 {
587 self.is_submap_by(other.borrow(), PartialEq::eq)
588 }
589
590 #[must_use]
611 pub fn is_proper_submap<RM>(&self, other: RM) -> bool
612 where
613 V: PartialEq,
614 RM: Borrow<Self>,
615 {
616 self.is_proper_submap_by(other.borrow(), PartialEq::eq)
617 }
618}
619
620impl<K, V> OrdMap<K, V>
621where
622 K: Ord + Clone,
623 V: Clone,
624{
625 #[must_use]
644 pub fn get_mut<BK>(&mut self, key: &BK) -> Option<&mut V>
645 where
646 BK: Ord + ?Sized,
647 K: Borrow<BK>,
648 {
649 let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
650 root.lookup_mut(&self.pool.0, key).map(|(_, v)| v)
651 }
652
653 #[must_use]
673 pub fn get_prev_mut<BK>(&mut self, key: &BK) -> Option<(&K, &mut V)>
674 where
675 BK: Ord + ?Sized,
676 K: Borrow<BK>,
677 {
678 let pool = &self.pool.0;
679 PoolRef::make_mut(pool, &mut self.root)
680 .lookup_prev_mut(pool, key)
681 .map(|(ref k, ref mut v)| (k, v))
682 }
683
684 #[must_use]
704 pub fn get_next_mut<BK>(&mut self, key: &BK) -> Option<(&K, &mut V)>
705 where
706 BK: Ord + ?Sized,
707 K: Borrow<BK>,
708 {
709 let pool = &self.pool.0;
710 PoolRef::make_mut(pool, &mut self.root)
711 .lookup_next_mut(pool, key)
712 .map(|(ref k, ref mut v)| (k, v))
713 }
714
715 #[inline]
742 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
743 let new_root = {
744 let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
745 match root.insert(&self.pool.0, (key, value)) {
746 Insert::Replaced((_, old_value)) => return Some(old_value),
747 Insert::Added => {
748 self.size += 1;
749 return None;
750 }
751 Insert::Split(left, median, right) => PoolRef::new(
752 &self.pool.0,
753 Node::new_from_split(&self.pool.0, left, median, right),
754 ),
755 }
756 };
757 self.size += 1;
758 self.root = new_root;
759 None
760 }
761
762 #[inline]
779 pub fn remove<BK>(&mut self, k: &BK) -> Option<V>
780 where
781 BK: Ord + ?Sized,
782 K: Borrow<BK>,
783 {
784 self.remove_with_key(k).map(|(_, v)| v)
785 }
786
787 pub fn remove_with_key<BK>(&mut self, k: &BK) -> Option<(K, V)>
792 where
793 BK: Ord + ?Sized,
794 K: Borrow<BK>,
795 {
796 let (new_root, removed_value) = {
797 let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
798 match root.remove(&self.pool.0, k) {
799 Remove::NoChange => return None,
800 Remove::Removed(pair) => {
801 self.size -= 1;
802 return Some(pair);
803 }
804 Remove::Update(pair, root) => (PoolRef::new(&self.pool.0, root), Some(pair)),
805 }
806 };
807 self.size -= 1;
808 self.root = new_root;
809 removed_value
810 }
811
812 #[must_use]
832 pub fn update(&self, key: K, value: V) -> Self {
833 let mut out = self.clone();
834 out.insert(key, value);
835 out
836 }
837
838 #[must_use]
847 pub fn update_with<F>(self, k: K, v: V, f: F) -> Self
848 where
849 F: FnOnce(V, V) -> V,
850 {
851 self.update_with_key(k, v, |_, v1, v2| f(v1, v2))
852 }
853
854 #[must_use]
863 pub fn update_with_key<F>(self, k: K, v: V, f: F) -> Self
864 where
865 F: FnOnce(&K, V, V) -> V,
866 {
867 match self.extract_with_key(&k) {
868 None => self.update(k, v),
869 Some((_, v2, m)) => {
870 let out_v = f(&k, v2, v);
871 m.update(k, out_v)
872 }
873 }
874 }
875
876 #[must_use]
886 pub fn update_lookup_with_key<F>(self, k: K, v: V, f: F) -> (Option<V>, Self)
887 where
888 F: FnOnce(&K, &V, V) -> V,
889 {
890 match self.extract_with_key(&k) {
891 None => (None, self.update(k, v)),
892 Some((_, v2, m)) => {
893 let out_v = f(&k, &v2, v);
894 (Some(v2), m.update(k, out_v))
895 }
896 }
897 }
898
899 #[must_use]
912 pub fn alter<F>(&self, f: F, k: K) -> Self
913 where
914 F: FnOnce(Option<V>) -> Option<V>,
915 {
916 let pop = self.extract_with_key(&k);
917 match (f(pop.as_ref().map(|&(_, ref v, _)| v.clone())), pop) {
918 (None, None) => self.clone(),
919 (Some(v), None) => self.update(k, v),
920 (None, Some((_, _, m))) => m,
921 (Some(v), Some((_, _, m))) => m.update(k, v),
922 }
923 }
924
925 #[must_use]
929 pub fn without<BK>(&self, k: &BK) -> Self
930 where
931 BK: Ord + ?Sized,
932 K: Borrow<BK>,
933 {
934 self.extract(k)
935 .map(|(_, m)| m)
936 .unwrap_or_else(|| self.clone())
937 }
938
939 #[must_use]
944 pub fn extract<BK>(&self, k: &BK) -> Option<(V, Self)>
945 where
946 BK: Ord + ?Sized,
947 K: Borrow<BK>,
948 {
949 self.extract_with_key(k).map(|(_, v, m)| (v, m))
950 }
951
952 #[must_use]
957 pub fn extract_with_key<BK>(&self, k: &BK) -> Option<(K, V, Self)>
958 where
959 BK: Ord + ?Sized,
960 K: Borrow<BK>,
961 {
962 let mut out = self.clone();
963 let result = out.remove_with_key(k);
964 result.map(|(k, v)| (k, v, out))
965 }
966
967 #[inline]
983 #[must_use]
984 pub fn union(self, other: Self) -> Self {
985 let (mut to_mutate, to_consume) = if self.len() >= other.len() {
986 (self, other)
987 } else {
988 (other, self)
989 };
990 for (k, v) in to_consume {
991 to_mutate.entry(k).or_insert(v);
992 }
993 to_mutate
994 }
995
996 #[inline]
1006 #[must_use]
1007 pub fn union_with<F>(self, other: Self, mut f: F) -> Self
1008 where
1009 F: FnMut(V, V) -> V,
1010 {
1011 self.union_with_key(other, |_, v1, v2| f(v1, v2))
1012 }
1013
1014 #[must_use]
1039 pub fn union_with_key<F>(self, other: Self, mut f: F) -> Self
1040 where
1041 F: FnMut(&K, V, V) -> V,
1042 {
1043 if self.len() >= other.len() {
1044 self.union_with_key_inner(other, f)
1045 } else {
1046 other.union_with_key_inner(self, |key, other_value, self_value| {
1047 f(key, self_value, other_value)
1048 })
1049 }
1050 }
1051
1052 fn union_with_key_inner<F>(mut self, other: Self, mut f: F) -> Self
1053 where
1054 F: FnMut(&K, V, V) -> V,
1055 {
1056 for (key, right_value) in other {
1057 match self.remove(&key) {
1058 None => {
1059 self.insert(key, right_value);
1060 }
1061 Some(left_value) => {
1062 let final_value = f(&key, left_value, right_value);
1063 self.insert(key, final_value);
1064 }
1065 }
1066 }
1067 self
1068 }
1069
1070 #[must_use]
1086 pub fn unions<I>(i: I) -> Self
1087 where
1088 I: IntoIterator<Item = Self>,
1089 {
1090 i.into_iter().fold(Self::default(), Self::union)
1091 }
1092
1093 #[must_use]
1104 pub fn unions_with<I, F>(i: I, f: F) -> Self
1105 where
1106 I: IntoIterator<Item = Self>,
1107 F: Fn(V, V) -> V,
1108 {
1109 i.into_iter()
1110 .fold(Self::default(), |a, b| a.union_with(b, &f))
1111 }
1112
1113 #[must_use]
1125 pub fn unions_with_key<I, F>(i: I, f: F) -> Self
1126 where
1127 I: IntoIterator<Item = Self>,
1128 F: Fn(&K, V, V) -> V,
1129 {
1130 i.into_iter()
1131 .fold(Self::default(), |a, b| a.union_with_key(b, &f))
1132 }
1133
1134 #[inline]
1155 #[must_use]
1156 pub fn difference(self, other: Self) -> Self {
1157 self.symmetric_difference(other)
1158 }
1159
1160 #[inline]
1176 #[must_use]
1177 pub fn symmetric_difference(self, other: Self) -> Self {
1178 self.symmetric_difference_with_key(other, |_, _, _| None)
1179 }
1180
1181 #[inline]
1191 #[must_use]
1192 pub fn difference_with<F>(self, other: Self, f: F) -> Self
1193 where
1194 F: FnMut(V, V) -> Option<V>,
1195 {
1196 self.symmetric_difference_with(other, f)
1197 }
1198
1199 #[inline]
1204 #[must_use]
1205 pub fn symmetric_difference_with<F>(self, other: Self, mut f: F) -> Self
1206 where
1207 F: FnMut(V, V) -> Option<V>,
1208 {
1209 self.symmetric_difference_with_key(other, |_, a, b| f(a, b))
1210 }
1211
1212 #[must_use]
1237 pub fn difference_with_key<F>(self, other: Self, f: F) -> Self
1238 where
1239 F: FnMut(&K, V, V) -> Option<V>,
1240 {
1241 self.symmetric_difference_with_key(other, f)
1242 }
1243
1244 #[must_use]
1264 pub fn symmetric_difference_with_key<F>(mut self, other: Self, mut f: F) -> Self
1265 where
1266 F: FnMut(&K, V, V) -> Option<V>,
1267 {
1268 let mut out = Self::default();
1269 for (key, right_value) in other {
1270 match self.remove(&key) {
1271 None => {
1272 out.insert(key, right_value);
1273 }
1274 Some(left_value) => {
1275 if let Some(final_value) = f(&key, left_value, right_value) {
1276 out.insert(key, final_value);
1277 }
1278 }
1279 }
1280 }
1281 out.union(self)
1282 }
1283
1284 #[inline]
1300 #[must_use]
1301 pub fn relative_complement(mut self, other: Self) -> Self {
1302 for (key, _) in other {
1303 let _ = self.remove(&key);
1304 }
1305 self
1306 }
1307
1308 #[inline]
1324 #[must_use]
1325 pub fn intersection(self, other: Self) -> Self {
1326 self.intersection_with_key(other, |_, v, _| v)
1327 }
1328
1329 #[inline]
1335 #[must_use]
1336 pub fn intersection_with<B, C, F>(self, other: OrdMap<K, B>, mut f: F) -> OrdMap<K, C>
1337 where
1338 B: Clone,
1339 C: Clone,
1340 F: FnMut(V, B) -> C,
1341 {
1342 self.intersection_with_key(other, |_, v1, v2| f(v1, v2))
1343 }
1344
1345 #[must_use]
1365 pub fn intersection_with_key<B, C, F>(mut self, other: OrdMap<K, B>, mut f: F) -> OrdMap<K, C>
1366 where
1367 B: Clone,
1368 C: Clone,
1369 F: FnMut(&K, V, B) -> C,
1370 {
1371 let mut out = OrdMap::<K, C>::default();
1372 for (key, right_value) in other {
1373 match self.remove(&key) {
1374 None => (),
1375 Some(left_value) => {
1376 let result = f(&key, left_value, right_value);
1377 out.insert(key, result);
1378 }
1379 }
1380 }
1381 out
1382 }
1383
1384 #[must_use]
1390 pub fn split<BK>(&self, split: &BK) -> (Self, Self)
1391 where
1392 BK: Ord + ?Sized,
1393 K: Borrow<BK>,
1394 {
1395 let (l, _, r) = self.split_lookup(split);
1396 (l, r)
1397 }
1398
1399 #[must_use]
1405 pub fn split_lookup<BK>(&self, split: &BK) -> (Self, Option<V>, Self)
1406 where
1407 BK: Ord + ?Sized,
1408 K: Borrow<BK>,
1409 {
1410 self.iter()
1412 .fold((ordmap![], None, ordmap![]), |(l, m, r), (k, v)| {
1413 match k.borrow().cmp(split) {
1414 Ordering::Less => (l.update(k.clone(), v.clone()), m, r),
1415 Ordering::Equal => (l, Some(v.clone()), r),
1416 Ordering::Greater => (l, m, r.update(k.clone(), v.clone())),
1417 }
1418 })
1419 }
1420
1421 #[must_use]
1424 pub fn take(&self, n: usize) -> Self {
1425 self.iter()
1426 .take(n)
1427 .map(|(k, v)| (k.clone(), v.clone()))
1428 .collect()
1429 }
1430
1431 #[must_use]
1434 pub fn skip(&self, n: usize) -> Self {
1435 self.iter()
1436 .skip(n)
1437 .map(|(k, v)| (k.clone(), v.clone()))
1438 .collect()
1439 }
1440
1441 #[must_use]
1444 pub fn without_min(&self) -> (Option<V>, Self) {
1445 let (pop, next) = self.without_min_with_key();
1446 (pop.map(|(_, v)| v), next)
1447 }
1448
1449 #[must_use]
1452 pub fn without_min_with_key(&self) -> (Option<(K, V)>, Self) {
1453 match self.get_min() {
1454 None => (None, self.clone()),
1455 Some((k, _)) => {
1456 let (key, value, next) = self.extract_with_key(k).unwrap();
1457 (Some((key, value)), next)
1458 }
1459 }
1460 }
1461
1462 #[must_use]
1465 pub fn without_max(&self) -> (Option<V>, Self) {
1466 let (pop, next) = self.without_max_with_key();
1467 (pop.map(|(_, v)| v), next)
1468 }
1469
1470 #[must_use]
1473 pub fn without_max_with_key(&self) -> (Option<(K, V)>, Self) {
1474 match self.get_max() {
1475 None => (None, self.clone()),
1476 Some((k, _)) => {
1477 let (key, value, next) = self.extract_with_key(k).unwrap();
1478 (Some((key, value)), next)
1479 }
1480 }
1481 }
1482
1483 #[must_use]
1489 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
1490 if self.contains_key(&key) {
1491 Entry::Occupied(OccupiedEntry { map: self, key })
1492 } else {
1493 Entry::Vacant(VacantEntry { map: self, key })
1494 }
1495 }
1496}
1497
1498pub enum Entry<'a, K, V>
1502where
1503 K: Ord + Clone,
1504 V: Clone,
1505{
1506 Occupied(OccupiedEntry<'a, K, V>),
1508 Vacant(VacantEntry<'a, K, V>),
1510}
1511
1512impl<'a, K, V> Entry<'a, K, V>
1513where
1514 K: Ord + Clone,
1515 V: Clone,
1516{
1517 pub fn or_insert(self, default: V) -> &'a mut V {
1520 self.or_insert_with(|| default)
1521 }
1522
1523 pub fn or_insert_with<F>(self, default: F) -> &'a mut V
1527 where
1528 F: FnOnce() -> V,
1529 {
1530 match self {
1531 Entry::Occupied(entry) => entry.into_mut(),
1532 Entry::Vacant(entry) => entry.insert(default()),
1533 }
1534 }
1535
1536 pub fn or_default(self) -> &'a mut V
1539 where
1540 V: Default,
1541 {
1542 self.or_insert_with(Default::default)
1543 }
1544
1545 #[must_use]
1547 pub fn key(&self) -> &K {
1548 match self {
1549 Entry::Occupied(entry) => entry.key(),
1550 Entry::Vacant(entry) => entry.key(),
1551 }
1552 }
1553
1554 pub fn and_modify<F>(mut self, f: F) -> Self
1557 where
1558 F: FnOnce(&mut V),
1559 {
1560 match &mut self {
1561 Entry::Occupied(ref mut entry) => f(entry.get_mut()),
1562 Entry::Vacant(_) => (),
1563 }
1564 self
1565 }
1566}
1567
1568pub struct OccupiedEntry<'a, K, V>
1570where
1571 K: Ord + Clone,
1572 V: Clone,
1573{
1574 map: &'a mut OrdMap<K, V>,
1575 key: K,
1576}
1577
1578impl<'a, K, V> OccupiedEntry<'a, K, V>
1579where
1580 K: 'a + Ord + Clone,
1581 V: 'a + Clone,
1582{
1583 #[must_use]
1585 pub fn key(&self) -> &K {
1586 &self.key
1587 }
1588
1589 pub fn remove_entry(self) -> (K, V) {
1591 self.map
1592 .remove_with_key(&self.key)
1593 .expect("ordmap::OccupiedEntry::remove_entry: key has vanished!")
1594 }
1595
1596 #[must_use]
1598 pub fn get(&self) -> &V {
1599 self.map.get(&self.key).unwrap()
1600 }
1601
1602 #[must_use]
1604 pub fn get_mut(&mut self) -> &mut V {
1605 self.map.get_mut(&self.key).unwrap()
1606 }
1607
1608 #[must_use]
1610 pub fn into_mut(self) -> &'a mut V {
1611 self.map.get_mut(&self.key).unwrap()
1612 }
1613
1614 pub fn insert(&mut self, value: V) -> V {
1616 mem::replace(self.get_mut(), value)
1617 }
1618
1619 pub fn remove(self) -> V {
1621 self.remove_entry().1
1622 }
1623}
1624
1625pub struct VacantEntry<'a, K, V>
1627where
1628 K: Ord + Clone,
1629 V: Clone,
1630{
1631 map: &'a mut OrdMap<K, V>,
1632 key: K,
1633}
1634
1635impl<'a, K, V> VacantEntry<'a, K, V>
1636where
1637 K: 'a + Ord + Clone,
1638 V: 'a + Clone,
1639{
1640 #[must_use]
1642 pub fn key(&self) -> &K {
1643 &self.key
1644 }
1645
1646 #[must_use]
1648 pub fn into_key(self) -> K {
1649 self.key
1650 }
1651
1652 pub fn insert(self, value: V) -> &'a mut V {
1654 self.map.insert(self.key.clone(), value);
1655 self.map.get_mut(&self.key).unwrap()
1657 }
1658}
1659
1660impl<K, V> Clone for OrdMap<K, V> {
1663 #[inline]
1667 fn clone(&self) -> Self {
1668 OrdMap {
1669 size: self.size,
1670 pool: self.pool.clone(),
1671 root: self.root.clone(),
1672 }
1673 }
1674}
1675
1676#[cfg(not(has_specialisation))]
1677impl<K, V> PartialEq for OrdMap<K, V>
1678where
1679 K: Ord + PartialEq,
1680 V: PartialEq,
1681{
1682 fn eq(&self, other: &Self) -> bool {
1683 self.len() == other.len() && self.diff(other).next().is_none()
1684 }
1685}
1686
1687#[cfg(has_specialisation)]
1688impl<K, V> PartialEq for OrdMap<K, V>
1689where
1690 K: Ord + PartialEq,
1691 V: PartialEq,
1692{
1693 default fn eq(&self, other: &Self) -> bool {
1694 self.len() == other.len() && self.diff(other).next().is_none()
1695 }
1696}
1697
1698#[cfg(has_specialisation)]
1699impl<K, V> PartialEq for OrdMap<K, V>
1700where
1701 K: Ord + Eq,
1702 V: Eq,
1703{
1704 fn eq(&self, other: &Self) -> bool {
1705 PoolRef::ptr_eq(&self.root, &other.root)
1706 || (self.len() == other.len() && self.diff(other).next().is_none())
1707 }
1708}
1709
1710impl<K: Ord + Eq, V: Eq> Eq for OrdMap<K, V> {}
1711
1712impl<K, V> PartialOrd for OrdMap<K, V>
1713where
1714 K: Ord,
1715 V: PartialOrd,
1716{
1717 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1718 self.iter().partial_cmp(other.iter())
1719 }
1720}
1721
1722impl<K, V> Ord for OrdMap<K, V>
1723where
1724 K: Ord,
1725 V: Ord,
1726{
1727 fn cmp(&self, other: &Self) -> Ordering {
1728 self.iter().cmp(other.iter())
1729 }
1730}
1731
1732impl<K, V> Hash for OrdMap<K, V>
1733where
1734 K: Ord + Hash,
1735 V: Hash,
1736{
1737 fn hash<H>(&self, state: &mut H)
1738 where
1739 H: Hasher,
1740 {
1741 for i in self.iter() {
1742 i.hash(state);
1743 }
1744 }
1745}
1746
1747impl<K, V> Default for OrdMap<K, V> {
1748 fn default() -> Self {
1749 Self::new()
1750 }
1751}
1752
1753impl<'a, K, V> Add for &'a OrdMap<K, V>
1754where
1755 K: Ord + Clone,
1756 V: Clone,
1757{
1758 type Output = OrdMap<K, V>;
1759
1760 fn add(self, other: Self) -> Self::Output {
1761 self.clone().union(other.clone())
1762 }
1763}
1764
1765impl<K, V> Add for OrdMap<K, V>
1766where
1767 K: Ord + Clone,
1768 V: Clone,
1769{
1770 type Output = OrdMap<K, V>;
1771
1772 fn add(self, other: Self) -> Self::Output {
1773 self.union(other)
1774 }
1775}
1776
1777impl<K, V> Sum for OrdMap<K, V>
1778where
1779 K: Ord + Clone,
1780 V: Clone,
1781{
1782 fn sum<I>(it: I) -> Self
1783 where
1784 I: Iterator<Item = Self>,
1785 {
1786 it.fold(Self::default(), |a, b| a + b)
1787 }
1788}
1789
1790impl<K, V, RK, RV> Extend<(RK, RV)> for OrdMap<K, V>
1791where
1792 K: Ord + Clone + From<RK>,
1793 V: Clone + From<RV>,
1794{
1795 fn extend<I>(&mut self, iter: I)
1796 where
1797 I: IntoIterator<Item = (RK, RV)>,
1798 {
1799 for (key, value) in iter {
1800 self.insert(From::from(key), From::from(value));
1801 }
1802 }
1803}
1804
1805impl<'a, BK, K, V> Index<&'a BK> for OrdMap<K, V>
1806where
1807 BK: Ord + ?Sized,
1808 K: Ord + Borrow<BK>,
1809{
1810 type Output = V;
1811
1812 fn index(&self, key: &BK) -> &Self::Output {
1813 match self.root.lookup(key) {
1814 None => panic!("OrdMap::index: invalid key"),
1815 Some(&(_, ref value)) => value,
1816 }
1817 }
1818}
1819
1820impl<'a, BK, K, V> IndexMut<&'a BK> for OrdMap<K, V>
1821where
1822 BK: Ord + ?Sized,
1823 K: Ord + Clone + Borrow<BK>,
1824 V: Clone,
1825{
1826 fn index_mut(&mut self, key: &BK) -> &mut Self::Output {
1827 let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
1828 match root.lookup_mut(&self.pool.0, key) {
1829 None => panic!("OrdMap::index: invalid key"),
1830 Some(&mut (_, ref mut value)) => value,
1831 }
1832 }
1833}
1834
1835impl<K, V> Debug for OrdMap<K, V>
1836where
1837 K: Ord + Debug,
1838 V: Debug,
1839{
1840 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
1841 let mut d = f.debug_map();
1842 for (k, v) in self.iter() {
1843 d.entry(k, v);
1844 }
1845 d.finish()
1846 }
1847}
1848
1849pub struct Iter<'a, K, V> {
1853 it: RangedIter<'a, (K, V)>,
1854}
1855
1856impl<'a, K, V> Iterator for Iter<'a, K, V>
1857where
1858 (K, V): 'a + BTreeValue,
1859{
1860 type Item = (&'a K, &'a V);
1861
1862 fn next(&mut self) -> Option<Self::Item> {
1863 self.it.next().map(|(k, v)| (k, v))
1864 }
1865
1866 fn size_hint(&self) -> (usize, Option<usize>) {
1867 (self.it.remaining, Some(self.it.remaining))
1868 }
1869}
1870
1871impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V>
1872where
1873 (K, V): 'a + BTreeValue,
1874{
1875 fn next_back(&mut self) -> Option<Self::Item> {
1876 self.it.next_back().map(|(k, v)| (k, v))
1877 }
1878}
1879
1880impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> where (K, V): 'a + BTreeValue {}
1881
1882pub struct DiffIter<'a, K, V> {
1884 it: NodeDiffIter<'a, (K, V)>,
1885}
1886
1887#[derive(PartialEq, Eq, Debug)]
1889pub enum DiffItem<'a, K, V> {
1890 Add(&'a K, &'a V),
1892 Update {
1894 old: (&'a K, &'a V),
1896 new: (&'a K, &'a V),
1898 },
1899 Remove(&'a K, &'a V),
1901}
1902
1903impl<'a, K, V> Iterator for DiffIter<'a, K, V>
1904where
1905 (K, V): 'a + BTreeValue + PartialEq,
1906{
1907 type Item = DiffItem<'a, K, V>;
1908
1909 fn next(&mut self) -> Option<Self::Item> {
1910 self.it.next().map(|item| match item {
1911 NodeDiffItem::Add((k, v)) => DiffItem::Add(k, v),
1912 NodeDiffItem::Update {
1913 old: (oldk, oldv),
1914 new: (newk, newv),
1915 } => DiffItem::Update {
1916 old: (oldk, oldv),
1917 new: (newk, newv),
1918 },
1919 NodeDiffItem::Remove((k, v)) => DiffItem::Remove(k, v),
1920 })
1921 }
1922}
1923
1924pub struct Keys<'a, K, V> {
1926 it: Iter<'a, K, V>,
1927}
1928
1929impl<'a, K, V> Iterator for Keys<'a, K, V>
1930where
1931 K: 'a + Ord,
1932 V: 'a,
1933{
1934 type Item = &'a K;
1935
1936 fn next(&mut self) -> Option<Self::Item> {
1937 self.it.next().map(|(k, _)| k)
1938 }
1939
1940 fn size_hint(&self) -> (usize, Option<usize>) {
1941 self.it.size_hint()
1942 }
1943}
1944
1945impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V>
1946where
1947 K: 'a + Ord,
1948 V: 'a,
1949{
1950 fn next_back(&mut self) -> Option<Self::Item> {
1951 self.it.next_back().map(|(k, _)| k)
1952 }
1953}
1954
1955impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V>
1956where
1957 K: 'a + Ord,
1958 V: 'a,
1959{
1960}
1961
1962pub struct Values<'a, K, V> {
1964 it: Iter<'a, K, V>,
1965}
1966
1967impl<'a, K, V> Iterator for Values<'a, K, V>
1968where
1969 K: 'a + Ord,
1970 V: 'a,
1971{
1972 type Item = &'a V;
1973
1974 fn next(&mut self) -> Option<Self::Item> {
1975 self.it.next().map(|(_, v)| v)
1976 }
1977
1978 fn size_hint(&self) -> (usize, Option<usize>) {
1979 self.it.size_hint()
1980 }
1981}
1982
1983impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V>
1984where
1985 K: 'a + Ord,
1986 V: 'a,
1987{
1988 fn next_back(&mut self) -> Option<Self::Item> {
1989 self.it.next_back().map(|(_, v)| v)
1990 }
1991}
1992
1993impl<'a, K, V> ExactSizeIterator for Values<'a, K, V>
1994where
1995 K: 'a + Ord,
1996 V: 'a,
1997{
1998}
1999
2000impl<K, V, RK, RV> FromIterator<(RK, RV)> for OrdMap<K, V>
2001where
2002 K: Ord + Clone + From<RK>,
2003 V: Clone + From<RV>,
2004{
2005 fn from_iter<T>(i: T) -> Self
2006 where
2007 T: IntoIterator<Item = (RK, RV)>,
2008 {
2009 let mut m = OrdMap::default();
2010 for (k, v) in i {
2011 m.insert(From::from(k), From::from(v));
2012 }
2013 m
2014 }
2015}
2016
2017impl<'a, K, V> IntoIterator for &'a OrdMap<K, V>
2018where
2019 K: Ord,
2020{
2021 type Item = (&'a K, &'a V);
2022 type IntoIter = Iter<'a, K, V>;
2023
2024 fn into_iter(self) -> Self::IntoIter {
2025 self.iter()
2026 }
2027}
2028
2029impl<K, V> IntoIterator for OrdMap<K, V>
2030where
2031 K: Ord + Clone,
2032 V: Clone,
2033{
2034 type Item = (K, V);
2035 type IntoIter = ConsumingIter<(K, V)>;
2036
2037 fn into_iter(self) -> Self::IntoIter {
2038 ConsumingIter::new(&self.root, self.size)
2039 }
2040}
2041
2042impl<K, V> AsRef<OrdMap<K, V>> for OrdMap<K, V> {
2045 fn as_ref(&self) -> &Self {
2046 self
2047 }
2048}
2049
2050impl<'m, 'k, 'v, K, V, OK, OV> From<&'m OrdMap<&'k K, &'v V>> for OrdMap<OK, OV>
2051where
2052 K: Ord + ToOwned<Owned = OK> + ?Sized,
2053 V: ToOwned<Owned = OV> + ?Sized,
2054 OK: Ord + Clone + Borrow<K>,
2055 OV: Clone + Borrow<V>,
2056{
2057 fn from(m: &OrdMap<&K, &V>) -> Self {
2058 m.iter()
2059 .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
2060 .collect()
2061 }
2062}
2063
2064impl<'a, K, V, RK, RV, OK, OV> From<&'a [(RK, RV)]> for OrdMap<K, V>
2065where
2066 K: Ord + Clone + From<OK>,
2067 V: Clone + From<OV>,
2068 OK: Borrow<RK>,
2069 OV: Borrow<RV>,
2070 RK: ToOwned<Owned = OK>,
2071 RV: ToOwned<Owned = OV>,
2072{
2073 fn from(m: &'a [(RK, RV)]) -> OrdMap<K, V> {
2074 m.iter()
2075 .map(|&(ref k, ref v)| (k.to_owned(), v.to_owned()))
2076 .collect()
2077 }
2078}
2079
2080impl<K, V, RK, RV> From<Vec<(RK, RV)>> for OrdMap<K, V>
2081where
2082 K: Ord + Clone + From<RK>,
2083 V: Clone + From<RV>,
2084{
2085 fn from(m: Vec<(RK, RV)>) -> OrdMap<K, V> {
2086 m.into_iter().collect()
2087 }
2088}
2089
2090impl<'a, K: Ord, V, RK, RV, OK, OV> From<&'a Vec<(RK, RV)>> for OrdMap<K, V>
2091where
2092 K: Ord + Clone + From<OK>,
2093 V: Clone + From<OV>,
2094 OK: Borrow<RK>,
2095 OV: Borrow<RV>,
2096 RK: ToOwned<Owned = OK>,
2097 RV: ToOwned<Owned = OV>,
2098{
2099 fn from(m: &'a Vec<(RK, RV)>) -> OrdMap<K, V> {
2100 m.iter()
2101 .map(|&(ref k, ref v)| (k.to_owned(), v.to_owned()))
2102 .collect()
2103 }
2104}
2105
2106impl<K: Ord, V, RK: Eq + Hash, RV> From<collections::HashMap<RK, RV>> for OrdMap<K, V>
2107where
2108 K: Ord + Clone + From<RK>,
2109 V: Clone + From<RV>,
2110{
2111 fn from(m: collections::HashMap<RK, RV>) -> OrdMap<K, V> {
2112 m.into_iter().collect()
2113 }
2114}
2115
2116impl<'a, K, V, OK, OV, RK, RV> From<&'a collections::HashMap<RK, RV>> for OrdMap<K, V>
2117where
2118 K: Ord + Clone + From<OK>,
2119 V: Clone + From<OV>,
2120 OK: Borrow<RK>,
2121 OV: Borrow<RV>,
2122 RK: Hash + Eq + ToOwned<Owned = OK>,
2123 RV: ToOwned<Owned = OV>,
2124{
2125 fn from(m: &'a collections::HashMap<RK, RV>) -> OrdMap<K, V> {
2126 m.iter()
2127 .map(|(k, v)| (k.to_owned(), v.to_owned()))
2128 .collect()
2129 }
2130}
2131
2132impl<K: Ord, V, RK, RV> From<collections::BTreeMap<RK, RV>> for OrdMap<K, V>
2133where
2134 K: Ord + Clone + From<RK>,
2135 V: Clone + From<RV>,
2136{
2137 fn from(m: collections::BTreeMap<RK, RV>) -> OrdMap<K, V> {
2138 m.into_iter().collect()
2139 }
2140}
2141
2142impl<'a, K: Ord, V, RK, RV, OK, OV> From<&'a collections::BTreeMap<RK, RV>> for OrdMap<K, V>
2143where
2144 K: Ord + Clone + From<OK>,
2145 V: Clone + From<OV>,
2146 OK: Borrow<RK>,
2147 OV: Borrow<RV>,
2148 RK: Ord + ToOwned<Owned = OK>,
2149 RV: ToOwned<Owned = OV>,
2150{
2151 fn from(m: &'a collections::BTreeMap<RK, RV>) -> OrdMap<K, V> {
2152 m.iter()
2153 .map(|(k, v)| (k.to_owned(), v.to_owned()))
2154 .collect()
2155 }
2156}
2157
2158impl<K: Ord + Hash + Eq + Clone, V: Clone, S: BuildHasher> From<HashMap<K, V, S>> for OrdMap<K, V> {
2159 fn from(m: HashMap<K, V, S>) -> Self {
2160 m.into_iter().collect()
2161 }
2162}
2163
2164impl<'a, K: Ord + Hash + Eq + Clone, V: Clone, S: BuildHasher> From<&'a HashMap<K, V, S>>
2165 for OrdMap<K, V>
2166{
2167 fn from(m: &'a HashMap<K, V, S>) -> Self {
2168 m.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
2169 }
2170}
2171
2172#[cfg(any(test, feature = "proptest"))]
2174#[doc(hidden)]
2175pub mod proptest {
2176 #[deprecated(
2177 since = "14.3.0",
2178 note = "proptest strategies have moved to im::proptest"
2179 )]
2180 pub use crate::proptest::ord_map;
2181}
2182
2183#[cfg(test)]
2186mod test {
2187 use super::*;
2188 use crate::proptest::*;
2189 use crate::test::is_sorted;
2190 use ::proptest::num::{i16, usize};
2191 use ::proptest::{bool, collection, proptest};
2192
2193 #[test]
2194 fn iterates_in_order() {
2195 let map = ordmap! {
2196 2 => 22,
2197 1 => 11,
2198 3 => 33,
2199 8 => 88,
2200 9 => 99,
2201 4 => 44,
2202 5 => 55,
2203 7 => 77,
2204 6 => 66
2205 };
2206 let mut it = map.iter();
2207 assert_eq!(it.next(), Some((&1, &11)));
2208 assert_eq!(it.next(), Some((&2, &22)));
2209 assert_eq!(it.next(), Some((&3, &33)));
2210 assert_eq!(it.next(), Some((&4, &44)));
2211 assert_eq!(it.next(), Some((&5, &55)));
2212 assert_eq!(it.next(), Some((&6, &66)));
2213 assert_eq!(it.next(), Some((&7, &77)));
2214 assert_eq!(it.next(), Some((&8, &88)));
2215 assert_eq!(it.next(), Some((&9, &99)));
2216 assert_eq!(it.next(), None);
2217 }
2218
2219 #[test]
2220 fn into_iter() {
2221 let map = ordmap! {
2222 2 => 22,
2223 1 => 11,
2224 3 => 33,
2225 8 => 88,
2226 9 => 99,
2227 4 => 44,
2228 5 => 55,
2229 7 => 77,
2230 6 => 66
2231 };
2232 let mut vec = vec![];
2233 for (k, v) in map {
2234 assert_eq!(k * 11, v);
2235 vec.push(k)
2236 }
2237 assert_eq!(vec, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]);
2238 }
2239
2240 #[test]
2241 fn deletes_correctly() {
2242 let map = ordmap! {
2243 2 => 22,
2244 1 => 11,
2245 3 => 33,
2246 8 => 88,
2247 9 => 99,
2248 4 => 44,
2249 5 => 55,
2250 7 => 77,
2251 6 => 66
2252 };
2253 assert_eq!(map.extract(&11), None);
2254 let (popped, less) = map.extract(&5).unwrap();
2255 assert_eq!(popped, 55);
2256 let mut it = less.iter();
2257 assert_eq!(it.next(), Some((&1, &11)));
2258 assert_eq!(it.next(), Some((&2, &22)));
2259 assert_eq!(it.next(), Some((&3, &33)));
2260 assert_eq!(it.next(), Some((&4, &44)));
2261 assert_eq!(it.next(), Some((&6, &66)));
2262 assert_eq!(it.next(), Some((&7, &77)));
2263 assert_eq!(it.next(), Some((&8, &88)));
2264 assert_eq!(it.next(), Some((&9, &99)));
2265 assert_eq!(it.next(), None);
2266 }
2267
2268 #[test]
2269 fn debug_output() {
2270 assert_eq!(
2271 format!("{:?}", ordmap! { 3 => 4, 5 => 6, 1 => 2 }),
2272 "{1: 2, 3: 4, 5: 6}"
2273 );
2274 }
2275
2276 #[test]
2277 fn equality2() {
2278 let v1 = "1".to_string();
2279 let v2 = "1".to_string();
2280 assert_eq!(v1, v2);
2281 let p1 = Vec::<String>::new();
2282 let p2 = Vec::<String>::new();
2283 assert_eq!(p1, p2);
2284 let c1 = OrdMap::unit(v1, p1);
2285 let c2 = OrdMap::unit(v2, p2);
2286 assert_eq!(c1, c2);
2287 }
2288
2289 #[test]
2290 fn insert_remove_single_mut() {
2291 let mut m = OrdMap::new();
2292 m.insert(0, 0);
2293 assert_eq!(OrdMap::unit(0, 0), m);
2294 m.remove(&0);
2295 assert_eq!(OrdMap::new(), m);
2296 }
2297
2298 #[test]
2299 fn double_ended_iterator_1() {
2300 let m = ordmap! {1 => 1, 2 => 2, 3 => 3, 4 => 4};
2301 let mut it = m.iter();
2302 assert_eq!(Some((&1, &1)), it.next());
2303 assert_eq!(Some((&4, &4)), it.next_back());
2304 assert_eq!(Some((&2, &2)), it.next());
2305 assert_eq!(Some((&3, &3)), it.next_back());
2306 assert_eq!(None, it.next());
2307 }
2308
2309 #[test]
2310 fn double_ended_iterator_2() {
2311 let m = ordmap! {1 => 1, 2 => 2, 3 => 3, 4 => 4};
2312 let mut it = m.iter();
2313 assert_eq!(Some((&1, &1)), it.next());
2314 assert_eq!(Some((&4, &4)), it.next_back());
2315 assert_eq!(Some((&2, &2)), it.next());
2316 assert_eq!(Some((&3, &3)), it.next_back());
2317 assert_eq!(None, it.next_back());
2318 }
2319
2320 #[test]
2321 fn safe_mutation() {
2322 let v1 = (0..131_072).map(|i| (i, i)).collect::<OrdMap<_, _>>();
2323 let mut v2 = v1.clone();
2324 v2.insert(131_000, 23);
2325 assert_eq!(Some(&23), v2.get(&131_000));
2326 assert_eq!(Some(&131_000), v1.get(&131_000));
2327 }
2328
2329 #[test]
2330 fn index_operator() {
2331 let mut map = ordmap! {1 => 2, 3 => 4, 5 => 6};
2332 assert_eq!(4, map[&3]);
2333 map[&3] = 8;
2334 assert_eq!(ordmap! {1 => 2, 3 => 8, 5 => 6}, map);
2335 }
2336
2337 #[test]
2338 fn entry_api() {
2339 let mut map = ordmap! {"bar" => 5};
2340 map.entry("foo").and_modify(|v| *v += 5).or_insert(1);
2341 assert_eq!(1, map[&"foo"]);
2342 map.entry("foo").and_modify(|v| *v += 5).or_insert(1);
2343 assert_eq!(6, map[&"foo"]);
2344 map.entry("bar").and_modify(|v| *v += 5).or_insert(1);
2345 assert_eq!(10, map[&"bar"]);
2346 assert_eq!(
2347 10,
2348 match map.entry("bar") {
2349 Entry::Occupied(entry) => entry.remove(),
2350 _ => panic!(),
2351 }
2352 );
2353 assert!(!map.contains_key(&"bar"));
2354 }
2355
2356 #[test]
2357 fn match_string_keys_with_string_slices() {
2358 let mut map: OrdMap<String, i32> =
2359 From::from(ºap! { "foo" => &1, "bar" => &2, "baz" => &3 });
2360 assert_eq!(Some(&1), map.get("foo"));
2361 map = map.without("foo");
2362 assert_eq!(Some(3), map.remove("baz"));
2363 map["bar"] = 8;
2364 assert_eq!(8, map["bar"]);
2365 }
2366
2367 #[test]
2368 fn ranged_iter() {
2369 let map: OrdMap<i32, i32> = ordmap![1=>2, 2=>3, 3=>4, 4=>5, 5=>6, 7=>8];
2370 let range: Vec<(i32, i32)> = map.range(..).map(|(k, v)| (*k, *v)).collect();
2371 assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (7, 8)], range);
2372 let range: Vec<(i32, i32)> = map.range(..).rev().map(|(k, v)| (*k, *v)).collect();
2373 assert_eq!(vec![(7, 8), (5, 6), (4, 5), (3, 4), (2, 3), (1, 2)], range);
2374 let range: Vec<(i32, i32)> = map.range(2..5).map(|(k, v)| (*k, *v)).collect();
2375 assert_eq!(vec![(2, 3), (3, 4), (4, 5)], range);
2376 let range: Vec<(i32, i32)> = map.range(2..5).rev().map(|(k, v)| (*k, *v)).collect();
2377 assert_eq!(vec![(4, 5), (3, 4), (2, 3)], range);
2378 let range: Vec<(i32, i32)> = map.range(3..).map(|(k, v)| (*k, *v)).collect();
2379 assert_eq!(vec![(3, 4), (4, 5), (5, 6), (7, 8)], range);
2380 let range: Vec<(i32, i32)> = map.range(3..).rev().map(|(k, v)| (*k, *v)).collect();
2381 assert_eq!(vec![(7, 8), (5, 6), (4, 5), (3, 4)], range);
2382 let range: Vec<(i32, i32)> = map.range(..4).map(|(k, v)| (*k, *v)).collect();
2383 assert_eq!(vec![(1, 2), (2, 3), (3, 4)], range);
2384 let range: Vec<(i32, i32)> = map.range(..4).rev().map(|(k, v)| (*k, *v)).collect();
2385 assert_eq!(vec![(3, 4), (2, 3), (1, 2)], range);
2386 let range: Vec<(i32, i32)> = map.range(..=3).map(|(k, v)| (*k, *v)).collect();
2387 assert_eq!(vec![(1, 2), (2, 3), (3, 4)], range);
2388 let range: Vec<(i32, i32)> = map.range(..=3).rev().map(|(k, v)| (*k, *v)).collect();
2389 assert_eq!(vec![(3, 4), (2, 3), (1, 2)], range);
2390 let range: Vec<(i32, i32)> = map.range(..6).map(|(k, v)| (*k, *v)).collect();
2391 assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)], range);
2392 let range: Vec<(i32, i32)> = map.range(..=6).map(|(k, v)| (*k, *v)).collect();
2393 assert_eq!(vec![(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)], range);
2394 }
2395
2396 #[test]
2397 fn range_iter_big() {
2398 use crate::nodes::btree::NODE_SIZE;
2399 use std::ops::Bound::Included;
2400 const N: usize = NODE_SIZE * NODE_SIZE * 5; let data = (1usize..N).filter(|i| i % 2 == 0).map(|i| (i, ()));
2403 let bmap = data
2404 .clone()
2405 .collect::<std::collections::BTreeMap<usize, ()>>();
2406 let omap = data.collect::<OrdMap<usize, ()>>();
2407
2408 for i in (0..NODE_SIZE * 5).chain(N - NODE_SIZE * 5..=N + 1) {
2409 assert_eq!(omap.range(i..).count(), bmap.range(i..).count());
2410 assert_eq!(omap.range(..i).count(), bmap.range(..i).count());
2411 assert_eq!(omap.range(i..i + 7).count(), bmap.range(i..i + 7).count());
2412 assert_eq!(omap.range(i..=i + 7).count(), bmap.range(i..=i + 7).count());
2413 assert_eq!(
2414 omap.range((Included(i), Included(i + 7))).count(),
2415 bmap.range((Included(i), Included(i + 7))).count(),
2416 );
2417 }
2418 }
2419
2420 #[test]
2421 fn issue_124() {
2422 let mut map = OrdMap::new();
2423 let contents = include_str!("test-fixtures/issue_124.txt");
2424 for line in contents.lines() {
2425 if line.starts_with("insert ") {
2426 map.insert(line[7..].parse::<u32>().unwrap(), 0);
2427 } else if line.starts_with("remove ") {
2428 map.remove(&line[7..].parse::<u32>().unwrap());
2429 }
2430 }
2431 }
2432
2433 proptest! {
2434 #[test]
2435 fn length(ref input in collection::btree_map(i16::ANY, i16::ANY, 0..1000)) {
2436 let map: OrdMap<i32, i32> = OrdMap::from(input.clone());
2437 assert_eq!(input.len(), map.len());
2438 }
2439
2440 #[test]
2441 fn order(ref input in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2442 let map: OrdMap<i32, i32> = OrdMap::from(input.clone());
2443 assert!(is_sorted(map.keys()));
2444 }
2445
2446 #[test]
2447 fn overwrite_values(ref vec in collection::vec((i16::ANY, i16::ANY), 1..1000), index_rand in usize::ANY, new_val in i16::ANY) {
2448 let index = vec[index_rand % vec.len()].0;
2449 let map1 = OrdMap::from_iter(vec.clone());
2450 let map2 = map1.update(index, new_val);
2451 for (k, v) in map2 {
2452 if k == index {
2453 assert_eq!(v, new_val);
2454 } else {
2455 match map1.get(&k) {
2456 None => panic!("map1 didn't have key {:?}", k),
2457 Some(other_v) => {
2458 assert_eq!(v, *other_v);
2459 }
2460 }
2461 }
2462 }
2463 }
2464
2465 #[test]
2466 fn delete_values(ref vec in collection::vec((usize::ANY, usize::ANY), 1..1000), index_rand in usize::ANY) {
2467 let index = vec[index_rand % vec.len()].0;
2468 let map1: OrdMap<usize, usize> = OrdMap::from_iter(vec.clone());
2469 let map2 = map1.without(&index);
2470 assert_eq!(map1.len(), map2.len() + 1);
2471 for k in map2.keys() {
2472 assert_ne!(*k, index);
2473 }
2474 }
2475
2476 #[test]
2477 fn insert_and_delete_values(
2478 ref input in ord_map(0usize..64, 0usize..64, 1..1000),
2479 ref ops in collection::vec((bool::ANY, usize::ANY, usize::ANY), 1..1000)
2480 ) {
2481 let mut map = input.clone();
2482 let mut tree: collections::BTreeMap<usize, usize> = input.iter().map(|(k, v)| (*k, *v)).collect();
2483 for (ins, key, val) in ops {
2484 if *ins {
2485 tree.insert(*key, *val);
2486 map = map.update(*key, *val)
2487 } else {
2488 tree.remove(key);
2489 map = map.without(key)
2490 }
2491 }
2492 assert!(map.iter().map(|(k, v)| (*k, *v)).eq(tree.iter().map(|(k, v)| (*k, *v))));
2493 }
2494
2495 #[test]
2496 fn proptest_works(ref m in ord_map(0..9999, ".*", 10..100)) {
2497 assert!(m.len() < 100);
2498 assert!(m.len() >= 10);
2499 }
2500
2501 #[test]
2502 fn insert_and_length(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2503 let mut map: OrdMap<i16, i16> = OrdMap::new();
2504 for (k, v) in m.iter() {
2505 map = map.update(*k, *v)
2506 }
2507 assert_eq!(m.len(), map.len());
2508 }
2509
2510 #[test]
2511 fn from_iterator(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2512 let map: OrdMap<i16, i16> =
2513 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2514 assert_eq!(m.len(), map.len());
2515 }
2516
2517 #[test]
2518 fn iterate_over(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2519 let map: OrdMap<i16, i16> =
2520 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2521 assert_eq!(m.len(), map.iter().count());
2522 }
2523
2524 #[test]
2525 fn equality(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2526 let map1: OrdMap<i16, i16> =
2527 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2528 let map2: OrdMap<i16, i16> =
2529 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2530 assert_eq!(map1, map2);
2531 }
2532
2533 #[test]
2534 fn lookup(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2535 let map: OrdMap<i16, i16> =
2536 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2537 for (k, v) in m.iter() {
2538 assert_eq!(Some(*v), map.get(k).cloned());
2539 }
2540 }
2541
2542 #[test]
2543 fn remove(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2544 let mut map: OrdMap<i16, i16> =
2545 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2546 for k in m.keys() {
2547 let l = map.len();
2548 assert_eq!(m.get(k).cloned(), map.get(k).cloned());
2549 map = map.without(k);
2550 assert_eq!(None, map.get(k));
2551 assert_eq!(l - 1, map.len());
2552 }
2553 }
2554
2555 #[test]
2556 fn insert_mut(ref m in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2557 let mut mut_map = OrdMap::new();
2558 let mut map = OrdMap::new();
2559 for (k, v) in m.iter() {
2560 map = map.update(*k, *v);
2561 mut_map.insert(*k, *v);
2562 }
2563 assert_eq!(map, mut_map);
2564 }
2565
2566 #[test]
2567 fn remove_mut(ref orig in ord_map(i16::ANY, i16::ANY, 0..1000)) {
2568 let mut map = orig.clone();
2569 for key in orig.keys() {
2570 let len = map.len();
2571 assert_eq!(orig.get(key), map.get(key));
2572 assert_eq!(orig.get(key).cloned(), map.remove(key));
2573 assert_eq!(None, map.get(key));
2574 assert_eq!(len - 1, map.len());
2575 }
2576 }
2577
2578 #[test]
2579 fn remove_alien(ref orig in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2580 let mut map = OrdMap::<i16, i16>::from(orig.clone());
2581 for key in orig.keys() {
2582 let len = map.len();
2583 assert_eq!(orig.get(key), map.get(key));
2584 assert_eq!(orig.get(key).cloned(), map.remove(key));
2585 assert_eq!(None, map.get(key));
2586 assert_eq!(len - 1, map.len());
2587 }
2588 }
2589
2590 #[test]
2591 fn delete_and_reinsert(
2592 ref input in collection::hash_map(i16::ANY, i16::ANY, 1..1000),
2593 index_rand in usize::ANY
2594 ) {
2595 let index = *input.keys().nth(index_rand % input.len()).unwrap();
2596 let map1 = OrdMap::from_iter(input.clone());
2597 let (val, map2): (i16, _) = map1.extract(&index).unwrap();
2598 let map3 = map2.update(index, val);
2599 for key in map2.keys() {
2600 assert!(*key != index);
2601 }
2602 assert_eq!(map1.len(), map2.len() + 1);
2603 assert_eq!(map1, map3);
2604 }
2605
2606 #[test]
2607 fn exact_size_iterator(ref m in ord_map(i16::ANY, i16::ANY, 1..1000)) {
2608 let mut should_be = m.len();
2609 let mut it = m.iter();
2610 loop {
2611 assert_eq!(should_be, it.len());
2612 match it.next() {
2613 None => break,
2614 Some(_) => should_be -= 1,
2615 }
2616 }
2617 assert_eq!(0, it.len());
2618 }
2619
2620 #[test]
2621 fn diff_all_values(a in collection::vec((usize::ANY, usize::ANY), 1..1000), b in collection::vec((usize::ANY, usize::ANY), 1..1000)) {
2622 let a: OrdMap<usize, usize> = OrdMap::from(a);
2623 let b: OrdMap<usize, usize> = OrdMap::from(b);
2624
2625 let diff: Vec<_> = a.diff(&b).collect();
2626 let union = b.clone().union(a.clone());
2627 let expected: Vec<_> = union.iter().filter_map(|(k, v)| {
2628 if a.contains_key(k) {
2629 if b.contains_key(k) {
2630 let old = a.get(k).unwrap();
2631 if old != v {
2632 Some(DiffItem::Update {
2633 old: (k, old),
2634 new: (k, v),
2635 })
2636 } else {
2637 None
2638 }
2639 } else {
2640 Some(DiffItem::Remove(k, v))
2641 }
2642 } else {
2643 Some(DiffItem::Add(k, v))
2644 }
2645 }).collect();
2646 assert_eq!(expected, diff);
2647 }
2648 }
2649}