1pub use self::Entry::*;
14use self::TrieNode::*;
15
16use std::cmp::Ordering;
17use std::fmt::{self, Debug};
18use std::hash::{Hash, Hasher};
19use std::iter;
20use std::marker::PhantomData;
21use std::mem;
22use std::ops;
23use std::ptr;
24use std::slice;
25
26#[cfg(target_pointer_width = "32")]
27pub const USIZE_BITS: usize = 32;
28
29#[cfg(target_pointer_width = "64")]
30pub const USIZE_BITS: usize = 64;
31
32const SHIFT: usize = 4;
38const SIZE: usize = 1 << SHIFT;
39const MASK: usize = SIZE - 1;
40const MAX_DEPTH: usize = USIZE_BITS / SHIFT;
42
43#[derive(Clone)]
92pub struct Map<T> {
93 root: InternalNode<T>,
94 length: usize,
95}
96
97struct InternalNode<T> {
102 count: usize,
104 children: [TrieNode<T>; SIZE],
105}
106
107#[derive(Clone)]
110enum TrieNode<T> {
111 Internal(Box<InternalNode<T>>),
112 External(usize, T),
113 Nothing,
114}
115
116impl<T: PartialEq> PartialEq for Map<T> {
117 fn eq(&self, other: &Map<T>) -> bool {
118 self.len() == other.len() && self.iter().zip(other.iter()).all(|(a, b)| a == b)
119 }
120}
121
122impl<T: Eq> Eq for Map<T> {}
123
124impl<T: PartialOrd> PartialOrd for Map<T> {
125 #[inline]
126 fn partial_cmp(&self, other: &Map<T>) -> Option<Ordering> {
127 self.iter().partial_cmp(other.iter())
128 }
129}
130
131impl<T: Ord> Ord for Map<T> {
132 #[inline]
133 fn cmp(&self, other: &Map<T>) -> Ordering {
134 self.iter().cmp(other.iter())
135 }
136}
137
138impl<T: Debug> Debug for Map<T> {
139 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
140 f.debug_map().entries(self.iter()).finish()
141 }
142}
143
144impl<T> Default for Map<T> {
145 #[inline]
146 fn default() -> Map<T> {
147 Map::new()
148 }
149}
150
151impl<T> Map<T> {
152 #[inline]
160 pub fn new() -> Map<T> {
161 Map {
162 root: InternalNode::new(),
163 length: 0,
164 }
165 }
166
167 #[inline]
185 pub fn each_reverse<'a, F>(&'a self, mut f: F) -> bool
186 where
187 F: FnMut(&usize, &'a T) -> bool,
188 {
189 self.root.each_reverse(&mut f)
190 }
191
192 pub fn keys(&self) -> Keys<'_, T> {
195 Keys(self.iter())
196 }
197
198 pub fn values(&self) -> Values<'_, T> {
201 Values(self.iter())
202 }
203
204 pub fn iter(&self) -> Iter<'_, T> {
216 let mut iter = unsafe { Iter::new() };
217 iter.stack[0] = self.root.children.iter();
218 iter.length = 1;
219 iter.remaining = self.length;
220
221 iter
222 }
223
224 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
241 let mut iter = unsafe { IterMut::new() };
242 iter.stack[0] = self.root.children.iter_mut();
243 iter.length = 1;
244 iter.remaining = self.length;
245
246 iter
247 }
248
249 #[inline]
260 pub fn len(&self) -> usize {
261 self.length
262 }
263
264 #[inline]
275 pub fn is_empty(&self) -> bool {
276 self.len() == 0
277 }
278
279 #[inline]
290 pub fn clear(&mut self) {
291 self.root = InternalNode::new();
292 self.length = 0;
293 }
294
295 #[inline]
306 pub fn get(&self, key: &usize) -> Option<&T> {
307 let mut node = &self.root;
308 let mut idx = 0;
309 loop {
310 match node.children[chunk(*key, idx)] {
311 Internal(ref x) => node = &**x,
312 External(stored, ref value) => {
313 if stored == *key {
314 return Some(value);
315 } else {
316 return None;
317 }
318 }
319 Nothing => return None,
320 }
321 idx += 1;
322 }
323 }
324
325 #[inline]
336 pub fn contains_key(&self, key: &usize) -> bool {
337 self.get(key).is_some()
338 }
339
340 #[inline]
354 pub fn get_mut(&mut self, key: &usize) -> Option<&mut T> {
355 find_mut(&mut self.root.children[chunk(*key, 0)], *key, 1)
356 }
357
358 pub fn insert(&mut self, key: usize, value: T) -> Option<T> {
373 let (_, old_val) = insert(
374 &mut self.root.count,
375 &mut self.root.children[chunk(key, 0)],
376 key,
377 value,
378 1,
379 );
380 if old_val.is_none() {
381 self.length += 1
382 }
383 old_val
384 }
385
386 pub fn remove(&mut self, key: &usize) -> Option<T> {
398 let ret = remove(
399 &mut self.root.count,
400 &mut self.root.children[chunk(*key, 0)],
401 *key,
402 1,
403 );
404 if ret.is_some() {
405 self.length -= 1
406 }
407 ret
408 }
409}
410
411macro_rules! bound {
412 (
413 $iterator_name:ident,
414 self = $this:expr,
416 key = $key:expr,
418 is_upper = $upper:expr,
420
421 iter = $iter:ident,
423
424 mutability = ($($mut_:tt)*),
426 const = ($($const_:tt)*)
427 ) => {
428 {
429 let this = $this;
440 let mut node = & $($mut_)* this.root as *$($mut_)* $($const_)* InternalNode<T>;
441
442 let key = $key;
443
444 let mut it = unsafe {$iterator_name::new()};
445 it.remaining = this.length;
447
448 loop {
450 let children = unsafe { & $($mut_)* (*node).children };
451 let child_id = chunk(key, it.length);
454 let (slice_idx, ret) = match & $($mut_)* children[child_id] {
455 & $($mut_)* Internal(ref $($mut_)* n) => {
456 node = (& $($mut_)* **n) as *$($mut_)* $($const_)* _;
457 (child_id + 1, false)
458 }
459 & $($mut_)* External(stored, _) => {
460 (if stored < key || ($upper && stored == key) {
461 child_id + 1
462 } else {
463 child_id
464 }, true)
465 }
466 & $($mut_)* Nothing => {
467 (child_id + 1, true)
468 }
469 };
470 it.stack[it.length] = children[slice_idx..].$iter();
472 it.length += 1;
473 if ret { break }
474 }
475
476 it
477 }
478 }
479}
480
481impl<T> Map<T> {
482 #[inline]
484 fn bound(&self, key: usize, upper: bool) -> Range<'_, T> {
485 Range(bound!(Iter, self = self,
486 key = key, is_upper = upper,
487 iter = iter,
488 mutability = (), const = (const)))
489 }
490
491 pub fn lower_bound(&self, key: usize) -> Range<'_, T> {
504 self.bound(key, false)
505 }
506
507 pub fn upper_bound(&self, key: usize) -> Range<'_, T> {
520 self.bound(key, true)
521 }
522 #[inline]
524 fn bound_mut(&mut self, key: usize, upper: bool) -> RangeMut<'_, T> {
525 RangeMut(bound!(IterMut, self = self,
526 key = key, is_upper = upper,
527 iter = iter_mut,
528 mutability = (mut), const = ()))
529 }
530
531 pub fn lower_bound_mut(&mut self, key: usize) -> RangeMut<'_, T> {
552 self.bound_mut(key, false)
553 }
554
555 pub fn upper_bound_mut(&mut self, key: usize) -> RangeMut<'_, T> {
576 self.bound_mut(key, true)
577 }
578}
579
580impl<T> iter::FromIterator<(usize, T)> for Map<T> {
581 fn from_iter<I: IntoIterator<Item = (usize, T)>>(iter: I) -> Map<T> {
582 let mut map = Map::new();
583 map.extend(iter);
584 map
585 }
586}
587
588impl<T> Extend<(usize, T)> for Map<T> {
589 fn extend<I: IntoIterator<Item = (usize, T)>>(&mut self, iter: I) {
590 for (k, v) in iter {
591 self.insert(k, v);
592 }
593 }
594}
595
596impl<T: Hash> Hash for Map<T> {
597 fn hash<H: Hasher>(&self, state: &mut H) {
598 for elt in self.iter() {
599 elt.hash(state);
600 }
601 }
602}
603
604impl<'a, T> ops::Index<&'a usize> for Map<T> {
605 type Output = T;
606 #[inline]
607 fn index(&self, i: &'a usize) -> &T {
608 self.get(i).expect("key not present")
609 }
610}
611
612impl<'a, T> ops::IndexMut<&'a usize> for Map<T> {
613 #[inline]
614 fn index_mut(&mut self, i: &'a usize) -> &mut T {
615 self.get_mut(i).expect("key not present")
616 }
617}
618
619impl<T: Clone> Clone for InternalNode<T> {
620 #[inline]
621 fn clone(&self) -> InternalNode<T> {
622 let ch = &self.children;
623 InternalNode {
624 count: self.count,
625 children: [
626 ch[0].clone(),
627 ch[1].clone(),
628 ch[2].clone(),
629 ch[3].clone(),
630 ch[4].clone(),
631 ch[5].clone(),
632 ch[6].clone(),
633 ch[7].clone(),
634 ch[8].clone(),
635 ch[9].clone(),
636 ch[10].clone(),
637 ch[11].clone(),
638 ch[12].clone(),
639 ch[13].clone(),
640 ch[14].clone(),
641 ch[15].clone(),
642 ],
643 }
644 }
645}
646
647impl<T> InternalNode<T> {
648 #[inline]
649 fn new() -> InternalNode<T> {
650 InternalNode {
653 count: 0,
654 children: [
655 Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing,
656 Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing,
657 ],
658 }
659 }
660}
661
662impl<T> InternalNode<T> {
663 fn each_reverse<'a, F>(&'a self, f: &mut F) -> bool
664 where
665 F: FnMut(&usize, &'a T) -> bool,
666 {
667 for elt in self.children.iter().rev() {
668 match *elt {
669 Internal(ref x) => {
670 if !x.each_reverse(f) {
671 return false;
672 }
673 }
674 External(k, ref v) => {
675 if !f(&k, v) {
676 return false;
677 }
678 }
679 Nothing => (),
680 }
681 }
682 true
683 }
684}
685
686#[inline]
688fn chunk(n: usize, idx: usize) -> usize {
689 let sh = USIZE_BITS - (SHIFT * (idx + 1));
690 (n >> sh) & MASK
691}
692
693fn find_mut<T>(child: &mut TrieNode<T>, key: usize, idx: usize) -> Option<&mut T> {
694 match *child {
695 External(stored, ref mut value) if stored == key => Some(value),
696 External(..) => None,
697 Internal(ref mut x) => find_mut(&mut x.children[chunk(key, idx)], key, idx + 1),
698 Nothing => None,
699 }
700}
701
702fn insert<'a, T>(
712 count: &mut usize,
713 start_node: &'a mut TrieNode<T>,
714 key: usize,
715 value: T,
716 idx: usize,
717) -> (&'a mut T, Option<T>) {
718 let mut hack = false;
723 match *start_node {
724 Nothing => {
725 *count += 1;
726 *start_node = External(key, value);
727 match *start_node {
728 External(_, ref mut value_ref) => return (value_ref, None),
729 _ => unreachable!(),
730 }
731 }
732 Internal(ref mut x) => {
733 let x = &mut **x;
734 return insert(
735 &mut x.count,
736 &mut x.children[chunk(key, idx)],
737 key,
738 value,
739 idx + 1,
740 );
741 }
742 External(stored_key, _) if stored_key == key => {
743 hack = true;
744 }
745 _ => {}
746 }
747
748 if !hack {
749 match mem::replace(start_node, Internal(Box::new(InternalNode::new()))) {
752 External(stored_key, stored_value) => {
753 match *start_node {
754 Internal(ref mut new_node) => {
755 let new_node = &mut **new_node;
756 insert(
758 &mut new_node.count,
759 &mut new_node.children[chunk(stored_key, idx)],
760 stored_key,
761 stored_value,
762 idx + 1,
763 );
764
765 return insert(
767 &mut new_node.count,
768 &mut new_node.children[chunk(key, idx)],
769 key,
770 value,
771 idx + 1,
772 );
773 }
774 _ => unreachable!(),
776 }
777 }
778 _ => unreachable!(),
780 }
781 }
782
783 if let External(_, ref mut stored_value) = *start_node {
784 let old_value = mem::replace(stored_value, value);
786 return (stored_value, Some(old_value));
787 }
788
789 unreachable!();
790}
791
792fn remove<T>(count: &mut usize, child: &mut TrieNode<T>, key: usize, idx: usize) -> Option<T> {
793 let (ret, this) = match *child {
794 External(stored, _) if stored == key => match mem::replace(child, Nothing) {
795 External(_, value) => (Some(value), true),
796 _ => unreachable!(),
797 },
798 External(..) => (None, false),
799 Internal(ref mut x) => {
800 let x = &mut **x;
801 let ret = remove(&mut x.count, &mut x.children[chunk(key, idx)], key, idx + 1);
802 (ret, x.count == 0)
803 }
804 Nothing => (None, false),
805 };
806
807 if this {
808 *child = Nothing;
809 *count -= 1;
810 }
811 ret
812}
813
814pub enum Entry<'a, T: 'a> {
816 Occupied(OccupiedEntry<'a, T>),
818 Vacant(VacantEntry<'a, T>),
820}
821
822impl<'a, T> Entry<'a, T> {
823 pub fn or_insert(self, default: T) -> &'a mut T {
826 match self {
827 Occupied(entry) => entry.into_mut(),
828 Vacant(entry) => entry.insert(default),
829 }
830 }
831
832 pub fn or_insert_with<F: FnOnce() -> T>(self, default: F) -> &'a mut T {
835 match self {
836 Occupied(entry) => entry.into_mut(),
837 Vacant(entry) => entry.insert(default()),
838 }
839 }
840}
841
842pub struct OccupiedEntry<'a, T: 'a> {
844 search_stack: SearchStack<'a, T>,
845}
846
847pub struct VacantEntry<'a, T: 'a> {
849 search_stack: SearchStack<'a, T>,
850}
851
852struct SearchStack<'a, T: 'a> {
862 map: *mut Map<T>,
863 length: usize,
864 key: usize,
865 items: [*mut TrieNode<T>; MAX_DEPTH],
866 phantom: PhantomData<&'a mut Map<T>>,
867}
868
869impl<'a, T> SearchStack<'a, T> {
870 fn new(map: &'a mut Map<T>, key: usize) -> SearchStack<'a, T> {
872 SearchStack {
873 map,
874 length: 0,
875 key,
876 items: [ptr::null_mut(); MAX_DEPTH],
877 phantom: PhantomData,
878 }
879 }
880
881 fn push(&mut self, node: *mut TrieNode<T>) {
882 self.length += 1;
883 self.items[self.length - 1] = node;
884 }
885
886 fn peek(&self) -> *mut TrieNode<T> {
887 self.items[self.length - 1]
888 }
889
890 fn peek_ref(&self) -> &'a mut TrieNode<T> {
891 let item = self.items[self.length - 1];
892 unsafe { &mut *item }
893 }
894
895 fn pop_ref(&mut self) -> &'a mut TrieNode<T> {
896 self.length -= 1;
897 unsafe { &mut *self.items[self.length] }
898 }
899
900 fn is_empty(&self) -> bool {
901 self.length == 0
902 }
903
904 fn get_ref(&self, idx: usize) -> &'a mut TrieNode<T> {
905 assert!(idx < self.length);
906 unsafe { &mut *self.items[idx] }
907 }
908}
909
910impl<T> Map<T> {
913 #[inline]
915 pub fn entry(&mut self, key: usize) -> Entry<'_, T> {
916 let mut search_stack = SearchStack::new(self, key);
918
919 let first_node =
921 unsafe { (&mut (*search_stack.map).root.children[chunk(key, 0)]) as *mut _ };
922 search_stack.push(first_node);
923
924 let search_successful: bool;
927 loop {
928 match unsafe { next_child(search_stack.peek(), key, search_stack.length) } {
929 (Some(child), _) => search_stack.push(child),
930 (None, success) => {
931 search_successful = success;
932 break;
933 }
934 }
935 }
936
937 if search_successful {
938 Occupied(OccupiedEntry { search_stack })
939 } else {
940 Vacant(VacantEntry { search_stack })
941 }
942 }
943}
944
945#[inline]
955unsafe fn next_child<T>(
956 node: *mut TrieNode<T>,
957 key: usize,
958 idx: usize,
959) -> (Option<*mut TrieNode<T>>, bool) {
960 match unsafe { &mut *node } {
961 &mut Internal(ref mut node_internal) => (
963 Some(&mut node_internal.children[chunk(key, idx)] as *mut _),
964 false,
965 ),
966 External(stored_key, _) if *stored_key == key => (None, true),
970 External(..) | Nothing => (None, false),
971 }
972}
973
974impl<'a, T> OccupiedEntry<'a, T> {
976 #[inline]
978 pub fn get(&self) -> &T {
979 match *self.search_stack.peek_ref() {
980 External(_, ref value) => value,
981 _ => unreachable!(),
983 }
984 }
985
986 #[inline]
988 pub fn get_mut(&mut self) -> &mut T {
989 match *self.search_stack.peek_ref() {
990 External(_, ref mut value) => value,
991 _ => unreachable!(),
993 }
994 }
995
996 #[inline]
999 pub fn into_mut(self) -> &'a mut T {
1000 match *self.search_stack.peek_ref() {
1001 External(_, ref mut value) => value,
1002 _ => unreachable!(),
1004 }
1005 }
1006
1007 #[inline]
1009 pub fn insert(&mut self, value: T) -> T {
1010 match *self.search_stack.peek_ref() {
1011 External(_, ref mut stored_value) => mem::replace(stored_value, value),
1012 _ => unreachable!(),
1014 }
1015 }
1016
1017 #[inline]
1019 pub fn remove(self) -> T {
1020 let mut search_stack = self.search_stack;
1023
1024 let leaf_node = mem::replace(search_stack.pop_ref(), Nothing);
1026
1027 let value = match leaf_node {
1028 External(_, value) => value,
1029 _ => unreachable!(),
1031 };
1032
1033 while !search_stack.is_empty() {
1037 let ancestor = search_stack.pop_ref();
1038 match *ancestor {
1039 Internal(ref mut internal) => {
1040 if internal.count != 1 {
1042 internal.count -= 1;
1043 break;
1044 }
1045 }
1046 _ => unreachable!(),
1048 }
1049 *ancestor = Nothing;
1050 }
1051
1052 unsafe {
1054 (*search_stack.map).length -= 1;
1055 }
1056
1057 value
1058 }
1059}
1060
1061impl<'a, T> VacantEntry<'a, T> {
1062 pub fn insert(self, value: T) -> &'a mut T {
1064 let search_stack = self.search_stack;
1065 let old_length = search_stack.length;
1066 let key = search_stack.key;
1067
1068 unsafe {
1070 (*search_stack.map).length += 1;
1071 }
1072
1073 if old_length == 1 {
1075 unsafe {
1076 let mut temp = (*search_stack.map).root.count;
1078 let (value_ref, _) = insert(&mut temp, search_stack.get_ref(0), key, value, 1);
1079 (*search_stack.map).root.count = temp;
1080 value_ref
1081 }
1082 }
1083 else {
1085 match *search_stack.get_ref(old_length - 2) {
1086 Internal(ref mut parent) => {
1087 let parent = &mut **parent;
1088 let (value_ref, _) = insert(
1089 &mut parent.count,
1090 &mut parent.children[chunk(key, old_length - 1)],
1091 key,
1092 value,
1093 old_length,
1094 );
1095 value_ref
1096 }
1097 _ => unreachable!(),
1099 }
1100 }
1101 }
1102}
1103
1104pub struct Iter<'a, T: 'a> {
1106 stack: [slice::Iter<'a, TrieNode<T>>; MAX_DEPTH],
1107 length: usize,
1108 remaining: usize,
1109}
1110
1111impl<'a, T> Clone for Iter<'a, T> {
1112 #[cfg(target_pointer_width = "32")]
1113 fn clone(&self) -> Iter<'a, T> {
1114 Iter {
1115 stack: [
1116 self.stack[0].clone(),
1117 self.stack[1].clone(),
1118 self.stack[2].clone(),
1119 self.stack[3].clone(),
1120 self.stack[4].clone(),
1121 self.stack[5].clone(),
1122 self.stack[6].clone(),
1123 self.stack[7].clone(),
1124 ],
1125 ..*self
1126 }
1127 }
1128
1129 #[cfg(target_pointer_width = "64")]
1130 fn clone(&self) -> Iter<'a, T> {
1131 Iter {
1132 stack: [
1133 self.stack[0].clone(),
1134 self.stack[1].clone(),
1135 self.stack[2].clone(),
1136 self.stack[3].clone(),
1137 self.stack[4].clone(),
1138 self.stack[5].clone(),
1139 self.stack[6].clone(),
1140 self.stack[7].clone(),
1141 self.stack[8].clone(),
1142 self.stack[9].clone(),
1143 self.stack[10].clone(),
1144 self.stack[11].clone(),
1145 self.stack[12].clone(),
1146 self.stack[13].clone(),
1147 self.stack[14].clone(),
1148 self.stack[15].clone(),
1149 ],
1150 ..*self
1151 }
1152 }
1153}
1154
1155pub struct IterMut<'a, T: 'a> {
1158 stack: [slice::IterMut<'a, TrieNode<T>>; MAX_DEPTH],
1159 length: usize,
1160 remaining: usize,
1161}
1162
1163pub struct Keys<'a, T: 'a>(Iter<'a, T>);
1165
1166impl<'a, T> Clone for Keys<'a, T> {
1167 fn clone(&self) -> Keys<'a, T> {
1168 Keys(self.0.clone())
1169 }
1170}
1171
1172impl<'a, T> Iterator for Keys<'a, T> {
1173 type Item = usize;
1174 fn next(&mut self) -> Option<usize> {
1175 self.0.next().map(|e| e.0)
1176 }
1177 fn size_hint(&self) -> (usize, Option<usize>) {
1178 self.0.size_hint()
1179 }
1180}
1181
1182impl<'a, T> ExactSizeIterator for Keys<'a, T> {}
1183
1184pub struct Values<'a, T: 'a>(Iter<'a, T>);
1186
1187impl<'a, T> Clone for Values<'a, T> {
1188 fn clone(&self) -> Values<'a, T> {
1189 Values(self.0.clone())
1190 }
1191}
1192
1193impl<'a, T> Iterator for Values<'a, T> {
1194 type Item = &'a T;
1195 fn next(&mut self) -> Option<&'a T> {
1196 self.0.next().map(|e| e.1)
1197 }
1198 fn size_hint(&self) -> (usize, Option<usize>) {
1199 self.0.size_hint()
1200 }
1201}
1202
1203impl<'a, T> ExactSizeIterator for Values<'a, T> {}
1204
1205macro_rules! iterator_impl {
1206 ($name:ident,
1207 iter = $iter:ident,
1208 mutability = $($mut_:tt)*) => {
1209 impl<'a, T> $name<'a, T> {
1210 #[cfg(target_pointer_width="32")]
1215 unsafe fn new() -> $name<'a, T> {
1216 $name {
1217 remaining: 0,
1218 length: 0,
1219 stack: [IntoIterator::into_iter((& $($mut_)*[])),
1221 IntoIterator::into_iter((& $($mut_)*[])),
1222 IntoIterator::into_iter((& $($mut_)*[])),
1223 IntoIterator::into_iter((& $($mut_)*[])),
1224
1225 IntoIterator::into_iter((& $($mut_)*[])),
1226 IntoIterator::into_iter((& $($mut_)*[])),
1227 IntoIterator::into_iter((& $($mut_)*[])),
1228 IntoIterator::into_iter((& $($mut_)*[])),
1229 ]
1230 }
1231 }
1232
1233 #[cfg(target_pointer_width="64")]
1234 unsafe fn new() -> $name<'a, T> {
1235 $name {
1236 remaining: 0,
1237 length: 0,
1238 stack: [IntoIterator::into_iter(& $($mut_)*[]),
1239 IntoIterator::into_iter(& $($mut_)*[]),
1240 IntoIterator::into_iter(& $($mut_)*[]),
1241 IntoIterator::into_iter(& $($mut_)*[]),
1242
1243 IntoIterator::into_iter(& $($mut_)*[]),
1244 IntoIterator::into_iter(& $($mut_)*[]),
1245 IntoIterator::into_iter(& $($mut_)*[]),
1246 IntoIterator::into_iter(& $($mut_)*[]),
1247
1248 IntoIterator::into_iter(& $($mut_)*[]),
1249 IntoIterator::into_iter(& $($mut_)*[]),
1250 IntoIterator::into_iter(& $($mut_)*[]),
1251 IntoIterator::into_iter(& $($mut_)*[]),
1252
1253 IntoIterator::into_iter(& $($mut_)*[]),
1254 IntoIterator::into_iter(& $($mut_)*[]),
1255 IntoIterator::into_iter(& $($mut_)*[]),
1256 IntoIterator::into_iter(& $($mut_)*[]),
1257 ]
1258 }
1259 }
1260 }
1261
1262 impl<'a, T> Iterator for $name<'a, T> {
1263 type Item = (usize, &'a $($mut_)* T);
1264 fn next(&mut self) -> Option<(usize, &'a $($mut_)* T)> {
1281 let start_ptr = self.stack.as_mut_ptr();
1282
1283 unsafe {
1284 let mut write_ptr = start_ptr.offset(self.length as isize);
1288 while write_ptr != start_ptr {
1289 match (*write_ptr.offset(-1)).next() {
1292 None => write_ptr = write_ptr.offset(-1),
1299 Some(child) => {
1300 match *child {
1301 Internal(ref $($mut_)* node) => {
1302 *write_ptr = node.children.$iter();
1306 write_ptr = write_ptr.offset(1);
1307 }
1308 External(key, ref $($mut_)* value) => {
1309 self.remaining -= 1;
1310 self.length = (write_ptr as usize
1314 - start_ptr as usize) /
1315 mem::size_of::<slice::Iter<'_, TrieNode<T>>>();
1316
1317 return Some((key, value));
1318 }
1319 Nothing => {}
1320 }
1321 }
1322 }
1323 }
1324 }
1325 return None;
1326 }
1327
1328 #[inline]
1329 fn size_hint(&self) -> (usize, Option<usize>) {
1330 (self.remaining, Some(self.remaining))
1331 }
1332 }
1333
1334 impl<'a, T> ExactSizeIterator for $name<'a, T> {
1335 fn len(&self) -> usize { self.remaining }
1336 }
1337 }
1338}
1339
1340iterator_impl! { Iter, iter = iter, mutability = }
1341iterator_impl! { IterMut, iter = iter_mut, mutability = mut }
1342
1343pub struct Range<'a, T: 'a>(Iter<'a, T>);
1345
1346impl<'a, T> Clone for Range<'a, T> {
1347 fn clone(&self) -> Range<'a, T> {
1348 Range(self.0.clone())
1349 }
1350}
1351
1352impl<'a, T> Iterator for Range<'a, T> {
1353 type Item = (usize, &'a T);
1354 fn next(&mut self) -> Option<(usize, &'a T)> {
1355 self.0.next()
1356 }
1357 fn size_hint(&self) -> (usize, Option<usize>) {
1358 (0, Some(self.0.remaining))
1359 }
1360}
1361
1362pub struct RangeMut<'a, T: 'a>(IterMut<'a, T>);
1365
1366impl<'a, T> Iterator for RangeMut<'a, T> {
1367 type Item = (usize, &'a mut T);
1368 fn next(&mut self) -> Option<(usize, &'a mut T)> {
1369 self.0.next()
1370 }
1371 fn size_hint(&self) -> (usize, Option<usize>) {
1372 (0, Some(self.0.remaining))
1373 }
1374}
1375
1376impl<'a, T> IntoIterator for &'a Map<T> {
1377 type Item = (usize, &'a T);
1378 type IntoIter = Iter<'a, T>;
1379 fn into_iter(self) -> Iter<'a, T> {
1380 self.iter()
1381 }
1382}
1383
1384impl<'a, T> IntoIterator for &'a mut Map<T> {
1385 type Item = (usize, &'a mut T);
1386 type IntoIter = IterMut<'a, T>;
1387 fn into_iter(self) -> IterMut<'a, T> {
1388 self.iter_mut()
1389 }
1390}
1391
1392#[cfg(test)]
1393mod test {
1394 use std::collections::hash_map::DefaultHasher;
1395 use std::hash::{Hash, Hasher};
1396 use std::hint::black_box;
1397
1398 use super::Entry::*;
1399 use super::TrieNode::*;
1400 use super::{InternalNode, Map};
1401
1402 fn check_integrity<T>(trie: &InternalNode<T>) {
1403 assert!(trie.count != 0);
1404
1405 let mut sum = 0;
1406
1407 for x in trie.children.iter() {
1408 match *x {
1409 Nothing => (),
1410 Internal(ref y) => {
1411 check_integrity(&**y);
1412 sum += 1
1413 }
1414 External(_, _) => sum += 1,
1415 }
1416 }
1417
1418 assert_eq!(sum, trie.count);
1419 }
1420
1421 #[test]
1422 fn test_find_mut() {
1423 let mut m = Map::new();
1424 assert!(m.insert(1, 12).is_none());
1425 assert!(m.insert(2, 8).is_none());
1426 assert!(m.insert(5, 14).is_none());
1427 let new = 100;
1428 match m.get_mut(&5) {
1429 None => panic!(),
1430 Some(x) => *x = new,
1431 }
1432 assert_eq!(m.get(&5), Some(&new));
1433 }
1434
1435 #[test]
1436 fn test_find_mut_missing() {
1437 let mut m = Map::new();
1438 assert!(m.get_mut(&0).is_none());
1439 assert!(m.insert(1, 12).is_none());
1440 assert!(m.get_mut(&0).is_none());
1441 assert!(m.insert(2, 8).is_none());
1442 assert!(m.get_mut(&0).is_none());
1443 }
1444
1445 #[test]
1446 fn test_step() {
1447 let mut trie = Map::new();
1448 let n = 300;
1449
1450 for x in (1..n).step_by(2) {
1451 assert!(trie.insert(x, x + 1).is_none());
1452 assert!(trie.contains_key(&x));
1453 check_integrity(&trie.root);
1454 }
1455
1456 for x in (0..n).step_by(2) {
1457 assert!(!trie.contains_key(&x));
1458 assert!(trie.insert(x, x + 1).is_none());
1459 check_integrity(&trie.root);
1460 }
1461
1462 for x in 0..n {
1463 assert!(trie.contains_key(&x));
1464 assert!(trie.insert(x, x + 1).is_some());
1465 check_integrity(&trie.root);
1466 }
1467
1468 for x in (1..n).step_by(2) {
1469 assert!(trie.remove(&x).is_some());
1470 assert!(!trie.contains_key(&x));
1471 check_integrity(&trie.root);
1472 }
1473
1474 for x in (0..n).step_by(2) {
1475 assert!(trie.contains_key(&x));
1476 assert!(trie.insert(x, x + 1).is_some());
1477 check_integrity(&trie.root);
1478 }
1479 }
1480
1481 #[test]
1482 fn test_each_reverse() {
1483 let mut m = Map::new();
1484
1485 assert!(m.insert(3, 6).is_none());
1486 assert!(m.insert(0, 0).is_none());
1487 assert!(m.insert(4, 8).is_none());
1488 assert!(m.insert(2, 4).is_none());
1489 assert!(m.insert(1, 2).is_none());
1490
1491 let mut n = 5;
1492 let mut vec: Vec<&i32> = vec![];
1493 m.each_reverse(|k, v| {
1494 n -= 1;
1495 assert_eq!(*k, n);
1496 vec.push(v);
1497 true
1498 });
1499 assert_eq!(vec, [&8, &6, &4, &2, &0]);
1500 }
1501
1502 #[test]
1503 fn test_each_reverse_break() {
1504 let mut m = Map::new();
1505
1506 for x in (usize::MAX - 10000..usize::MAX).rev() {
1507 m.insert(x, x / 2);
1508 }
1509
1510 let mut n = usize::MAX - 1;
1511 m.each_reverse(|k, v| {
1512 if n == usize::MAX - 5000 {
1513 false
1514 } else {
1515 assert!(n > usize::MAX - 5000);
1516
1517 assert_eq!(*k, n);
1518 assert_eq!(*v, n / 2);
1519 n -= 1;
1520 true
1521 }
1522 });
1523 }
1524
1525 #[test]
1526 fn test_insert() {
1527 let mut m = Map::new();
1528 assert_eq!(m.insert(1, 2), None);
1529 assert_eq!(m.insert(1, 3), Some(2));
1530 assert_eq!(m.insert(1, 4), Some(3));
1531 }
1532
1533 #[test]
1534 fn test_remove() {
1535 let mut m = Map::new();
1536 m.insert(1, 2);
1537 assert_eq!(m.remove(&1), Some(2));
1538 assert_eq!(m.remove(&1), None);
1539 }
1540
1541 #[test]
1542 fn test_from_iter() {
1543 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
1544
1545 let map: Map<i32> = xs.iter().cloned().collect();
1546
1547 for &(k, v) in xs.iter() {
1548 assert_eq!(map.get(&k), Some(&v));
1549 }
1550 }
1551
1552 #[test]
1553 fn test_keys() {
1554 let vec = [(1, 'a'), (2, 'b'), (3, 'c')];
1555 let map: Map<_> = vec.iter().cloned().collect();
1556 let keys: Vec<_> = map.keys().collect();
1557 assert_eq!(keys.len(), 3);
1558 assert!(keys.contains(&1));
1559 assert!(keys.contains(&2));
1560 assert!(keys.contains(&3));
1561 }
1562
1563 #[test]
1564 fn test_values() {
1565 let vec = [(1, 'a'), (2, 'b'), (3, 'c')];
1566 let map: Map<_> = vec.iter().cloned().collect();
1567 let values: Vec<_> = map.values().cloned().collect();
1568 assert_eq!(values.len(), 3);
1569 assert!(values.contains(&'a'));
1570 assert!(values.contains(&'b'));
1571 assert!(values.contains(&'c'));
1572 }
1573
1574 #[test]
1575 fn test_iteration() {
1576 let empty_map: Map<usize> = Map::new();
1577 assert_eq!(empty_map.iter().next(), None);
1578
1579 let first = usize::MAX - 10000;
1580 let last = usize::MAX;
1581
1582 let mut map = Map::new();
1583 for x in (first..last).rev() {
1584 map.insert(x, x / 2);
1585 }
1586
1587 let mut i = 0;
1588 for (k, &v) in map.iter() {
1589 assert_eq!(k, first + i);
1590 assert_eq!(v, k / 2);
1591 i += 1;
1592 }
1593 assert_eq!(i, last - first);
1594 }
1595
1596 #[test]
1597 fn test_mut_iter() {
1598 let mut empty_map: Map<usize> = Map::new();
1599 assert!(empty_map.iter_mut().next().is_none());
1600
1601 let first = usize::MAX - 10000;
1602 let last = usize::MAX;
1603
1604 let mut map = Map::new();
1605 for x in (first..last).rev() {
1606 map.insert(x, x / 2);
1607 }
1608
1609 let mut i = 0;
1610 for (k, v) in map.iter_mut() {
1611 assert_eq!(k, first + i);
1612 *v -= k / 2;
1613 i += 1;
1614 }
1615 assert_eq!(i, last - first);
1616
1617 assert!(map.iter().all(|(_, &v)| v == 0));
1618 }
1619
1620 #[test]
1621 fn test_bound() {
1622 let empty_map: Map<usize> = Map::new();
1623 assert_eq!(empty_map.lower_bound(0).next(), None);
1624 assert_eq!(empty_map.upper_bound(0).next(), None);
1625
1626 let last = 999;
1627 let step = 3;
1628 let value = 42;
1629
1630 let mut map: Map<usize> = Map::new();
1631 for x in (0..last).step_by(step) {
1632 assert!(x % step == 0);
1633 map.insert(x, value);
1634 }
1635
1636 for i in 0..last - step {
1637 let mut lb = map.lower_bound(i);
1638 let mut ub = map.upper_bound(i);
1639 let next_key = i - i % step + step;
1640 let next_pair = (next_key, &value);
1641 if i % step == 0 {
1642 assert_eq!(lb.next(), Some((i, &value)));
1643 } else {
1644 assert_eq!(lb.next(), Some(next_pair));
1645 }
1646 assert_eq!(ub.next(), Some(next_pair));
1647 }
1648
1649 let mut lb = map.lower_bound(last - step);
1650 assert_eq!(lb.next(), Some((last - step, &value)));
1651 let mut ub = map.upper_bound(last - step);
1652 assert_eq!(ub.next(), None);
1653
1654 for i in last - step + 1..last {
1655 let mut lb = map.lower_bound(i);
1656 assert_eq!(lb.next(), None);
1657 let mut ub = map.upper_bound(i);
1658 assert_eq!(ub.next(), None);
1659 }
1660 }
1661
1662 #[test]
1663 fn test_mut_bound() {
1664 let empty_map: Map<usize> = Map::new();
1665 assert_eq!(empty_map.lower_bound(0).next(), None);
1666 assert_eq!(empty_map.upper_bound(0).next(), None);
1667
1668 let mut m_lower = Map::new();
1669 let mut m_upper = Map::new();
1670 for i in 0..100 {
1671 m_lower.insert(2 * i, 4 * i);
1672 m_upper.insert(2 * i, 4 * i);
1673 }
1674
1675 for i in 0..199 {
1676 let mut lb_it = m_lower.lower_bound_mut(i);
1677 let (k, v) = lb_it.next().unwrap();
1678 let lb = i + i % 2;
1679 assert_eq!(lb, k);
1680 *v -= k;
1681 }
1682
1683 for i in 0..198 {
1684 let mut ub_it = m_upper.upper_bound_mut(i);
1685 let (k, v) = ub_it.next().unwrap();
1686 let ub = i + 2 - i % 2;
1687 assert_eq!(ub, k);
1688 *v -= k;
1689 }
1690
1691 assert!(m_lower.lower_bound_mut(199).next().is_none());
1692 assert!(m_upper.upper_bound_mut(198).next().is_none());
1693
1694 assert!(m_lower.iter().all(|(_, &x)| x == 0));
1695 assert!(m_upper.iter().all(|(_, &x)| x == 0));
1696 }
1697
1698 #[test]
1699 fn test_clone() {
1700 let mut a = Map::new();
1701
1702 a.insert(1, 'a');
1703 a.insert(2, 'b');
1704 a.insert(3, 'c');
1705
1706 assert!(a.clone() == a);
1707 }
1708
1709 #[test]
1710 fn test_eq() {
1711 let mut a = Map::new();
1712 let mut b = Map::new();
1713
1714 assert!(a == b);
1715 assert!(a.insert(0, 5).is_none());
1716 assert!(a != b);
1717 assert!(b.insert(0, 4).is_none());
1718 assert!(a != b);
1719 assert!(a.insert(5, 19).is_none());
1720 assert!(a != b);
1721 assert!(b.insert(0, 5).is_some());
1722 assert!(a != b);
1723 assert!(b.insert(5, 19).is_none());
1724 assert!(a == b);
1725 }
1726
1727 #[test]
1728 fn test_lt() {
1729 let mut a = Map::new();
1730 let mut b = Map::new();
1731
1732 assert!((a >= b) && (b >= a));
1733 assert!(b.insert(2, 5).is_none());
1734 assert!(a < b);
1735 assert!(a.insert(2, 7).is_none());
1736 assert!((a >= b) && b < a);
1737 assert!(b.insert(1, 0).is_none());
1738 assert!(b < a);
1739 assert!(a.insert(0, 6).is_none());
1740 assert!(a < b);
1741 assert!(a.insert(6, 2).is_none());
1742 assert!(a < b && (b >= a));
1743 }
1744
1745 #[test]
1746 fn test_ord() {
1747 let mut a = Map::new();
1748 let mut b = Map::new();
1749
1750 assert!(a == b);
1751 assert!(a.insert(1, 1).is_none());
1752 assert!(a > b && a >= b);
1753 assert!(b < a && b <= a);
1754 assert!(b.insert(2, 2).is_none());
1755 assert!(b > a && b >= a);
1756 assert!(a < b && a <= b);
1757 }
1758
1759 #[test]
1760 fn test_hash() {
1761 fn hash<T: Hash>(t: &T) -> u64 {
1762 let mut s = DefaultHasher::new();
1763 t.hash(&mut s);
1764 s.finish()
1765 }
1766
1767 let mut x = Map::new();
1768 let mut y = Map::new();
1769
1770 assert!(hash(&x) == hash(&y));
1771 x.insert(1, 'a');
1772 x.insert(2, 'b');
1773 x.insert(3, 'c');
1774
1775 y.insert(3, 'c');
1776 y.insert(2, 'b');
1777 y.insert(1, 'a');
1778
1779 assert!(hash(&x) == hash(&y));
1780 }
1781
1782 #[test]
1783 fn test_debug() {
1784 let mut map = Map::new();
1785 let empty: Map<char> = Map::new();
1786
1787 map.insert(1, 'a');
1788 map.insert(2, 'b');
1789
1790 assert_eq!(format!("{:?}", map), "{1: 'a', 2: 'b'}");
1791 assert_eq!(format!("{:?}", empty), "{}");
1792 }
1793
1794 #[test]
1795 fn test_index() {
1796 let mut map = Map::new();
1797
1798 map.insert(1, 2);
1799 map.insert(2, 1);
1800 map.insert(3, 4);
1801
1802 assert_eq!(map[&2], 1);
1803 }
1804
1805 #[test]
1806 #[should_panic]
1807 fn test_index_nonexistent() {
1808 let mut map = Map::new();
1809
1810 map.insert(1, 2);
1811 map.insert(2, 1);
1812 map.insert(3, 4);
1813
1814 black_box(map[&4]);
1815 }
1816
1817 const SQUARES_UPPER_LIM: usize = 128;
1820
1821 fn squares_map() -> Map<usize> {
1823 let mut map = Map::new();
1824 for i in 0..SQUARES_UPPER_LIM {
1825 map.insert(i, i * i);
1826 }
1827 map
1828 }
1829
1830 #[test]
1831 fn test_entry_get() {
1832 let mut map = squares_map();
1833
1834 for i in 0..SQUARES_UPPER_LIM {
1835 match map.entry(i) {
1836 Occupied(slot) => assert_eq!(slot.get(), &(i * i)),
1837 Vacant(_) => panic!("Key not found."),
1838 }
1839 }
1840 check_integrity(&map.root);
1841 }
1842
1843 #[test]
1844 fn test_entry_get_mut() {
1845 let mut map = squares_map();
1846
1847 for i in 0..SQUARES_UPPER_LIM {
1849 match map.entry(i) {
1850 Occupied(mut e) => {
1851 *e.get_mut() = i * i * i;
1852 }
1853 Vacant(_) => panic!("Key not found."),
1854 }
1855 assert_eq!(map.get(&i).unwrap(), &(i * i * i));
1856 }
1857
1858 check_integrity(&map.root);
1859 }
1860
1861 #[test]
1862 fn test_entry_into_mut() {
1863 let mut map = Map::new();
1864 map.insert(3, 6);
1865
1866 let value_ref = match map.entry(3) {
1867 Occupied(e) => e.into_mut(),
1868 Vacant(_) => panic!("Entry not found."),
1869 };
1870
1871 assert_eq!(*value_ref, 6);
1872 }
1873
1874 #[test]
1875 fn test_entry_take() {
1876 let mut map = squares_map();
1877 assert_eq!(map.len(), SQUARES_UPPER_LIM);
1878
1879 for i in (1..SQUARES_UPPER_LIM).step_by(2) {
1881 match map.entry(i) {
1882 Occupied(e) => assert_eq!(e.remove(), i * i),
1883 Vacant(_) => panic!("Key not found."),
1884 }
1885 }
1886
1887 check_integrity(&map.root);
1888
1889 for i in (0..SQUARES_UPPER_LIM).step_by(2) {
1891 assert_eq!(map.get(&i).unwrap(), &(i * i));
1892 }
1893
1894 assert_eq!(map.len(), SQUARES_UPPER_LIM / 2);
1895 }
1896
1897 #[test]
1898 fn test_occupied_entry_set() {
1899 let mut map = squares_map();
1900
1901 for i in 0..SQUARES_UPPER_LIM {
1903 match map.entry(i) {
1904 Occupied(mut e) => assert_eq!(e.insert(i * i * i), i * i),
1905 Vacant(_) => panic!("Key not found."),
1906 }
1907 assert_eq!(map.get(&i).unwrap(), &(i * i * i));
1908 }
1909 check_integrity(&map.root);
1910 }
1911
1912 #[test]
1913 fn test_vacant_entry_set() {
1914 let mut map = Map::new();
1915
1916 for i in 0..SQUARES_UPPER_LIM {
1917 match map.entry(i) {
1918 Vacant(e) => {
1919 let inserted_val = e.insert(i * i);
1921 assert_eq!(*inserted_val, i * i);
1922
1923 *inserted_val = i * i * i;
1925 }
1926 _ => panic!("Non-existent key found."),
1927 }
1928 assert_eq!(map.get(&i).unwrap(), &(i * i * i));
1929 }
1930
1931 check_integrity(&map.root);
1932 assert_eq!(map.len(), SQUARES_UPPER_LIM);
1933 }
1934
1935 #[test]
1936 fn test_single_key() {
1937 let mut map = Map::new();
1938 map.insert(1, 2);
1939
1940 if let Occupied(e) = map.entry(1) {
1941 e.remove();
1942 }
1943 }
1944}