1 // Copyright 2013 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 //! An ordered map and set for integer keys implemented as a radix trie
14 use iterator::{IteratorUtil, FromIterator, Extendable};
16 use util::{swap, replace};
19 // FIXME: #5244: need to manually update the TrieNode constructor
20 static SHIFT: uint = 4;
21 static SIZE: uint = 1 << SHIFT;
22 static MASK: uint = SIZE - 1;
25 Internal(~TrieNode<T>),
31 pub struct TrieMap<T> {
32 priv root: TrieNode<T>,
36 impl<T> Container for TrieMap<T> {
37 /// Return the number of elements in the map
39 fn len(&self) -> uint { self.length }
42 impl<T> Mutable for TrieMap<T> {
43 /// Clear the map, removing all values.
46 self.root = TrieNode::new();
51 impl<T> Map<uint, T> for TrieMap<T> {
52 /// Return a reference to the value corresponding to the key
54 fn find<'a>(&'a self, key: &uint) -> Option<&'a T> {
55 let mut node: &'a TrieNode<T> = &self.root;
58 match node.children[chunk(*key, idx)] {
59 Internal(ref x) => node = &**x,
60 External(stored, ref value) => {
67 Nothing => return None
74 impl<T> MutableMap<uint, T> for TrieMap<T> {
75 /// Return a mutable reference to the value corresponding to the key
77 fn find_mut<'a>(&'a mut self, key: &uint) -> Option<&'a mut T> {
78 find_mut(&mut self.root.children[chunk(*key, 0)], *key, 1)
81 /// Insert a key-value pair from the map. If the key already had a value
82 /// present in the map, that value is returned. Otherwise None is returned.
83 fn swap(&mut self, key: uint, value: T) -> Option<T> {
84 let ret = insert(&mut self.root.count,
85 &mut self.root.children[chunk(key, 0)],
87 if ret.is_none() { self.length += 1 }
91 /// Removes a key from the map, returning the value at the key if the key
92 /// was previously in the map.
93 fn pop(&mut self, key: &uint) -> Option<T> {
94 let ret = remove(&mut self.root.count,
95 &mut self.root.children[chunk(*key, 0)],
97 if ret.is_some() { self.length -= 1 }
103 /// Create an empty TrieMap
105 pub fn new() -> TrieMap<T> {
106 TrieMap{root: TrieNode::new(), length: 0}
109 /// Visit all key-value pairs in reverse order
111 pub fn each_reverse<'a>(&'a self, f: &fn(&uint, &'a T) -> bool) -> bool {
112 self.root.each_reverse(f)
115 /// Visit all key-value pairs in order
117 pub fn each<'a>(&'a self, f: &fn(&uint, &'a T) -> bool) -> bool {
121 /// Visit all keys in order
123 pub fn each_key(&self, f: &fn(&uint) -> bool) -> bool {
124 self.each(|k, _| f(k))
127 /// Visit all values in order
129 pub fn each_value<'a>(&'a self, f: &fn(&'a T) -> bool) -> bool {
130 self.each(|_, v| f(v))
133 /// Iterate over the map and mutate the contained values
135 pub fn mutate_values(&mut self, f: &fn(&uint, &mut T) -> bool) -> bool {
136 self.root.mutate_values(f)
139 /// Visit all keys in reverse order
141 pub fn each_key_reverse(&self, f: &fn(&uint) -> bool) -> bool {
142 self.each_reverse(|k, _| f(k))
145 /// Visit all values in reverse order
147 pub fn each_value_reverse(&self, f: &fn(&T) -> bool) -> bool {
148 self.each_reverse(|_, v| f(v))
151 /// Get an iterator over the key-value pairs in the map
152 pub fn iter<'a>(&'a self) -> TrieMapIterator<'a, T> {
154 stack: ~[self.root.children.iter()],
155 remaining_min: self.length,
156 remaining_max: self.length
161 impl<T, Iter: Iterator<(uint, T)>> FromIterator<(uint, T), Iter> for TrieMap<T> {
162 fn from_iterator(iter: &mut Iter) -> TrieMap<T> {
163 let mut map = TrieMap::new();
169 impl<T, Iter: Iterator<(uint, T)>> Extendable<(uint, T), Iter> for TrieMap<T> {
170 fn extend(&mut self, iter: &mut Iter) {
171 for (k, v) in *iter {
177 #[allow(missing_doc)]
179 priv map: TrieMap<()>
182 impl Container for TrieSet {
183 /// Return the number of elements in the set
185 fn len(&self) -> uint { self.map.len() }
188 impl Mutable for TrieSet {
189 /// Clear the set, removing all values.
191 fn clear(&mut self) { self.map.clear() }
195 /// Create an empty TrieSet
197 pub fn new() -> TrieSet {
198 TrieSet{map: TrieMap::new()}
201 /// Return true if the set contains a value
203 pub fn contains(&self, value: &uint) -> bool {
204 self.map.contains_key(value)
207 /// Add a value to the set. Return true if the value was not already
208 /// present in the set.
210 pub fn insert(&mut self, value: uint) -> bool {
211 self.map.insert(value, ())
214 /// Remove a value from the set. Return true if the value was
215 /// present in the set.
217 pub fn remove(&mut self, value: &uint) -> bool {
218 self.map.remove(value)
221 /// Visit all values in order
223 pub fn each(&self, f: &fn(&uint) -> bool) -> bool { self.map.each_key(f) }
225 /// Visit all values in reverse order
227 pub fn each_reverse(&self, f: &fn(&uint) -> bool) -> bool {
228 self.map.each_key_reverse(f)
231 /// Get an iterator over the values in the set
233 pub fn iter<'a>(&'a self) -> TrieSetIterator<'a> {
234 TrieSetIterator{iter: self.map.iter()}
238 impl<Iter: Iterator<uint>> FromIterator<uint, Iter> for TrieSet {
239 fn from_iterator(iter: &mut Iter) -> TrieSet {
240 let mut set = TrieSet::new();
246 impl<Iter: Iterator<uint>> Extendable<uint, Iter> for TrieSet {
247 fn extend(&mut self, iter: &mut Iter) {
256 children: [Child<T>, ..SIZE]
259 impl<T> TrieNode<T> {
261 fn new() -> TrieNode<T> {
262 // FIXME: #5244: [Nothing, ..SIZE] should be possible without implicit
265 children: [Nothing, Nothing, Nothing, Nothing,
266 Nothing, Nothing, Nothing, Nothing,
267 Nothing, Nothing, Nothing, Nothing,
268 Nothing, Nothing, Nothing, Nothing]}
272 impl<T> TrieNode<T> {
273 fn each<'a>(&'a self, f: &fn(&uint, &'a T) -> bool) -> bool {
274 for idx in range(0u, self.children.len()) {
275 match self.children[idx] {
276 Internal(ref x) => if !x.each(|i,t| f(i,t)) { return false },
277 External(k, ref v) => if !f(&k, v) { return false },
284 fn each_reverse<'a>(&'a self, f: &fn(&uint, &'a T) -> bool) -> bool {
285 do uint::range_rev(self.children.len(), 0) |idx| {
286 match self.children[idx] {
287 Internal(ref x) => x.each_reverse(|i,t| f(i,t)),
288 External(k, ref v) => f(&k, v),
294 fn mutate_values<'a>(&'a mut self, f: &fn(&uint, &mut T) -> bool) -> bool {
295 for child in self.children.mut_iter() {
297 Internal(ref mut x) => if !x.mutate_values(|i,t| f(i,t)) {
300 External(k, ref mut v) => if !f(&k, v) { return false },
308 // if this was done via a trait, the key could be generic
310 fn chunk(n: uint, idx: uint) -> uint {
311 let sh = uint::bits - (SHIFT * (idx + 1));
315 fn find_mut<'r, T>(child: &'r mut Child<T>, key: uint, idx: uint) -> Option<&'r mut T> {
317 External(_, ref mut value) => Some(value),
318 Internal(ref mut x) => find_mut(&mut x.children[chunk(key, idx)], key, idx + 1),
323 fn insert<T>(count: &mut uint, child: &mut Child<T>, key: uint, value: T,
324 idx: uint) -> Option<T> {
325 let mut tmp = Nothing;
327 swap(&mut tmp, child);
330 External(stored_key, stored_value) => {
331 if stored_key == key {
332 ret = Some(stored_value);
333 External(stored_key, value)
335 // conflict - split the node
336 let mut new = ~TrieNode::new();
337 insert(&mut new.count,
338 &mut new.children[chunk(stored_key, idx)],
339 stored_key, stored_value, idx + 1);
340 ret = insert(&mut new.count, &mut new.children[chunk(key, idx)],
341 key, value, idx + 1);
347 ret = insert(&mut x.count, &mut x.children[chunk(key, idx)], key,
360 fn remove<T>(count: &mut uint, child: &mut Child<T>, key: uint,
361 idx: uint) -> Option<T> {
362 let (ret, this) = match *child {
363 External(stored, _) if stored == key => {
364 match replace(child, Nothing) {
365 External(_, value) => (Some(value), true),
369 External(*) => (None, false),
370 Internal(ref mut x) => {
371 let ret = remove(&mut x.count, &mut x.children[chunk(key, idx)],
375 Nothing => (None, false)
385 /// Forward iterator over a map
386 pub struct TrieMapIterator<'self, T> {
387 priv stack: ~[vec::VecIterator<'self, Child<T>>],
388 priv remaining_min: uint,
389 priv remaining_max: uint
392 impl<'self, T> Iterator<(uint, &'self T)> for TrieMapIterator<'self, T> {
393 fn next(&mut self) -> Option<(uint, &'self T)> {
394 while !self.stack.is_empty() {
395 match self.stack[self.stack.len() - 1].next() {
401 Internal(ref node) => {
402 self.stack.push(node.children.iter());
404 External(key, ref value) => {
405 self.remaining_max -= 1;
406 if self.remaining_min > 0 {
407 self.remaining_min -= 1;
409 return Some((key, value));
420 fn size_hint(&self) -> (uint, Option<uint>) {
421 (self.remaining_min, Some(self.remaining_max))
425 /// Forward iterator over a set
426 pub struct TrieSetIterator<'self> {
427 priv iter: TrieMapIterator<'self, ()>
430 impl<'self> Iterator<uint> for TrieSetIterator<'self> {
431 fn next(&mut self) -> Option<uint> {
432 do self.iter.next().map |&(key, _)| { key }
435 fn size_hint(&self) -> (uint, Option<uint>) {
436 self.iter.size_hint()
441 pub fn check_integrity<T>(trie: &TrieNode<T>) {
442 assert!(trie.count != 0);
446 for x in trie.children.iter() {
450 check_integrity(&**y);
453 External(_, _) => { sum += 1 }
457 assert_eq!(sum, trie.count);
468 let mut m = TrieMap::new();
469 assert!(m.insert(1, 12));
470 assert!(m.insert(2, 8));
471 assert!(m.insert(5, 14));
473 match m.find_mut(&5) {
474 None => fail!(), Some(x) => *x = new
476 assert_eq!(m.find(&5), Some(&new));
481 let mut trie = TrieMap::new();
484 do uint::range_step(1, n, 2) |x| {
485 assert!(trie.insert(x, x + 1));
486 assert!(trie.contains_key(&x));
487 check_integrity(&trie.root);
491 do uint::range_step(0, n, 2) |x| {
492 assert!(!trie.contains_key(&x));
493 assert!(trie.insert(x, x + 1));
494 check_integrity(&trie.root);
498 for x in range(0u, n) {
499 assert!(trie.contains_key(&x));
500 assert!(!trie.insert(x, x + 1));
501 check_integrity(&trie.root);
504 do uint::range_step(1, n, 2) |x| {
505 assert!(trie.remove(&x));
506 assert!(!trie.contains_key(&x));
507 check_integrity(&trie.root);
511 do uint::range_step(0, n, 2) |x| {
512 assert!(trie.contains_key(&x));
513 assert!(!trie.insert(x, x + 1));
514 check_integrity(&trie.root);
521 let mut m = TrieMap::new();
523 assert!(m.insert(3, 6));
524 assert!(m.insert(0, 0));
525 assert!(m.insert(4, 8));
526 assert!(m.insert(2, 4));
527 assert!(m.insert(1, 2));
532 assert_eq!(*v, n * 2);
539 fn test_each_break() {
540 let mut m = TrieMap::new();
542 do uint::range_rev(uint::max_value, uint::max_value - 10000) |x| {
547 let mut n = uint::max_value - 10000;
549 if n == uint::max_value - 5000 { false } else {
550 assert!(n < uint::max_value - 5000);
553 assert_eq!(*v, n / 2);
561 fn test_each_reverse() {
562 let mut m = TrieMap::new();
564 assert!(m.insert(3, 6));
565 assert!(m.insert(0, 0));
566 assert!(m.insert(4, 8));
567 assert!(m.insert(2, 4));
568 assert!(m.insert(1, 2));
571 do m.each_reverse |k, v| {
573 assert_eq!(*v, n * 2);
580 fn test_each_reverse_break() {
581 let mut m = TrieMap::new();
583 do uint::range_rev(uint::max_value, uint::max_value - 10000) |x| {
588 let mut n = uint::max_value - 1;
589 do m.each_reverse |k, v| {
590 if n == uint::max_value - 5000 { false } else {
591 assert!(n > uint::max_value - 5000);
594 assert_eq!(*v, n / 2);
603 let mut m = TrieMap::new();
604 assert_eq!(m.swap(1, 2), None);
605 assert_eq!(m.swap(1, 3), Some(2));
606 assert_eq!(m.swap(1, 4), Some(3));
611 let mut m = TrieMap::new();
613 assert_eq!(m.pop(&1), Some(2));
614 assert_eq!(m.pop(&1), None);
618 fn test_from_iter() {
619 let xs = ~[(1u, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
621 let map: TrieMap<int> = xs.iter().transform(|&x| x).collect();
623 for &(k, v) in xs.iter() {
624 assert_eq!(map.find(&k), Some(&v));
629 fn test_iteration() {
630 let empty_map : TrieMap<uint> = TrieMap::new();
631 assert_eq!(empty_map.iter().next(), None);
633 let first = uint::max_value - 10000;
634 let last = uint::max_value;
636 let mut map = TrieMap::new();
637 do uint::range_rev(last, first) |x| {
638 map.insert(x, x / 2);
643 for (k, &v) in map.iter() {
644 assert_eq!(k, first + i);
645 assert_eq!(v, k / 2);
648 assert_eq!(i, last - first);
659 fn test_sane_chunk() {
661 let y = 1 << (uint::bits - 1);
663 let mut trie = TrieSet::new();
665 assert!(trie.insert(x));
666 assert!(trie.insert(y));
668 assert_eq!(trie.len(), 2);
670 let expected = [x, y];
675 assert_eq!(expected[i], *x);
682 fn test_from_iter() {
683 let xs = ~[9u, 8, 7, 6, 5, 4, 3, 2, 1];
685 let set: TrieSet = xs.iter().transform(|&x| x).collect();
688 assert!(set.contains(x));