1use std::borrow::Borrow;
25use std::collections;
26use std::collections::hash_map::RandomState;
27use std::fmt::{Debug, Error, Formatter};
28use std::hash::{BuildHasher, Hash};
29use std::iter::{FromIterator, FusedIterator, Sum};
30use std::mem;
31use std::ops::{Add, Index, IndexMut};
32
33use archery::{SharedPointer, SharedPointerKind};
34use equivalent::Equivalent;
35
36use crate::nodes::hamt::{
37 hash_key, Drain as NodeDrain, HashBits, HashValue, Iter as NodeIter, IterMut as NodeIterMut,
38 Node,
39};
40use crate::shared_ptr::DefaultSharedPtr;
41
42#[macro_export]
61macro_rules! hashmap {
62 () => { $crate::hashmap::HashMap::new() };
63
64 ( $( $key:expr => $value:expr ),* ) => {{
65 let mut map = $crate::hashmap::HashMap::new();
66 $({
67 map.insert($key, $value);
68 })*;
69 map
70 }};
71
72 ( $( $key:expr => $value:expr ,)* ) => {{
73 let mut map = $crate::hashmap::HashMap::new();
74 $({
75 map.insert($key, $value);
76 })*;
77 map
78 }};
79}
80
81pub type HashMap<K, V> = GenericHashMap<K, V, RandomState, DefaultSharedPtr>;
87
88pub struct GenericHashMap<K, V, S, P: SharedPointerKind> {
107 size: usize,
108 root: Option<SharedPointer<Node<(K, V), P>, P>>,
109 hasher: S,
110}
111
112impl<K, V> HashValue for (K, V)
113where
114 K: Eq,
115{
116 type Key = K;
117
118 fn extract_key(&self) -> &Self::Key {
119 &self.0
120 }
121
122 fn ptr_eq(&self, _other: &Self) -> bool {
123 false
124 }
125}
126
127impl<K, V, P> GenericHashMap<K, V, RandomState, P>
128where
129 K: Hash + Eq + Clone,
130 V: Clone,
131 P: SharedPointerKind,
132{
133 #[inline]
147 #[must_use]
148 pub fn unit(k: K, v: V) -> GenericHashMap<K, V, RandomState, P> {
149 GenericHashMap::new().update(k, v)
150 }
151}
152
153impl<K, V, S, P: SharedPointerKind> GenericHashMap<K, V, S, P> {
154 #[inline]
156 #[must_use]
157 pub fn new() -> Self
158 where
159 S: Default,
160 {
161 Self::default()
162 }
163
164 #[inline]
181 #[must_use]
182 pub fn is_empty(&self) -> bool {
183 self.len() == 0
184 }
185
186 #[inline]
202 #[must_use]
203 pub fn len(&self) -> usize {
204 self.size
205 }
206
207 pub fn ptr_eq(&self, other: &Self) -> bool {
217 match (&self.root, &other.root) {
218 (Some(a), Some(b)) => SharedPointer::ptr_eq(a, b),
219 (None, None) => true,
220 _ => false,
221 }
222 }
223
224 #[inline]
226 #[must_use]
227 pub fn with_hasher(hasher: S) -> Self {
228 GenericHashMap {
229 size: 0,
230 hasher,
231 root: None,
232 }
233 }
234
235 #[must_use]
239 pub fn hasher(&self) -> &S {
240 &self.hasher
241 }
242
243 #[inline]
246 #[must_use]
247 pub fn new_from<K1, V1>(&self) -> GenericHashMap<K1, V1, S, P>
248 where
249 K1: Hash + Eq + Clone,
250 V1: Clone,
251 S: Clone,
252 {
253 GenericHashMap {
254 size: 0,
255 root: None,
256 hasher: self.hasher.clone(),
257 }
258 }
259
260 #[inline]
268 #[must_use]
269 pub fn iter(&self) -> Iter<'_, K, V, P> {
270 Iter {
271 it: NodeIter::new(self.root.as_deref(), self.size),
272 }
273 }
274
275 #[inline]
283 #[must_use]
284 pub fn keys(&self) -> Keys<'_, K, V, P> {
285 Keys {
286 it: NodeIter::new(self.root.as_deref(), self.size),
287 }
288 }
289
290 #[inline]
298 #[must_use]
299 pub fn values(&self) -> Values<'_, K, V, P> {
300 Values {
301 it: NodeIter::new(self.root.as_deref(), self.size),
302 }
303 }
304
305 pub fn clear(&mut self) {
322 self.root = None;
323 self.size = 0;
324 }
325
326 #[cfg(test)]
329 pub fn print_structure_summary(&self) {
330 use crate::nodes::hamt::Entry as NodeEntry;
331 use std::collections::VecDeque;
332
333 println!("HashMap Structure Summary:");
334
335 #[derive(Default, Debug)]
336 struct LevelStats {
337 node_count: usize,
338 value_count: usize,
339 collision_count: usize,
340 collision_entry_sum: usize,
341 child_node_count: usize,
342 small_simd_node_count: usize,
343 large_simd_node_count: usize,
344 small_simd_entry_sum: usize,
345 large_simd_entry_sum: usize,
346 total_entries: usize,
347 }
348
349 if self.root.is_none() {
350 println!(" Empty HashMap (no root node)");
351 println!(" Total entries: 0");
352 return;
353 }
354
355 let mut level_stats: Vec<LevelStats> = Vec::new();
356 let mut queue: VecDeque<(usize, SharedPointer<Node<(K, V), P>, P>)> = VecDeque::new();
357 let mut max_depth = 0;
358
359 if let Some(ref root) = self.root {
361 queue.push_back((0, root.clone()));
362 }
363
364 while let Some((level, node)) = queue.pop_front() {
366 while level_stats.len() <= level {
368 level_stats.push(LevelStats::default());
369 }
370
371 let stats = &mut level_stats[level];
372 stats.node_count += 1;
373
374 node.analyze_structure(|entry| {
376 stats.total_entries += 1;
377 match entry {
378 NodeEntry::Value(_, _) => {
379 stats.value_count += 1;
380 max_depth = max_depth.max(level);
381 }
382 NodeEntry::Collision(_coll) => {
383 stats.collision_count += 1;
384 max_depth = max_depth.max(level);
386 }
387 NodeEntry::HamtNode(child_node) => {
388 stats.child_node_count += 1;
389 queue.push_back((level + 1, child_node.clone()));
390 }
391 NodeEntry::SmallSimdNode(small_node) => {
392 stats.small_simd_node_count += 1;
393 stats.small_simd_entry_sum += small_node.len();
394 max_depth = max_depth.max(level + 1);
395 }
396 NodeEntry::LargeSimdNode(large_node) => {
397 stats.large_simd_node_count += 1;
398 stats.large_simd_entry_sum += large_node.len();
399 max_depth = max_depth.max(level + 1);
400 }
401 }
402 })
403 }
404
405 println!(
407 " Hash level size (bits): {}",
408 crate::config::HASH_LEVEL_SIZE
409 );
410 println!(
411 " Branching factor: {}",
412 2_usize.pow(crate::config::HASH_LEVEL_SIZE as u32)
413 );
414 println!(" Total entries: {}", self.size);
415 println!(" Tree depth: {} levels", max_depth + 1);
416 println!();
417
418 for (level, stats) in level_stats.iter().enumerate() {
419 println!(" Level {}:", level);
420 println!(" Nodes: {}", stats.node_count);
421
422 if stats.total_entries > 0 {
423 let avg_entries = stats.total_entries as f64 / stats.node_count as f64;
424 println!(" Average entries per node: {:.2}", avg_entries);
425
426 println!(" Entry types:");
427 println!(
428 " Values: {} ({:.1}%)",
429 stats.value_count,
430 (stats.value_count as f64 / stats.total_entries as f64) * 100.0
431 );
432 println!(
433 " Collisions: {} (avg len: {:.1}) ({:.1}%)",
434 stats.collision_count,
435 if stats.collision_count > 0 {
436 stats.collision_entry_sum as f64 / stats.collision_count as f64
437 } else {
438 0.0
439 },
440 (stats.collision_count as f64 / stats.total_entries as f64) * 100.0
441 );
442 println!(
443 " Child HAMT nodes: {} ({:.1}%)",
444 stats.child_node_count,
445 (stats.child_node_count as f64 / stats.total_entries as f64) * 100.0
446 );
447 if stats.small_simd_node_count > 0 {
448 println!(
449 " Small SIMD leaf nodes: {} ({:.1}%) [total values: {}]",
450 stats.small_simd_node_count,
451 (stats.small_simd_node_count as f64 / stats.total_entries as f64) * 100.0,
452 stats.small_simd_entry_sum
453 );
454 println!(
455 " → Avg values per small SIMD node: {:.1}",
456 stats.small_simd_entry_sum as f64 / stats.small_simd_node_count as f64
457 );
458 }
459 if stats.large_simd_node_count > 0 {
460 println!(
461 " Large SIMD leaf nodes: {} ({:.1}%) [total values: {}]",
462 stats.large_simd_node_count,
463 (stats.large_simd_node_count as f64 / stats.total_entries as f64) * 100.0,
464 stats.large_simd_entry_sum
465 );
466 println!(
467 " → Avg values per large SIMD node: {:.1}",
468 stats.large_simd_entry_sum as f64 / stats.large_simd_node_count as f64
469 );
470 }
471 }
472 println!();
473 }
474 }
475}
476
477impl<K, V, S, P> GenericHashMap<K, V, S, P>
478where
479 K: Hash + Eq,
480 S: BuildHasher + Clone,
481 P: SharedPointerKind,
482{
483 fn test_eq<S2: BuildHasher + Clone, P2: SharedPointerKind>(
484 &self,
485 other: &GenericHashMap<K, V, S2, P2>,
486 ) -> bool
487 where
488 V: PartialEq,
489 {
490 if self.len() != other.len() {
491 return false;
492 }
493 let mut seen = collections::HashSet::new();
494 for (key, value) in self.iter() {
495 if Some(value) != other.get(key) {
496 return false;
497 }
498 seen.insert(key);
499 }
500 for key in other.keys() {
501 if !seen.contains(&key) {
502 return false;
503 }
504 }
505 true
506 }
507
508 #[must_use]
524 pub fn get<Q>(&self, key: &Q) -> Option<&V>
525 where
526 Q: Hash + Equivalent<K> + ?Sized,
527 {
528 if let Some(root) = &self.root {
529 root.get(hash_key(&self.hasher, key), 0, key)
530 .map(|(_, v)| v)
531 } else {
532 None
533 }
534 }
535
536 #[must_use]
552 pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
553 where
554 Q: Hash + Equivalent<K> + ?Sized,
555 {
556 if let Some(root) = &self.root {
557 root.get(hash_key(&self.hasher, key), 0, key)
558 .map(|(k, v)| (k, v))
559 } else {
560 None
561 }
562 }
563
564 #[inline]
582 #[must_use]
583 pub fn contains_key<Q>(&self, k: &Q) -> bool
584 where
585 Q: Hash + Equivalent<K> + ?Sized,
586 {
587 self.get(k).is_some()
588 }
589
590 #[must_use]
598 pub fn is_submap_by<B, RM, F, P2: SharedPointerKind>(&self, other: RM, mut cmp: F) -> bool
599 where
600 F: FnMut(&V, &B) -> bool,
601 RM: Borrow<GenericHashMap<K, B, S, P2>>,
602 {
603 self.iter()
604 .all(|(k, v)| other.borrow().get(k).map(|ov| cmp(v, ov)).unwrap_or(false))
605 }
606
607 #[must_use]
616 pub fn is_proper_submap_by<B, RM, F, P2: SharedPointerKind>(&self, other: RM, cmp: F) -> bool
617 where
618 F: FnMut(&V, &B) -> bool,
619 RM: Borrow<GenericHashMap<K, B, S, P2>>,
620 {
621 self.len() != other.borrow().len() && self.is_submap_by(other, cmp)
622 }
623
624 #[inline]
640 #[must_use]
641 pub fn is_submap<RM>(&self, other: RM) -> bool
642 where
643 V: PartialEq,
644 RM: Borrow<Self>,
645 {
646 self.is_submap_by(other.borrow(), PartialEq::eq)
647 }
648
649 #[inline]
670 #[must_use]
671 pub fn is_proper_submap<RM>(&self, other: RM) -> bool
672 where
673 V: PartialEq,
674 RM: Borrow<Self>,
675 {
676 self.is_proper_submap_by(other.borrow(), PartialEq::eq)
677 }
678}
679
680impl<K, V, S, P> GenericHashMap<K, V, S, P>
681where
682 K: Hash + Eq + Clone,
683 V: Clone,
684 S: BuildHasher + Clone,
685 P: SharedPointerKind,
686{
687 #[inline]
695 #[must_use]
696 pub fn iter_mut(&mut self) -> IterMut<'_, K, V, P> {
697 let root = self.root.as_mut().map(|r| SharedPointer::make_mut(r));
698 IterMut {
699 it: NodeIterMut::new(root, self.size),
700 }
701 }
702
703 #[must_use]
723 pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
724 where
725 Q: Hash + Equivalent<K> + ?Sized,
726 {
727 self.get_key_value_mut(key).map(|(_, v)| v)
728 }
729
730 #[must_use]
746 pub fn get_key_value_mut<Q>(&mut self, key: &Q) -> Option<(&K, &mut V)>
747 where
748 Q: Hash + Equivalent<K> + ?Sized,
749 {
750 let root = self.root.as_mut()?;
751 match SharedPointer::make_mut(root).get_mut(hash_key(&self.hasher, key), 0, key) {
752 None => None,
753 Some((key, value)) => Some((key, value)),
754 }
755 }
756
757 #[inline]
778 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
779 let hash = hash_key(&self.hasher, &k);
780 let root = SharedPointer::make_mut(self.root.get_or_insert_with(SharedPointer::default));
781 let result = root.insert(hash, 0, (k, v));
782 if result.is_none() {
783 self.size += 1;
784 }
785 result.map(|(_, v)| v)
786 }
787
788 pub fn remove<Q>(&mut self, k: &Q) -> Option<V>
809 where
810 Q: Hash + Equivalent<K> + ?Sized,
811 {
812 self.remove_with_key(k).map(|(_, v)| v)
813 }
814
815 pub fn remove_with_key<Q>(&mut self, k: &Q) -> Option<(K, V)>
832 where
833 Q: Hash + Equivalent<K> + ?Sized,
834 {
835 let Some(root) = &mut self.root else {
836 return None;
837 };
838 let result = SharedPointer::make_mut(root).remove(hash_key(&self.hasher, k), 0, k);
839 if result.is_some() {
840 self.size -= 1;
841 }
842 result
843 }
844
845 #[must_use]
851 pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S, P> {
852 let hash = hash_key(&self.hasher, &key);
853 if self
854 .root
855 .as_ref()
856 .and_then(|r| r.get(hash, 0, &key))
857 .is_some()
858 {
859 Entry::Occupied(OccupiedEntry {
860 map: self,
861 hash,
862 key,
863 })
864 } else {
865 Entry::Vacant(VacantEntry {
866 map: self,
867 hash,
868 key,
869 })
870 }
871 }
872
873 #[inline]
892 #[must_use]
893 pub fn update(&self, k: K, v: V) -> Self {
894 let mut out = self.clone();
895 out.insert(k, v);
896 out
897 }
898
899 #[must_use]
908 pub fn update_with<F>(&self, k: K, v: V, f: F) -> Self
909 where
910 F: FnOnce(V, V) -> V,
911 {
912 match self.extract_with_key(&k) {
913 None => self.update(k, v),
914 Some((_, v2, m)) => m.update(k, f(v2, v)),
915 }
916 }
917
918 #[must_use]
927 pub fn update_with_key<F>(&self, k: K, v: V, f: F) -> Self
928 where
929 F: FnOnce(&K, V, V) -> V,
930 {
931 match self.extract_with_key(&k) {
932 None => self.update(k, v),
933 Some((_, v2, m)) => {
934 let out_v = f(&k, v2, v);
935 m.update(k, out_v)
936 }
937 }
938 }
939
940 #[must_use]
950 pub fn update_lookup_with_key<F>(&self, k: K, v: V, f: F) -> (Option<V>, Self)
951 where
952 F: FnOnce(&K, &V, V) -> V,
953 {
954 match self.extract_with_key(&k) {
955 None => (None, self.update(k, v)),
956 Some((_, v2, m)) => {
957 let out_v = f(&k, &v2, v);
958 (Some(v2), m.update(k, out_v))
959 }
960 }
961 }
962
963 #[must_use]
976 pub fn alter<F>(&self, f: F, k: K) -> Self
977 where
978 F: FnOnce(Option<V>) -> Option<V>,
979 {
980 let pop = self.extract_with_key(&k);
981 match (f(pop.as_ref().map(|(_, v, _)| v.clone())), pop) {
982 (None, None) => self.clone(),
983 (Some(v), None) => self.update(k, v),
984 (None, Some((_, _, m))) => m,
985 (Some(v), Some((_, _, m))) => m.update(k, v),
986 }
987 }
988
989 #[must_use]
996 pub fn without<Q>(&self, k: &Q) -> Self
997 where
998 Q: Hash + Equivalent<K> + ?Sized,
999 {
1000 match self.extract_with_key(k) {
1001 None => self.clone(),
1002 Some((_, _, map)) => map,
1003 }
1004 }
1005
1006 pub fn retain<F>(&mut self, mut f: F)
1026 where
1027 F: FnMut(&K, &V) -> bool,
1028 {
1029 let Some(root) = &mut self.root else {
1030 return;
1031 };
1032 let old_root = root.clone();
1033 let root = SharedPointer::make_mut(root);
1034 for ((key, value), hash) in NodeIter::new(Some(&old_root), self.size) {
1035 if !f(key, value) && root.remove(hash, 0, key).is_some() {
1036 self.size -= 1;
1037 }
1038 }
1039 }
1040
1041 #[must_use]
1046 pub fn extract<Q>(&self, k: &Q) -> Option<(V, Self)>
1047 where
1048 Q: Hash + Equivalent<K> + ?Sized,
1049 {
1050 self.extract_with_key(k).map(|(_, v, m)| (v, m))
1051 }
1052
1053 #[must_use]
1058 pub fn extract_with_key<Q>(&self, k: &Q) -> Option<(K, V, Self)>
1059 where
1060 Q: Hash + Equivalent<K> + ?Sized,
1061 {
1062 let mut out = self.clone();
1063 out.remove_with_key(k).map(|(k, v)| (k, v, out))
1064 }
1065
1066 #[must_use]
1082 pub fn union(self, other: Self) -> Self {
1083 let (mut to_mutate, to_consume, use_to_consume) = if self.len() >= other.len() {
1084 (self, other, false)
1085 } else {
1086 (other, self, true)
1087 };
1088 for (k, v) in to_consume {
1089 match to_mutate.entry(k) {
1090 Entry::Occupied(mut e) if use_to_consume => {
1091 e.insert(v);
1092 }
1093 Entry::Vacant(e) => {
1094 e.insert(v);
1095 }
1096 _ => {}
1097 }
1098 }
1099 to_mutate
1100 }
1101
1102 #[inline]
1112 #[must_use]
1113 pub fn union_with<F>(self, other: Self, mut f: F) -> Self
1114 where
1115 F: FnMut(V, V) -> V,
1116 {
1117 self.union_with_key(other, |_, v1, v2| f(v1, v2))
1118 }
1119
1120 #[must_use]
1145 pub fn union_with_key<F>(self, other: Self, mut f: F) -> Self
1146 where
1147 F: FnMut(&K, V, V) -> V,
1148 {
1149 if self.len() >= other.len() {
1150 self.union_with_key_inner(other, f)
1151 } else {
1152 other.union_with_key_inner(self, |key, other_value, self_value| {
1153 f(key, self_value, other_value)
1154 })
1155 }
1156 }
1157
1158 fn union_with_key_inner<F>(mut self, other: Self, mut f: F) -> Self
1159 where
1160 F: FnMut(&K, V, V) -> V,
1161 {
1162 for (key, right_value) in other {
1163 match self.remove(&key) {
1164 None => {
1165 self.insert(key, right_value);
1166 }
1167 Some(left_value) => {
1168 let final_value = f(&key, left_value, right_value);
1169 self.insert(key, final_value);
1170 }
1171 }
1172 }
1173 self
1174 }
1175
1176 #[must_use]
1192 pub fn unions<I>(i: I) -> Self
1193 where
1194 S: Default,
1195 I: IntoIterator<Item = Self>,
1196 {
1197 i.into_iter().fold(Self::default(), Self::union)
1198 }
1199
1200 #[must_use]
1211 pub fn unions_with<I, F>(i: I, f: F) -> Self
1212 where
1213 S: Default,
1214 I: IntoIterator<Item = Self>,
1215 F: Fn(V, V) -> V,
1216 {
1217 i.into_iter()
1218 .fold(Self::default(), |a, b| a.union_with(b, &f))
1219 }
1220
1221 #[must_use]
1233 pub fn unions_with_key<I, F>(i: I, f: F) -> Self
1234 where
1235 S: Default,
1236 I: IntoIterator<Item = Self>,
1237 F: Fn(&K, V, V) -> V,
1238 {
1239 i.into_iter()
1240 .fold(Self::default(), |a, b| a.union_with_key(b, &f))
1241 }
1242
1243 #[deprecated(
1264 since = "2.0.1",
1265 note = "to avoid conflicting behaviors between std and imbl, the `difference` alias for `symmetric_difference` will be removed."
1266 )]
1267 #[inline]
1268 #[must_use]
1269 pub fn difference(self, other: Self) -> Self {
1270 self.symmetric_difference(other)
1271 }
1272
1273 #[inline]
1289 #[must_use]
1290 pub fn symmetric_difference(self, other: Self) -> Self {
1291 self.symmetric_difference_with_key(other, |_, _, _| None)
1292 }
1293
1294 #[deprecated(
1304 since = "2.0.1",
1305 note = "to avoid conflicting behaviors between std and imbl, the `difference_with` alias for `symmetric_difference_with` will be removed."
1306 )]
1307 #[inline]
1308 #[must_use]
1309 pub fn difference_with<F>(self, other: Self, f: F) -> Self
1310 where
1311 F: FnMut(V, V) -> Option<V>,
1312 {
1313 self.symmetric_difference_with(other, f)
1314 }
1315
1316 #[inline]
1321 #[must_use]
1322 pub fn symmetric_difference_with<F>(self, other: Self, mut f: F) -> Self
1323 where
1324 F: FnMut(V, V) -> Option<V>,
1325 {
1326 self.symmetric_difference_with_key(other, |_, a, b| f(a, b))
1327 }
1328
1329 #[deprecated(
1355 since = "2.0.1",
1356 note = "to avoid conflicting behaviors between std and imbl, the `difference_with_key` alias for `symmetric_difference_with_key` will be removed."
1357 )]
1358 #[must_use]
1359 pub fn difference_with_key<F>(self, other: Self, f: F) -> Self
1360 where
1361 F: FnMut(&K, V, V) -> Option<V>,
1362 {
1363 self.symmetric_difference_with_key(other, f)
1364 }
1365
1366 #[must_use]
1386 pub fn symmetric_difference_with_key<F>(mut self, other: Self, mut f: F) -> Self
1387 where
1388 F: FnMut(&K, V, V) -> Option<V>,
1389 {
1390 let mut out = self.new_from();
1391 for (key, right_value) in other {
1392 match self.remove(&key) {
1393 None => {
1394 out.insert(key, right_value);
1395 }
1396 Some(left_value) => {
1397 if let Some(final_value) = f(&key, left_value, right_value) {
1398 out.insert(key, final_value);
1399 }
1400 }
1401 }
1402 }
1403 out.union(self)
1404 }
1405
1406 #[inline]
1422 #[must_use]
1423 pub fn relative_complement(mut self, other: Self) -> Self {
1424 for (key, _) in other {
1425 let _ = self.remove(&key);
1426 }
1427 self
1428 }
1429
1430 #[inline]
1446 #[must_use]
1447 pub fn intersection(self, other: Self) -> Self {
1448 self.intersection_with_key(other, |_, v, _| v)
1449 }
1450
1451 #[inline]
1457 #[must_use]
1458 pub fn intersection_with<B, C, F>(
1459 self,
1460 other: GenericHashMap<K, B, S, P>,
1461 mut f: F,
1462 ) -> GenericHashMap<K, C, S, P>
1463 where
1464 B: Clone,
1465 C: Clone,
1466 F: FnMut(V, B) -> C,
1467 {
1468 self.intersection_with_key(other, |_, v1, v2| f(v1, v2))
1469 }
1470
1471 #[must_use]
1491 pub fn intersection_with_key<B, C, F>(
1492 mut self,
1493 other: GenericHashMap<K, B, S, P>,
1494 mut f: F,
1495 ) -> GenericHashMap<K, C, S, P>
1496 where
1497 B: Clone,
1498 C: Clone,
1499 F: FnMut(&K, V, B) -> C,
1500 {
1501 let mut out = self.new_from();
1502 for (key, right_value) in other {
1503 match self.remove(&key) {
1504 None => (),
1505 Some(left_value) => {
1506 let result = f(&key, left_value, right_value);
1507 out.insert(key, result);
1508 }
1509 }
1510 }
1511 out
1512 }
1513}
1514
1515pub enum Entry<'a, K, V, S, P>
1529where
1530 K: Hash + Eq + Clone,
1531 V: Clone,
1532 S: BuildHasher + Clone,
1533 P: SharedPointerKind,
1534{
1535 Occupied(OccupiedEntry<'a, K, V, S, P>),
1537 Vacant(VacantEntry<'a, K, V, S, P>),
1539}
1540
1541impl<'a, K, V, S, P> Entry<'a, K, V, S, P>
1542where
1543 K: 'a + Hash + Eq + Clone,
1544 V: 'a + Clone,
1545 S: 'a + BuildHasher + Clone,
1546 P: SharedPointerKind,
1547{
1548 pub fn or_insert(self, default: V) -> &'a mut V {
1551 self.or_insert_with(|| default)
1552 }
1553
1554 pub fn or_insert_with<F>(self, default: F) -> &'a mut V
1558 where
1559 F: FnOnce() -> V,
1560 {
1561 match self {
1562 Entry::Occupied(entry) => entry.into_mut(),
1563 Entry::Vacant(entry) => entry.insert(default()),
1564 }
1565 }
1566
1567 pub fn or_default(self) -> &'a mut V
1570 where
1571 V: Default,
1572 {
1573 #[allow(clippy::unwrap_or_default)]
1574 self.or_insert_with(Default::default)
1575 }
1576
1577 #[must_use]
1579 pub fn key(&self) -> &K {
1580 match self {
1581 Entry::Occupied(entry) => entry.key(),
1582 Entry::Vacant(entry) => entry.key(),
1583 }
1584 }
1585
1586 pub fn and_modify<F>(mut self, f: F) -> Self
1589 where
1590 F: FnOnce(&mut V),
1591 {
1592 match &mut self {
1593 Entry::Occupied(ref mut entry) => f(entry.get_mut()),
1594 Entry::Vacant(_) => (),
1595 }
1596 self
1597 }
1598}
1599
1600pub struct OccupiedEntry<'a, K, V, S, P>
1602where
1603 K: Hash + Eq + Clone,
1604 V: Clone,
1605 S: BuildHasher + Clone,
1606 P: SharedPointerKind,
1607{
1608 map: &'a mut GenericHashMap<K, V, S, P>,
1609 hash: HashBits,
1610 key: K,
1611}
1612
1613impl<'a, K, V, S, P> OccupiedEntry<'a, K, V, S, P>
1614where
1615 K: 'a + Hash + Eq + Clone,
1616 V: 'a + Clone,
1617 S: 'a + BuildHasher + Clone,
1618 P: SharedPointerKind,
1619{
1620 #[must_use]
1622 pub fn key(&self) -> &K {
1623 &self.key
1624 }
1625
1626 pub fn remove_entry(self) -> (K, V) {
1628 let root = SharedPointer::make_mut(self.map.root.as_mut().unwrap());
1630 let result = root.remove(self.hash, 0, &self.key);
1631 self.map.size -= 1;
1632 result.unwrap()
1633 }
1634
1635 #[must_use]
1637 pub fn get(&self) -> &V {
1638 &self
1640 .map
1641 .root
1642 .as_ref()
1643 .unwrap()
1644 .get(self.hash, 0, &self.key)
1645 .unwrap()
1646 .1
1647 }
1648
1649 #[must_use]
1651 pub fn get_mut(&mut self) -> &mut V {
1652 let root = SharedPointer::make_mut(self.map.root.as_mut().unwrap());
1654 &mut root.get_mut(self.hash, 0, &self.key).unwrap().1
1655 }
1656
1657 #[must_use]
1659 pub fn into_mut(self) -> &'a mut V {
1660 let root = SharedPointer::make_mut(self.map.root.as_mut().unwrap());
1662 &mut root.get_mut(self.hash, 0, &self.key).unwrap().1
1663 }
1664
1665 pub fn insert(&mut self, value: V) -> V {
1667 mem::replace(self.get_mut(), value)
1668 }
1669
1670 pub fn remove(self) -> V {
1672 self.remove_entry().1
1673 }
1674}
1675
1676pub struct VacantEntry<'a, K, V, S, P>
1678where
1679 K: Hash + Eq + Clone,
1680 V: Clone,
1681 S: BuildHasher + Clone,
1682 P: SharedPointerKind,
1683{
1684 map: &'a mut GenericHashMap<K, V, S, P>,
1685 hash: HashBits,
1686 key: K,
1687}
1688
1689impl<'a, K, V, S, P> VacantEntry<'a, K, V, S, P>
1690where
1691 K: 'a + Hash + Eq + Clone,
1692 V: 'a + Clone,
1693 S: 'a + BuildHasher + Clone,
1694 P: SharedPointerKind,
1695{
1696 #[must_use]
1698 pub fn key(&self) -> &K {
1699 &self.key
1700 }
1701
1702 #[must_use]
1704 pub fn into_key(self) -> K {
1705 self.key
1706 }
1707
1708 pub fn insert(self, value: V) -> &'a mut V {
1710 let root =
1711 SharedPointer::make_mut(self.map.root.get_or_insert_with(SharedPointer::default));
1712 if root
1713 .insert(self.hash, 0, (self.key.clone(), value))
1714 .is_none()
1715 {
1716 self.map.size += 1;
1717 }
1718 &mut root.get_mut(self.hash, 0, &self.key).unwrap().1
1721 }
1722}
1723
1724impl<K, V, S, P> Clone for GenericHashMap<K, V, S, P>
1727where
1728 K: Clone,
1729 V: Clone,
1730 S: Clone,
1731 P: SharedPointerKind,
1732{
1733 #[inline]
1737 fn clone(&self) -> Self {
1738 GenericHashMap {
1739 root: self.root.clone(),
1740 size: self.size,
1741 hasher: self.hasher.clone(),
1742 }
1743 }
1744}
1745
1746impl<K, V, S1, S2, P1, P2> PartialEq<GenericHashMap<K, V, S2, P2>> for GenericHashMap<K, V, S1, P1>
1747where
1748 K: Hash + Eq,
1749 V: PartialEq,
1750 S1: BuildHasher + Clone,
1751 S2: BuildHasher + Clone,
1752 P1: SharedPointerKind,
1753 P2: SharedPointerKind,
1754{
1755 fn eq(&self, other: &GenericHashMap<K, V, S2, P2>) -> bool {
1756 self.test_eq(other)
1757 }
1758}
1759
1760impl<K, V, S, P> Eq for GenericHashMap<K, V, S, P>
1761where
1762 K: Hash + Eq,
1763 V: Eq,
1764 S: BuildHasher + Clone,
1765 P: SharedPointerKind,
1766{
1767}
1768
1769impl<K, V, S, P> Default for GenericHashMap<K, V, S, P>
1770where
1771 S: Default,
1772 P: SharedPointerKind,
1773{
1774 #[inline]
1775 fn default() -> Self {
1776 GenericHashMap {
1777 size: 0,
1778 root: None,
1779 hasher: Default::default(),
1780 }
1781 }
1782}
1783
1784impl<K, V, S, P> Add for GenericHashMap<K, V, S, P>
1785where
1786 K: Hash + Eq + Clone,
1787 V: Clone,
1788 S: BuildHasher + Clone,
1789 P: SharedPointerKind,
1790{
1791 type Output = GenericHashMap<K, V, S, P>;
1792
1793 fn add(self, other: Self) -> Self::Output {
1794 self.union(other)
1795 }
1796}
1797
1798impl<K, V, S, P> Add for &GenericHashMap<K, V, S, P>
1799where
1800 K: Hash + Eq + Clone,
1801 V: Clone,
1802 S: BuildHasher + Clone,
1803 P: SharedPointerKind,
1804{
1805 type Output = GenericHashMap<K, V, S, P>;
1806
1807 fn add(self, other: Self) -> Self::Output {
1808 self.clone().union(other.clone())
1809 }
1810}
1811
1812impl<K, V, S, P> Sum for GenericHashMap<K, V, S, P>
1813where
1814 K: Hash + Eq + Clone,
1815 V: Clone,
1816 S: BuildHasher + Default + Clone,
1817 P: SharedPointerKind,
1818{
1819 fn sum<I>(it: I) -> Self
1820 where
1821 I: Iterator<Item = Self>,
1822 {
1823 it.fold(Self::default(), |a, b| a + b)
1824 }
1825}
1826
1827impl<K, V, S, RK, RV, P> Extend<(RK, RV)> for GenericHashMap<K, V, S, P>
1828where
1829 K: Hash + Eq + Clone + From<RK>,
1830 V: Clone + From<RV>,
1831 S: BuildHasher + Clone,
1832 P: SharedPointerKind,
1833{
1834 fn extend<I>(&mut self, iter: I)
1835 where
1836 I: IntoIterator<Item = (RK, RV)>,
1837 {
1838 for (key, value) in iter {
1839 self.insert(From::from(key), From::from(value));
1840 }
1841 }
1842}
1843
1844impl<Q, K, V, S, P> Index<&Q> for GenericHashMap<K, V, S, P>
1845where
1846 Q: Hash + Equivalent<K> + ?Sized,
1847 K: Hash + Eq,
1848 S: BuildHasher + Clone,
1849 P: SharedPointerKind,
1850{
1851 type Output = V;
1852
1853 fn index(&self, key: &Q) -> &Self::Output {
1854 match self.get(key) {
1855 None => panic!("HashMap::index: invalid key"),
1856 Some(value) => value,
1857 }
1858 }
1859}
1860
1861impl<Q, K, V, S, P> IndexMut<&Q> for GenericHashMap<K, V, S, P>
1862where
1863 Q: Hash + Equivalent<K> + ?Sized,
1864 K: Hash + Eq + Clone,
1865 V: Clone,
1866 S: BuildHasher + Clone,
1867 P: SharedPointerKind,
1868{
1869 fn index_mut(&mut self, key: &Q) -> &mut Self::Output {
1870 match self.get_mut(key) {
1871 None => panic!("HashMap::index_mut: invalid key"),
1872 Some(value) => value,
1873 }
1874 }
1875}
1876
1877impl<K, V, S, P> Debug for GenericHashMap<K, V, S, P>
1878where
1879 K: Debug,
1880 V: Debug,
1881 P: SharedPointerKind,
1882{
1883 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
1884 let mut d = f.debug_map();
1885 for (k, v) in self {
1886 d.entry(k, v);
1887 }
1888 d.finish()
1889 }
1890}
1891
1892pub struct Iter<'a, K, V, P: SharedPointerKind> {
1896 it: NodeIter<'a, (K, V), P>,
1897}
1898
1899impl<'a, K, V, P: SharedPointerKind> Clone for Iter<'a, K, V, P> {
1901 fn clone(&self) -> Self {
1902 Iter {
1903 it: self.it.clone(),
1904 }
1905 }
1906}
1907
1908impl<'a, K, V, P: SharedPointerKind> Iterator for Iter<'a, K, V, P> {
1909 type Item = (&'a K, &'a V);
1910
1911 fn next(&mut self) -> Option<Self::Item> {
1912 self.it.next().map(|((k, v), _)| (k, v))
1913 }
1914
1915 fn size_hint(&self) -> (usize, Option<usize>) {
1916 self.it.size_hint()
1917 }
1918}
1919
1920impl<'a, K, V, P: SharedPointerKind> ExactSizeIterator for Iter<'a, K, V, P> {}
1921
1922impl<'a, K, V, P: SharedPointerKind> FusedIterator for Iter<'a, K, V, P> {}
1923
1924pub struct IterMut<'a, K, V, P>
1926where
1927 K: Clone,
1928 V: Clone,
1929 P: SharedPointerKind,
1930{
1931 it: NodeIterMut<'a, (K, V), P>,
1932}
1933
1934impl<'a, K, V, P> Iterator for IterMut<'a, K, V, P>
1935where
1936 K: Clone,
1937 V: Clone,
1938 P: SharedPointerKind,
1939{
1940 type Item = (&'a K, &'a mut V);
1941
1942 fn next(&mut self) -> Option<Self::Item> {
1943 self.it.next().map(|((k, v), _)| (&*k, v))
1944 }
1945
1946 fn size_hint(&self) -> (usize, Option<usize>) {
1947 self.it.size_hint()
1948 }
1949}
1950
1951impl<'a, K, V, P> ExactSizeIterator for IterMut<'a, K, V, P>
1952where
1953 K: Clone,
1954 V: Clone,
1955 P: SharedPointerKind,
1956{
1957}
1958
1959impl<'a, K, V, P> FusedIterator for IterMut<'a, K, V, P>
1960where
1961 K: Clone,
1962 V: Clone,
1963 P: SharedPointerKind,
1964{
1965}
1966
1967pub struct ConsumingIter<A: HashValue, P: SharedPointerKind> {
1969 it: NodeDrain<A, P>,
1970}
1971
1972impl<A: HashValue, P: SharedPointerKind> Clone for ConsumingIter<A, P> {
1973 fn clone(&self) -> Self {
1974 Self {
1975 it: self.it.clone(),
1976 }
1977 }
1978}
1979
1980impl<A, P: SharedPointerKind> Iterator for ConsumingIter<A, P>
1981where
1982 A: HashValue + Clone,
1983{
1984 type Item = A;
1985
1986 fn next(&mut self) -> Option<Self::Item> {
1987 self.it.next().map(|(p, _)| p)
1988 }
1989
1990 fn size_hint(&self) -> (usize, Option<usize>) {
1991 self.it.size_hint()
1992 }
1993}
1994
1995impl<A, P> ExactSizeIterator for ConsumingIter<A, P>
1996where
1997 A: HashValue + Clone,
1998 P: SharedPointerKind,
1999{
2000}
2001
2002impl<A, P> FusedIterator for ConsumingIter<A, P>
2003where
2004 A: HashValue + Clone,
2005 P: SharedPointerKind,
2006{
2007}
2008
2009pub struct Keys<'a, K, V, P: SharedPointerKind> {
2011 it: NodeIter<'a, (K, V), P>,
2012}
2013
2014impl<'a, K, V, P: SharedPointerKind> Iterator for Keys<'a, K, V, P> {
2015 type Item = &'a K;
2016
2017 fn next(&mut self) -> Option<Self::Item> {
2018 self.it.next().map(|((k, _), _)| k)
2019 }
2020
2021 fn size_hint(&self) -> (usize, Option<usize>) {
2022 self.it.size_hint()
2023 }
2024}
2025
2026impl<'a, K, V, P: SharedPointerKind> ExactSizeIterator for Keys<'a, K, V, P> {}
2027
2028impl<'a, K, V, P: SharedPointerKind> FusedIterator for Keys<'a, K, V, P> {}
2029
2030pub struct Values<'a, K, V, P: SharedPointerKind> {
2032 it: NodeIter<'a, (K, V), P>,
2033}
2034
2035impl<'a, K, V, P: SharedPointerKind> Iterator for Values<'a, K, V, P> {
2036 type Item = &'a V;
2037
2038 fn next(&mut self) -> Option<Self::Item> {
2039 self.it.next().map(|((_, v), _)| v)
2040 }
2041
2042 fn size_hint(&self) -> (usize, Option<usize>) {
2043 self.it.size_hint()
2044 }
2045}
2046
2047impl<'a, K, V, P: SharedPointerKind> ExactSizeIterator for Values<'a, K, V, P> {}
2048
2049impl<'a, K, V, P: SharedPointerKind> FusedIterator for Values<'a, K, V, P> {}
2050
2051impl<'a, K, V, S, P: SharedPointerKind> IntoIterator for &'a GenericHashMap<K, V, S, P> {
2052 type Item = (&'a K, &'a V);
2053 type IntoIter = Iter<'a, K, V, P>;
2054
2055 #[inline]
2056 fn into_iter(self) -> Self::IntoIter {
2057 self.iter()
2058 }
2059}
2060
2061impl<K, V, S, P> IntoIterator for GenericHashMap<K, V, S, P>
2062where
2063 K: Hash + Eq + Clone,
2064 V: Clone,
2065 S: BuildHasher + Clone,
2066 P: SharedPointerKind,
2067{
2068 type Item = (K, V);
2069 type IntoIter = ConsumingIter<(K, V), P>;
2070
2071 #[inline]
2072 fn into_iter(self) -> Self::IntoIter {
2073 ConsumingIter {
2074 it: NodeDrain::new(self.root, self.size),
2075 }
2076 }
2077}
2078
2079impl<K, V, S, P> FromIterator<(K, V)> for GenericHashMap<K, V, S, P>
2082where
2083 K: Hash + Eq + Clone,
2084 V: Clone,
2085 S: BuildHasher + Default + Clone,
2086 P: SharedPointerKind,
2087{
2088 fn from_iter<T>(i: T) -> Self
2089 where
2090 T: IntoIterator<Item = (K, V)>,
2091 {
2092 let mut map = Self::default();
2093 for (k, v) in i {
2094 map.insert(k, v);
2095 }
2096 map
2097 }
2098}
2099
2100impl<K, V, S, P: SharedPointerKind> AsRef<GenericHashMap<K, V, S, P>>
2101 for GenericHashMap<K, V, S, P>
2102{
2103 #[inline]
2104 fn as_ref(&self) -> &Self {
2105 self
2106 }
2107}
2108
2109impl<K, V, OK, OV, SA, SB, P1, P2> From<&GenericHashMap<&K, &V, SA, P1>>
2110 for GenericHashMap<OK, OV, SB, P2>
2111where
2112 K: Hash + Equivalent<OK> + ToOwned<Owned = OK> + ?Sized,
2113 V: ToOwned<Owned = OV> + ?Sized,
2114 OK: Hash + Eq + Clone,
2115 OV: Borrow<V> + Clone,
2116 SA: BuildHasher + Clone,
2117 SB: BuildHasher + Default + Clone,
2118 P1: SharedPointerKind,
2119 P2: SharedPointerKind,
2120{
2121 fn from(m: &GenericHashMap<&K, &V, SA, P1>) -> Self {
2122 m.iter()
2123 .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
2124 .collect()
2125 }
2126}
2127
2128impl<'a, K, V, S, P> From<&'a [(K, V)]> for GenericHashMap<K, V, S, P>
2129where
2130 K: Hash + Eq + Clone,
2131 V: Clone,
2132 S: BuildHasher + Default + Clone,
2133 P: SharedPointerKind,
2134{
2135 fn from(m: &'a [(K, V)]) -> Self {
2136 m.iter().cloned().collect()
2137 }
2138}
2139
2140impl<K, V, S, P> From<Vec<(K, V)>> for GenericHashMap<K, V, S, P>
2141where
2142 K: Hash + Eq + Clone,
2143 V: Clone,
2144 S: BuildHasher + Default + Clone,
2145 P: SharedPointerKind,
2146{
2147 fn from(m: Vec<(K, V)>) -> Self {
2148 m.into_iter().collect()
2149 }
2150}
2151
2152impl<'a, K, V, S, P> From<&'a Vec<(K, V)>> for GenericHashMap<K, V, S, P>
2153where
2154 K: Hash + Eq + Clone,
2155 V: Clone,
2156 S: BuildHasher + Default + Clone,
2157 P: SharedPointerKind,
2158{
2159 fn from(m: &'a Vec<(K, V)>) -> Self {
2160 m.iter().cloned().collect()
2161 }
2162}
2163
2164impl<K, V, S1, S2, P> From<collections::HashMap<K, V, S2>> for GenericHashMap<K, V, S1, P>
2165where
2166 K: Hash + Eq + Clone,
2167 V: Clone,
2168 S1: BuildHasher + Default + Clone,
2169 S2: BuildHasher,
2170 P: SharedPointerKind,
2171{
2172 fn from(m: collections::HashMap<K, V, S2>) -> Self {
2173 m.into_iter().collect()
2174 }
2175}
2176
2177impl<'a, K, V, S1, S2, P> From<&'a collections::HashMap<K, V, S2>> for GenericHashMap<K, V, S1, P>
2178where
2179 K: Hash + Eq + Clone,
2180 V: Clone,
2181 S1: BuildHasher + Default + Clone,
2182 S2: BuildHasher,
2183 P: SharedPointerKind,
2184{
2185 fn from(m: &'a collections::HashMap<K, V, S2>) -> Self {
2186 m.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
2187 }
2188}
2189
2190impl<K, V, S, P> From<collections::BTreeMap<K, V>> for GenericHashMap<K, V, S, P>
2191where
2192 K: Hash + Eq + Clone,
2193 V: Clone,
2194 S: BuildHasher + Default + Clone,
2195 P: SharedPointerKind,
2196{
2197 fn from(m: collections::BTreeMap<K, V>) -> Self {
2198 m.into_iter().collect()
2199 }
2200}
2201
2202impl<'a, K, V, S, P> From<&'a collections::BTreeMap<K, V>> for GenericHashMap<K, V, S, P>
2203where
2204 K: Hash + Eq + Clone,
2205 V: Clone,
2206 S: BuildHasher + Default + Clone,
2207 P: SharedPointerKind,
2208{
2209 fn from(m: &'a collections::BTreeMap<K, V>) -> Self {
2210 m.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
2211 }
2212}
2213
2214#[cfg(any(test, feature = "proptest"))]
2234#[doc(hidden)]
2235pub mod proptest {
2236 #[deprecated(
2237 since = "14.3.0",
2238 note = "proptest strategies have moved to imbl::proptest"
2239 )]
2240 pub use crate::proptest::hash_map;
2241}
2242
2243#[cfg(test)]
2246mod test {
2247 use super::*;
2248 use crate::test::LolHasher;
2249 #[rustfmt::skip]
2250 use ::proptest::{collection, num::{i16, usize}, proptest};
2251 use static_assertions::{assert_impl_all, assert_not_impl_any};
2252 use std::hash::BuildHasherDefault;
2253
2254 assert_impl_all!(HashMap<i32, i32>: Send, Sync);
2255 assert_not_impl_any!(HashMap<i32, *const i32>: Send, Sync);
2256 assert_not_impl_any!(HashMap<*const i32, i32>: Send, Sync);
2257 assert_covariant!(HashMap<T, i32> in T);
2258 assert_covariant!(HashMap<i32, T> in T);
2259
2260 #[test]
2261 fn safe_mutation() {
2262 let v1: HashMap<usize, usize> = GenericHashMap::from_iter((0..131_072).map(|i| (i, i)));
2263 let mut v2 = v1.clone();
2264 v2.insert(131_000, 23);
2265 assert_eq!(Some(&23), v2.get(&131_000));
2266 assert_eq!(Some(&131_000), v1.get(&131_000));
2267 }
2268
2269 #[test]
2270 fn index_operator() {
2271 let mut map: HashMap<usize, usize> = hashmap![1 => 2, 3 => 4, 5 => 6];
2272 assert_eq!(4, map[&3]);
2273 map[&3] = 8;
2274 let target_map: HashMap<usize, usize> = hashmap![1 => 2, 3 => 8, 5 => 6];
2275 assert_eq!(target_map, map);
2276 }
2277
2278 #[test]
2279 fn proper_formatting() {
2280 let map: HashMap<usize, usize> = hashmap![1 => 2];
2281 assert_eq!("{1: 2}", format!("{:?}", map));
2282
2283 assert_eq!("{}", format!("{:?}", HashMap::<(), ()>::new()));
2284 }
2285
2286 #[test]
2287 fn remove_failing() {
2288 let pairs = [(1469, 0), (-67, 0)];
2289 let mut m: collections::HashMap<i16, i16, _> =
2290 collections::HashMap::with_hasher(BuildHasherDefault::<LolHasher>::default());
2291 for (k, v) in &pairs {
2292 m.insert(*k, *v);
2293 }
2294 let mut map: GenericHashMap<i16, i16, _, DefaultSharedPtr> =
2295 GenericHashMap::with_hasher(BuildHasherDefault::<LolHasher>::default());
2296 for (k, v) in &m {
2297 map = map.update(*k, *v);
2298 }
2299 for k in m.keys() {
2300 let l = map.len();
2301 assert_eq!(m.get(k).cloned(), map.get(k).cloned());
2302 map = map.without(k);
2303 assert_eq!(None, map.get(k));
2304 assert_eq!(l - 1, map.len());
2305 }
2306 }
2307
2308 #[test]
2309 fn match_string_keys_with_string_slices() {
2310 let tmp_map: HashMap<&str, &i32> = hashmap! { "foo" => &1, "bar" => &2, "baz" => &3 };
2311 let mut map: HashMap<String, i32> = From::from(&tmp_map);
2312 assert_eq!(Some(&1), map.get("foo"));
2313 map = map.without("foo");
2314 assert_eq!(Some(3), map.remove("baz"));
2315 map["bar"] = 8;
2316 assert_eq!(8, map["bar"]);
2317 }
2318
2319 #[test]
2320 fn macro_allows_trailing_comma() {
2321 let map1: HashMap<&str, i32> = hashmap! {"x" => 1, "y" => 2};
2322 let map2: HashMap<&str, i32> = hashmap! {
2323 "x" => 1,
2324 "y" => 2,
2325 };
2326 assert_eq!(map1, map2);
2327 }
2328
2329 #[test]
2330 fn remove_top_level_collisions() {
2331 let pairs = vec![9, 2569, 27145];
2332 let mut map: GenericHashMap<i16, i16, BuildHasherDefault<LolHasher>, DefaultSharedPtr> =
2333 Default::default();
2334 for k in pairs.clone() {
2335 map.insert(k, k);
2336 }
2337 assert_eq!(pairs.len(), map.len());
2338 let keys: Vec<_> = map.keys().cloned().collect();
2339 for k in keys {
2340 let l = map.len();
2341 assert_eq!(Some(&k), map.get(&k));
2342 map.remove(&k);
2343 assert_eq!(None, map.get(&k));
2344 assert_eq!(l - 1, map.len());
2345 }
2346 }
2347
2348 #[test]
2349 fn entry_api() {
2350 let mut map: HashMap<&str, i32> = hashmap! {"bar" => 5};
2351 map.entry("foo").and_modify(|v| *v += 5).or_insert(1);
2352 assert_eq!(1, map[&"foo"]);
2353 map.entry("foo").and_modify(|v| *v += 5).or_insert(1);
2354 assert_eq!(6, map[&"foo"]);
2355 map.entry("bar").and_modify(|v| *v += 5).or_insert(1);
2356 assert_eq!(10, map[&"bar"]);
2357 assert_eq!(
2358 10,
2359 match map.entry("bar") {
2360 Entry::Occupied(entry) => entry.remove(),
2361 _ => panic!(),
2362 }
2363 );
2364 assert!(!map.contains_key(&"bar"));
2365 }
2366
2367 #[test]
2368 fn refpool_crash() {
2369 let _map = HashMap::<u128, usize>::new();
2370 }
2371
2372 #[test]
2373 fn large_map() {
2374 let mut map = HashMap::<_, _>::new();
2375 let size = 32769;
2376 for i in 0..size {
2377 map.insert(i, i);
2378 }
2379 assert_eq!(size, map.len());
2380 for i in 0..size {
2381 assert_eq!(Some(&i), map.get(&i));
2382 }
2383 }
2384
2385 struct PanicOnClone;
2386
2387 impl Clone for PanicOnClone {
2388 fn clone(&self) -> Self {
2389 panic!("PanicOnClone::clone called")
2390 }
2391 }
2392
2393 #[test]
2394 fn into_iter_no_clone() {
2395 let mut map = HashMap::new();
2396 for i in 0..10_000 {
2397 map.insert(i, PanicOnClone);
2398 }
2399 let _ = map.into_iter().collect::<Vec<_>>();
2400 }
2401
2402 #[test]
2403 fn iter_mut_no_clone() {
2404 let mut map = HashMap::new();
2405 for i in 0..10_000 {
2406 map.insert(i, PanicOnClone);
2407 }
2408 let _ = map.iter_mut().collect::<Vec<_>>();
2409 }
2410
2411 #[test]
2412 fn iter_no_clone() {
2413 let mut map = HashMap::new();
2414 for i in 0..10_000 {
2415 map.insert(i, PanicOnClone);
2416 }
2417 let _ = map.iter().collect::<Vec<_>>();
2418 }
2419
2420 proptest! {
2421 #[test]
2422 fn update_and_length(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2423 let mut map: GenericHashMap<i16, i16, BuildHasherDefault<LolHasher>, DefaultSharedPtr> = Default::default();
2424 for (index, (k, v)) in m.iter().enumerate() {
2425 map = map.update(*k, *v);
2426 assert_eq!(Some(v), map.get(k));
2427 assert_eq!(index + 1, map.len());
2428 }
2429 }
2430
2431 #[test]
2432 fn from_iterator(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2433 let map: HashMap<i16, i16> =
2434 FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2435 assert_eq!(m.len(), map.len());
2436 }
2437
2438 #[test]
2439 fn iterate_over(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2440 let map: HashMap<i16, i16> = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2441 assert_eq!(m.len(), map.iter().count());
2442 }
2443
2444 #[test]
2445 fn equality(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2446 let map1: HashMap<i16, i16> = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2447 let map2: HashMap<i16, i16> = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2448 assert_eq!(map1, map2);
2449 }
2450
2451 #[test]
2452 fn lookup(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2453 let map: HashMap<i16, i16> = FromIterator::from_iter(m.iter().map(|(k, v)| (*k, *v)));
2454 for (k, v) in m {
2455 assert_eq!(Some(*v), map.get(k).cloned(), "{k} not found in map {map:?}");
2456 }
2457 }
2458
2459 #[test]
2460 fn without(ref pairs in collection::vec((i16::ANY, i16::ANY), 0..100)) {
2461 let mut m: collections::HashMap<i16, i16, _> =
2462 collections::HashMap::with_hasher(BuildHasherDefault::<LolHasher>::default());
2463 for (k, v) in pairs {
2464 m.insert(*k, *v);
2465 }
2466 let mut map: GenericHashMap<i16, i16, _, DefaultSharedPtr> = GenericHashMap::with_hasher(BuildHasherDefault::<LolHasher>::default());
2467 for (k, v) in &m {
2468 map = map.update(*k, *v);
2469 }
2470 for k in m.keys() {
2471 let l = map.len();
2472 assert_eq!(m.get(k).cloned(), map.get(k).cloned());
2473 map = map.without(k);
2474 assert_eq!(None, map.get(k));
2475 assert_eq!(l - 1, map.len());
2476 }
2477 }
2478
2479 #[test]
2480 fn insert(ref m in collection::hash_map(i16::ANY, i16::ANY, 0..1000)) {
2481 let mut mut_map: GenericHashMap<i16, i16, BuildHasherDefault<LolHasher>, DefaultSharedPtr> = Default::default();
2482 let mut map: GenericHashMap<i16, i16, BuildHasherDefault<LolHasher>, DefaultSharedPtr> = Default::default();
2483 for (count, (k, v)) in m.iter().enumerate() {
2484 map = map.update(*k, *v);
2485 mut_map.insert(*k, *v);
2486 assert_eq!(count + 1, map.len());
2487 assert_eq!(count + 1, mut_map.len());
2488 }
2489 for (k, v) in m {
2490 assert_eq!(Some(v), map.get(k));
2491 assert_eq!(Some(v), mut_map.get(k));
2492 }
2493 assert_eq!(map, mut_map);
2494 }
2495
2496 #[test]
2497 fn remove(ref pairs in collection::vec((i16::ANY, i16::ANY), 0..100)) {
2498 let mut m: collections::HashMap<i16, i16, _> =
2499 collections::HashMap::with_hasher(BuildHasherDefault::<LolHasher>::default());
2500 for (k, v) in pairs {
2501 m.insert(*k, *v);
2502 }
2503 let mut map: GenericHashMap<i16, i16, _, DefaultSharedPtr> = GenericHashMap::with_hasher(BuildHasherDefault::<LolHasher>::default());
2504 for (k, v) in &m {
2505 map.insert(*k, *v);
2506 }
2507 for k in m.keys() {
2508 let l = map.len();
2509 assert_eq!(m.get(k).cloned(), map.get(k).cloned());
2510 map.remove(k);
2511 assert_eq!(None, map.get(k));
2512 assert_eq!(l - 1, map.len());
2513 }
2514 }
2515
2516 #[test]
2517 fn delete_and_reinsert(
2518 ref input in collection::hash_map(i16::ANY, i16::ANY, 1..1000),
2519 index_rand in usize::ANY
2520 ) {
2521 let index = *input.keys().nth(index_rand % input.len()).unwrap();
2522 let map1: HashMap<_, _> = HashMap::from_iter(input.clone());
2523 let (val, map2) = map1.extract(&index).unwrap();
2524 let map3 = map2.update(index, val);
2525 for key in map2.keys() {
2526 assert!(*key != index);
2527 }
2528 assert_eq!(map1.len(), map2.len() + 1);
2529 assert_eq!(map1, map3);
2530 }
2531
2532 #[test]
2533 fn proptest_works(ref m in proptest::hash_map(0..9999, ".*", 10..100)) {
2534 assert!(m.len() < 100);
2535 assert!(m.len() >= 10);
2536 }
2537
2538 #[test]
2539 fn exact_size_iterator(ref m in proptest::hash_map(i16::ANY, i16::ANY, 0..100)) {
2540 let mut should_be = m.len();
2541 let mut it = m.iter();
2542 loop {
2543 assert_eq!(should_be, it.len());
2544 match it.next() {
2545 None => break,
2546 Some(_) => should_be -= 1,
2547 }
2548 }
2549 assert_eq!(0, it.len());
2550 }
2551
2552 #[test]
2553 fn union(ref m1 in collection::hash_map(i16::ANY, i16::ANY, 0..100),
2554 ref m2 in collection::hash_map(i16::ANY, i16::ANY, 0..100)) {
2555 let map1: HashMap<i16, i16> = FromIterator::from_iter(m1.iter().map(|(k, v)| (*k, *v)));
2556 let map2: HashMap<i16, i16> = FromIterator::from_iter(m2.iter().map(|(k, v)| (*k, *v)));
2557 let union_map = map1.union(map2);
2558
2559 for k in m1.keys() {
2560 assert!(union_map.contains_key(k));
2561 }
2562
2563 for k in m2.keys() {
2564 assert!(union_map.contains_key(k));
2565 }
2566
2567 for (k, v) in union_map.iter() {
2568 assert_eq!(v, m1.get(k).or_else(|| m2.get(k)).unwrap());
2569 }
2570 }
2571 }
2572
2573 #[test]
2574 fn test_structure_summary() {
2575 let sizes = vec![10, 100, 1_000, 10_000, 100_000];
2577
2578 for size in sizes {
2579 println!("\n=== Testing with {} entries ===", size);
2580
2581 let mut map = HashMap::new();
2582
2583 for i in 0..size {
2585 map.insert(i, i * 2);
2587 }
2588
2589 map.print_structure_summary();
2591 }
2592 }
2593}