1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Ordered containers with integer keys, implemented as radix tries (`TrieSet` and `TrieMap` types)
15 use alloc::boxed::Box;
16 use core::default::Default;
17 use core::mem::zeroed;
21 use {Collection, Mutable, Map, MutableMap, Set, MutableSet};
22 use slice::{Items, MutItems};
25 // FIXME: #5244: need to manually update the TrieNode constructor
26 static SHIFT: uint = 4;
27 static SIZE: uint = 1 << SHIFT;
28 static MASK: uint = SIZE - 1;
29 static NUM_CHUNKS: uint = uint::BITS / SHIFT;
32 Internal(Box<TrieNode<T>>),
38 pub struct TrieMap<T> {
43 impl<T> Collection for TrieMap<T> {
44 /// Return the number of elements in the map
46 fn len(&self) -> uint { self.length }
49 impl<T> Mutable for TrieMap<T> {
50 /// Clear the map, removing all values.
53 self.root = TrieNode::new();
58 impl<T> Map<uint, T> for TrieMap<T> {
59 /// Return a reference to the value corresponding to the key
61 fn find<'a>(&'a self, key: &uint) -> Option<&'a T> {
62 let mut node: &'a TrieNode<T> = &self.root;
65 match node.children[chunk(*key, idx)] {
66 Internal(ref x) => node = &**x,
67 External(stored, ref value) => {
74 Nothing => return None
81 impl<T> MutableMap<uint, T> for TrieMap<T> {
82 /// Return a mutable reference to the value corresponding to the key
84 fn find_mut<'a>(&'a mut self, key: &uint) -> Option<&'a mut T> {
85 find_mut(&mut self.root.children[chunk(*key, 0)], *key, 1)
88 /// Insert a key-value pair from the map. If the key already had a value
89 /// present in the map, that value is returned. Otherwise None is returned.
90 fn swap(&mut self, key: uint, value: T) -> Option<T> {
91 let ret = insert(&mut self.root.count,
92 &mut self.root.children[chunk(key, 0)],
94 if ret.is_none() { self.length += 1 }
98 /// Removes a key from the map, returning the value at the key if the key
99 /// was previously in the map.
100 fn pop(&mut self, key: &uint) -> Option<T> {
101 let ret = remove(&mut self.root.count,
102 &mut self.root.children[chunk(*key, 0)],
104 if ret.is_some() { self.length -= 1 }
109 impl<T> Default for TrieMap<T> {
111 fn default() -> TrieMap<T> { TrieMap::new() }
115 /// Create an empty TrieMap
117 pub fn new() -> TrieMap<T> {
118 TrieMap{root: TrieNode::new(), length: 0}
121 /// Visit all key-value pairs in reverse order
123 pub fn each_reverse<'a>(&'a self, f: |&uint, &'a T| -> bool) -> bool {
124 self.root.each_reverse(f)
127 /// Get an iterator over the key-value pairs in the map
128 pub fn iter<'a>(&'a self) -> Entries<'a, T> {
129 let mut iter = unsafe {Entries::new()};
130 iter.stack[0] = self.root.children.iter();
132 iter.remaining_min = self.length;
133 iter.remaining_max = self.length;
138 /// Get an iterator over the key-value pairs in the map, with the
139 /// ability to mutate the values.
140 pub fn mut_iter<'a>(&'a mut self) -> MutEntries<'a, T> {
141 let mut iter = unsafe {MutEntries::new()};
142 iter.stack[0] = self.root.children.mut_iter();
144 iter.remaining_min = self.length;
145 iter.remaining_max = self.length;
151 // FIXME #5846 we want to be able to choose between &x and &mut x
152 // (with many different `x`) below, so we need to optionally pass mut
153 // as a tt, but the only thing we can do with a `tt` is pass them to
154 // other macros, so this takes the `& <mutability> <operand>` token
155 // sequence and forces their evaluation as an expression. (see also
157 macro_rules! addr { ($e:expr) => { $e } }
160 ($iterator_name:ident,
161 // the current treemap
163 // the key to look for
165 // are we looking at the upper bound?
166 is_upper = $upper:expr,
168 // method names for slicing/iterating.
169 slice_from = $slice_from:ident,
172 // see the comment on `addr!`, this is just an optional mut, but
173 // there's no 0-or-1 repeats yet.
174 mutability = $($mut_:tt)*) => {
177 // We need an unsafe pointer here because we are borrowing
178 // mutable references to the internals of each of these
179 // mutable nodes, while still using the outer node.
181 // However, we're allowed to flaunt rustc like this because we
182 // never actually modify the "shape" of the nodes. The only
183 // place that mutation is can actually occur is of the actual
184 // values of the TrieMap (as the return value of the
185 // iterator), i.e. we can never cause a deallocation of any
186 // TrieNodes so the raw pointer is always valid.
189 // We like sharing code so much that even a little unsafe won't
192 let mut node = unsafe {
193 mem::transmute::<_, uint>(&this.root) as *mut TrieNode<T>
198 let mut it = unsafe {$iterator_name::new()};
199 // everything else is zero'd, as we want.
200 it.remaining_max = this.length;
202 // this addr is necessary for the `Internal` pattern.
204 let children = unsafe {addr!(& $($mut_)* (*node).children)};
205 // it.length is the current depth in the iterator and the
206 // current depth through the `uint` key we've traversed.
207 let child_id = chunk(key, it.length);
208 let (slice_idx, ret) = match children[child_id] {
209 Internal(ref $($mut_)* n) => {
211 mem::transmute::<_, uint>(&**n)
214 (child_id + 1, false)
216 External(stored, _) => {
217 (if stored < key || ($upper && stored == key) {
227 // push to the stack.
228 it.stack[it.length] = children.$slice_from(slice_idx).$iter();
237 // If `upper` is true then returns upper_bound else returns lower_bound.
239 fn bound<'a>(&'a self, key: uint, upper: bool) -> Entries<'a, T> {
240 bound!(Entries, self = self,
241 key = key, is_upper = upper,
242 slice_from = slice_from, iter = iter,
246 /// Get an iterator pointing to the first key-value pair whose key is not less than `key`.
247 /// If all keys in the map are less than `key` an empty iterator is returned.
248 pub fn lower_bound<'a>(&'a self, key: uint) -> Entries<'a, T> {
249 self.bound(key, false)
252 /// Get an iterator pointing to the first key-value pair whose key is greater than `key`.
253 /// If all keys in the map are not greater than `key` an empty iterator is returned.
254 pub fn upper_bound<'a>(&'a self, key: uint) -> Entries<'a, T> {
255 self.bound(key, true)
257 // If `upper` is true then returns upper_bound else returns lower_bound.
259 fn mut_bound<'a>(&'a mut self, key: uint, upper: bool) -> MutEntries<'a, T> {
260 bound!(MutEntries, self = self,
261 key = key, is_upper = upper,
262 slice_from = mut_slice_from, iter = mut_iter,
266 /// Get an iterator pointing to the first key-value pair whose key is not less than `key`.
267 /// If all keys in the map are less than `key` an empty iterator is returned.
268 pub fn mut_lower_bound<'a>(&'a mut self, key: uint) -> MutEntries<'a, T> {
269 self.mut_bound(key, false)
272 /// Get an iterator pointing to the first key-value pair whose key is greater than `key`.
273 /// If all keys in the map are not greater than `key` an empty iterator is returned.
274 pub fn mut_upper_bound<'a>(&'a mut self, key: uint) -> MutEntries<'a, T> {
275 self.mut_bound(key, true)
279 impl<T> FromIterator<(uint, T)> for TrieMap<T> {
280 fn from_iter<Iter: Iterator<(uint, T)>>(iter: Iter) -> TrieMap<T> {
281 let mut map = TrieMap::new();
287 impl<T> Extendable<(uint, T)> for TrieMap<T> {
288 fn extend<Iter: Iterator<(uint, T)>>(&mut self, mut iter: Iter) {
295 #[allow(missing_doc)]
300 impl Collection for TrieSet {
301 /// Return the number of elements in the set
303 fn len(&self) -> uint { self.map.len() }
306 impl Mutable for TrieSet {
307 /// Clear the set, removing all values.
309 fn clear(&mut self) { self.map.clear() }
312 impl Set<uint> for TrieSet {
314 fn contains(&self, value: &uint) -> bool {
315 self.map.contains_key(value)
319 fn is_disjoint(&self, other: &TrieSet) -> bool {
320 self.iter().all(|v| !other.contains(&v))
324 fn is_subset(&self, other: &TrieSet) -> bool {
325 self.iter().all(|v| other.contains(&v))
329 fn is_superset(&self, other: &TrieSet) -> bool {
330 other.is_subset(self)
334 impl MutableSet<uint> for TrieSet {
336 fn insert(&mut self, value: uint) -> bool {
337 self.map.insert(value, ())
341 fn remove(&mut self, value: &uint) -> bool {
342 self.map.remove(value)
346 impl Default for TrieSet {
348 fn default() -> TrieSet { TrieSet::new() }
352 /// Create an empty TrieSet
354 pub fn new() -> TrieSet {
355 TrieSet{map: TrieMap::new()}
358 /// Visit all values in reverse order
360 pub fn each_reverse(&self, f: |&uint| -> bool) -> bool {
361 self.map.each_reverse(|k, _| f(k))
364 /// Get an iterator over the values in the set
366 pub fn iter<'a>(&'a self) -> SetItems<'a> {
367 SetItems{iter: self.map.iter()}
370 /// Get an iterator pointing to the first value that is not less than `val`.
371 /// If all values in the set are less than `val` an empty iterator is returned.
372 pub fn lower_bound<'a>(&'a self, val: uint) -> SetItems<'a> {
373 SetItems{iter: self.map.lower_bound(val)}
376 /// Get an iterator pointing to the first value that key is greater than `val`.
377 /// If all values in the set are not greater than `val` an empty iterator is returned.
378 pub fn upper_bound<'a>(&'a self, val: uint) -> SetItems<'a> {
379 SetItems{iter: self.map.upper_bound(val)}
383 impl FromIterator<uint> for TrieSet {
384 fn from_iter<Iter: Iterator<uint>>(iter: Iter) -> TrieSet {
385 let mut set = TrieSet::new();
391 impl Extendable<uint> for TrieSet {
392 fn extend<Iter: Iterator<uint>>(&mut self, mut iter: Iter) {
401 children: [Child<T>, ..SIZE]
404 impl<T> TrieNode<T> {
406 fn new() -> TrieNode<T> {
407 // FIXME: #5244: [Nothing, ..SIZE] should be possible without implicit
410 children: [Nothing, Nothing, Nothing, Nothing,
411 Nothing, Nothing, Nothing, Nothing,
412 Nothing, Nothing, Nothing, Nothing,
413 Nothing, Nothing, Nothing, Nothing]}
417 impl<T> TrieNode<T> {
418 fn each_reverse<'a>(&'a self, f: |&uint, &'a T| -> bool) -> bool {
419 for elt in self.children.iter().rev() {
421 Internal(ref x) => if !x.each_reverse(|i,t| f(i,t)) { return false },
422 External(k, ref v) => if !f(&k, v) { return false },
430 // if this was done via a trait, the key could be generic
432 fn chunk(n: uint, idx: uint) -> uint {
433 let sh = uint::BITS - (SHIFT * (idx + 1));
437 fn find_mut<'r, T>(child: &'r mut Child<T>, key: uint, idx: uint) -> Option<&'r mut T> {
439 External(stored, ref mut value) if stored == key => Some(value),
440 External(..) => None,
441 Internal(ref mut x) => find_mut(&mut x.children[chunk(key, idx)], key, idx + 1),
446 fn insert<T>(count: &mut uint, child: &mut Child<T>, key: uint, value: T,
447 idx: uint) -> Option<T> {
448 // we branch twice to avoid having to do the `replace` when we
449 // don't need to; this is much faster, especially for keys that
450 // have long shared prefixes.
454 *child = External(key, value);
457 Internal(ref mut x) => {
458 return insert(&mut x.count, &mut x.children[chunk(key, idx)], key, value, idx + 1);
460 External(stored_key, ref mut stored_value) if stored_key == key => {
461 // swap in the new value and return the old.
462 return Some(mem::replace(stored_value, value));
467 // conflict, an external node with differing keys: we have to
468 // split the node, so we need the old value by value; hence we
469 // have to move out of `child`.
470 match mem::replace(child, Nothing) {
471 External(stored_key, stored_value) => {
472 let mut new = box TrieNode::new();
473 insert(&mut new.count,
474 &mut new.children[chunk(stored_key, idx)],
475 stored_key, stored_value, idx + 1);
476 let ret = insert(&mut new.count, &mut new.children[chunk(key, idx)],
477 key, value, idx + 1);
478 *child = Internal(new);
481 _ => fail!("unreachable code"),
485 fn remove<T>(count: &mut uint, child: &mut Child<T>, key: uint,
486 idx: uint) -> Option<T> {
487 let (ret, this) = match *child {
488 External(stored, _) if stored == key => {
489 match mem::replace(child, Nothing) {
490 External(_, value) => (Some(value), true),
494 External(..) => (None, false),
495 Internal(ref mut x) => {
496 let ret = remove(&mut x.count, &mut x.children[chunk(key, idx)],
500 Nothing => (None, false)
510 /// Forward iterator over a map
511 pub struct Entries<'a, T> {
512 stack: [slice::Items<'a, Child<T>>, .. NUM_CHUNKS],
518 /// Forward iterator over the key-value pairs of a map, with the
519 /// values being mutable.
520 pub struct MutEntries<'a, T> {
521 stack: [slice::MutItems<'a, Child<T>>, .. NUM_CHUNKS],
527 // FIXME #5846: see `addr!` above.
528 macro_rules! item { ($i:item) => {$i}}
530 macro_rules! iterator_impl {
533 mutability = $($mut_:tt)*) => {
534 impl<'a, T> $name<'a, T> {
535 // Create new zero'd iterator. We have a thin gilding of safety by
536 // using init rather than uninit, so that the worst that can happen
537 // from failing to initialise correctly after calling these is a
539 #[cfg(target_word_size="32")]
540 unsafe fn new() -> $name<'a, T> {
545 // ick :( ... at least the compiler will tell us if we screwed up.
546 stack: [zeroed(), zeroed(), zeroed(), zeroed(), zeroed(),
547 zeroed(), zeroed(), zeroed()]
551 #[cfg(target_word_size="64")]
552 unsafe fn new() -> $name<'a, T> {
557 stack: [zeroed(), zeroed(), zeroed(), zeroed(),
558 zeroed(), zeroed(), zeroed(), zeroed(),
559 zeroed(), zeroed(), zeroed(), zeroed(),
560 zeroed(), zeroed(), zeroed(), zeroed()]
565 item!(impl<'a, T> Iterator<(uint, &'a $($mut_)* T)> for $name<'a, T> {
566 // you might wonder why we're not even trying to act within the
567 // rules, and are just manipulating raw pointers like there's no
568 // such thing as invalid pointers and memory unsafety. The
569 // reason is performance, without doing this we can get the
570 // bench_iter_large microbenchmark down to about 30000 ns/iter
571 // (using .unsafe_ref to index self.stack directly, 38000
572 // ns/iter with [] checked indexing), but this smashes that down
575 // Fortunately, it's still safe...
577 // We have an invariant that every Internal node
578 // corresponds to one push to self.stack, and one pop,
579 // nested appropriately. self.stack has enough storage
580 // to store the maximum depth of Internal nodes in the
581 // trie (8 on 32-bit platforms, 16 on 64-bit).
582 fn next(&mut self) -> Option<(uint, &'a $($mut_)* T)> {
583 let start_ptr = self.stack.as_mut_ptr();
586 // write_ptr is the next place to write to the stack.
587 // invariant: start_ptr <= write_ptr < end of the
589 let mut write_ptr = start_ptr.offset(self.length as int);
590 while write_ptr != start_ptr {
591 // indexing back one is safe, since write_ptr >
593 match (*write_ptr.offset(-1)).next() {
594 // exhausted this iterator (i.e. finished this
595 // Internal node), so pop from the stack.
597 // don't bother clearing the memory, because the
598 // next time we use it we'll've written to it
600 None => write_ptr = write_ptr.offset(-1),
603 Internal(ref $($mut_)* node) => {
604 // going down a level, so push
605 // to the stack (this is the
606 // write referenced above)
607 *write_ptr = node.children.$iter();
608 write_ptr = write_ptr.offset(1);
610 External(key, ref $($mut_)* value) => {
611 self.remaining_max -= 1;
612 if self.remaining_min > 0 {
613 self.remaining_min -= 1;
615 // store the new length of the
616 // stack, based on our current
618 self.length = (write_ptr as uint
619 - start_ptr as uint) /
620 mem::size_of_val(&*write_ptr);
622 return Some((key, value));
634 fn size_hint(&self) -> (uint, Option<uint>) {
635 (self.remaining_min, Some(self.remaining_max))
641 iterator_impl! { Entries, iter = iter, mutability = }
642 iterator_impl! { MutEntries, iter = mut_iter, mutability = mut }
644 /// Forward iterator over a set
645 pub struct SetItems<'a> {
646 iter: Entries<'a, ()>
649 impl<'a> Iterator<uint> for SetItems<'a> {
650 fn next(&mut self) -> Option<uint> {
651 self.iter.next().map(|(key, _)| key)
654 fn size_hint(&self) -> (uint, Option<uint>) {
655 self.iter.size_hint()
662 use std::iter::range_step;
665 use {MutableMap, Map};
666 use super::{TrieMap, TrieNode, Internal, External, Nothing};
668 fn check_integrity<T>(trie: &TrieNode<T>) {
669 assert!(trie.count != 0);
673 for x in trie.children.iter() {
677 check_integrity(&**y);
680 External(_, _) => { sum += 1 }
684 assert_eq!(sum, trie.count);
689 let mut m = TrieMap::new();
690 assert!(m.insert(1u, 12i));
691 assert!(m.insert(2u, 8i));
692 assert!(m.insert(5u, 14i));
694 match m.find_mut(&5) {
695 None => fail!(), Some(x) => *x = new
697 assert_eq!(m.find(&5), Some(&new));
701 fn test_find_mut_missing() {
702 let mut m = TrieMap::new();
703 assert!(m.find_mut(&0).is_none());
704 assert!(m.insert(1u, 12i));
705 assert!(m.find_mut(&0).is_none());
706 assert!(m.insert(2, 8));
707 assert!(m.find_mut(&0).is_none());
712 let mut trie = TrieMap::new();
715 for x in range_step(1u, n, 2) {
716 assert!(trie.insert(x, x + 1));
717 assert!(trie.contains_key(&x));
718 check_integrity(&trie.root);
721 for x in range_step(0u, n, 2) {
722 assert!(!trie.contains_key(&x));
723 assert!(trie.insert(x, x + 1));
724 check_integrity(&trie.root);
727 for x in range(0u, n) {
728 assert!(trie.contains_key(&x));
729 assert!(!trie.insert(x, x + 1));
730 check_integrity(&trie.root);
733 for x in range_step(1u, n, 2) {
734 assert!(trie.remove(&x));
735 assert!(!trie.contains_key(&x));
736 check_integrity(&trie.root);
739 for x in range_step(0u, n, 2) {
740 assert!(trie.contains_key(&x));
741 assert!(!trie.insert(x, x + 1));
742 check_integrity(&trie.root);
747 fn test_each_reverse() {
748 let mut m = TrieMap::new();
750 assert!(m.insert(3, 6));
751 assert!(m.insert(0, 0));
752 assert!(m.insert(4, 8));
753 assert!(m.insert(2, 4));
754 assert!(m.insert(1, 2));
757 m.each_reverse(|k, v| {
759 assert_eq!(*v, n * 2);
766 fn test_each_reverse_break() {
767 let mut m = TrieMap::new();
769 for x in range(uint::MAX - 10000, uint::MAX).rev() {
773 let mut n = uint::MAX - 1;
774 m.each_reverse(|k, v| {
775 if n == uint::MAX - 5000 { false } else {
776 assert!(n > uint::MAX - 5000);
779 assert_eq!(*v, n / 2);
788 let mut m = TrieMap::new();
789 assert_eq!(m.swap(1u, 2i), None);
790 assert_eq!(m.swap(1u, 3i), Some(2));
791 assert_eq!(m.swap(1u, 4i), Some(3));
796 let mut m = TrieMap::new();
798 assert_eq!(m.pop(&1), Some(2));
799 assert_eq!(m.pop(&1), None);
803 fn test_from_iter() {
804 let xs = vec![(1u, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
806 let map: TrieMap<int> = xs.iter().map(|&x| x).collect();
808 for &(k, v) in xs.iter() {
809 assert_eq!(map.find(&k), Some(&v));
814 fn test_iteration() {
815 let empty_map : TrieMap<uint> = TrieMap::new();
816 assert_eq!(empty_map.iter().next(), None);
818 let first = uint::MAX - 10000;
819 let last = uint::MAX;
821 let mut map = TrieMap::new();
822 for x in range(first, last).rev() {
823 map.insert(x, x / 2);
827 for (k, &v) in map.iter() {
828 assert_eq!(k, first + i);
829 assert_eq!(v, k / 2);
832 assert_eq!(i, last - first);
837 let mut empty_map : TrieMap<uint> = TrieMap::new();
838 assert!(empty_map.mut_iter().next().is_none());
840 let first = uint::MAX - 10000;
841 let last = uint::MAX;
843 let mut map = TrieMap::new();
844 for x in range(first, last).rev() {
845 map.insert(x, x / 2);
849 for (k, v) in map.mut_iter() {
850 assert_eq!(k, first + i);
854 assert_eq!(i, last - first);
856 assert!(map.iter().all(|(_, &v)| v == 0));
861 let empty_map : TrieMap<uint> = TrieMap::new();
862 assert_eq!(empty_map.lower_bound(0).next(), None);
863 assert_eq!(empty_map.upper_bound(0).next(), None);
869 let mut map : TrieMap<uint> = TrieMap::new();
870 for x in range_step(0u, last, step) {
871 assert!(x % step == 0);
872 map.insert(x, value);
875 for i in range(0u, last - step) {
876 let mut lb = map.lower_bound(i);
877 let mut ub = map.upper_bound(i);
878 let next_key = i - i % step + step;
879 let next_pair = (next_key, &value);
881 assert_eq!(lb.next(), Some((i, &value)));
883 assert_eq!(lb.next(), Some(next_pair));
885 assert_eq!(ub.next(), Some(next_pair));
888 let mut lb = map.lower_bound(last - step);
889 assert_eq!(lb.next(), Some((last - step, &value)));
890 let mut ub = map.upper_bound(last - step);
891 assert_eq!(ub.next(), None);
893 for i in range(last - step + 1, last) {
894 let mut lb = map.lower_bound(i);
895 assert_eq!(lb.next(), None);
896 let mut ub = map.upper_bound(i);
897 assert_eq!(ub.next(), None);
902 fn test_mut_bound() {
903 let empty_map : TrieMap<uint> = TrieMap::new();
904 assert_eq!(empty_map.lower_bound(0).next(), None);
905 assert_eq!(empty_map.upper_bound(0).next(), None);
907 let mut m_lower = TrieMap::new();
908 let mut m_upper = TrieMap::new();
909 for i in range(0u, 100) {
910 m_lower.insert(2 * i, 4 * i);
911 m_upper.insert(2 * i, 4 * i);
914 for i in range(0u, 199) {
915 let mut lb_it = m_lower.mut_lower_bound(i);
916 let (k, v) = lb_it.next().unwrap();
922 for i in range(0u, 198) {
923 let mut ub_it = m_upper.mut_upper_bound(i);
924 let (k, v) = ub_it.next().unwrap();
925 let ub = i + 2 - i % 2;
930 assert!(m_lower.mut_lower_bound(199).next().is_none());
931 assert!(m_upper.mut_upper_bound(198).next().is_none());
933 assert!(m_lower.iter().all(|(_, &x)| x == 0));
934 assert!(m_upper.iter().all(|(_, &x)| x == 0));
941 use std::rand::{weak_rng, Rng};
948 fn bench_iter_small(b: &mut Bencher) {
949 let mut m = TrieMap::<uint>::new();
950 let mut rng = weak_rng();
951 for _ in range(0u, 20) {
952 m.insert(rng.gen(), rng.gen());
955 b.iter(|| for _ in m.iter() {})
959 fn bench_iter_large(b: &mut Bencher) {
960 let mut m = TrieMap::<uint>::new();
961 let mut rng = weak_rng();
962 for _ in range(0u, 1000) {
963 m.insert(rng.gen(), rng.gen());
966 b.iter(|| for _ in m.iter() {})
970 fn bench_lower_bound(b: &mut Bencher) {
971 let mut m = TrieMap::<uint>::new();
972 let mut rng = weak_rng();
973 for _ in range(0u, 1000) {
974 m.insert(rng.gen(), rng.gen());
978 for _ in range(0u, 10) {
979 m.lower_bound(rng.gen());
985 fn bench_upper_bound(b: &mut Bencher) {
986 let mut m = TrieMap::<uint>::new();
987 let mut rng = weak_rng();
988 for _ in range(0u, 1000) {
989 m.insert(rng.gen(), rng.gen());
993 for _ in range(0u, 10) {
994 m.upper_bound(rng.gen());
1000 fn bench_insert_large(b: &mut Bencher) {
1001 let mut m = TrieMap::<[uint, .. 10]>::new();
1002 let mut rng = weak_rng();
1005 for _ in range(0u, 1000) {
1006 m.insert(rng.gen(), [1, .. 10]);
1011 fn bench_insert_large_low_bits(b: &mut Bencher) {
1012 let mut m = TrieMap::<[uint, .. 10]>::new();
1013 let mut rng = weak_rng();
1016 for _ in range(0u, 1000) {
1017 // only have the last few bits set.
1018 m.insert(rng.gen::<uint>() & 0xff_ff, [1, .. 10]);
1024 fn bench_insert_small(b: &mut Bencher) {
1025 let mut m = TrieMap::<()>::new();
1026 let mut rng = weak_rng();
1029 for _ in range(0u, 1000) {
1030 m.insert(rng.gen(), ());
1035 fn bench_insert_small_low_bits(b: &mut Bencher) {
1036 let mut m = TrieMap::<()>::new();
1037 let mut rng = weak_rng();
1040 for _ in range(0u, 1000) {
1041 // only have the last few bits set.
1042 m.insert(rng.gen::<uint>() & 0xff_ff, ());
1050 use std::prelude::*;
1053 use {MutableSet, Set};
1057 fn test_sane_chunk() {
1059 let y = 1 << (uint::BITS - 1);
1061 let mut trie = TrieSet::new();
1063 assert!(trie.insert(x));
1064 assert!(trie.insert(y));
1066 assert_eq!(trie.len(), 2);
1068 let expected = [x, y];
1070 for (i, x) in trie.iter().enumerate() {
1071 assert_eq!(expected[i], x);
1076 fn test_from_iter() {
1077 let xs = vec![9u, 8, 7, 6, 5, 4, 3, 2, 1];
1079 let set: TrieSet = xs.iter().map(|&x| x).collect();
1081 for x in xs.iter() {
1082 assert!(set.contains(x));