(index<- ) ./libextra/treemap.rs
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.
4 //
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.
10
11 //! An ordered map and set implemented as self-balancing binary search
12 //! trees. The only requirement for the types is that the key implements
13 //! `TotalOrd`.
14
15
16 use std::util::{swap, replace};
17 use std::iter::{Peekable};
18 use std::cmp::Ordering;
19
20 // This is implemented as an AA tree, which is a simplified variation of
21 // a red-black tree where red (horizontal) nodes can only be added
22 // as a right child. The time complexity is the same, and re-balancing
23 // operations are more frequent but also cheaper.
24
25 // Future improvements:
26
27 // range search - O(log n) retrieval of an iterator from some key
28
29 // (possibly) implement the overloads Python does for sets:
30 // * intersection: &
31 // * difference: -
32 // * symmetric difference: ^
33 // * union: |
34 // These would be convenient since the methods work like `each`
35
36 #[allow(missing_doc)]
37 #[deriving(Clone)]
38 pub struct TreeMap<K, V> {
39 priv root: Option<~TreeNode<K, V>>,
40 priv length: uint
41 }
42
43 impl<K: Eq + TotalOrd, V: Eq> Eq for TreeMap<K, V> {
44 fn eq(&self, other: &TreeMap<K, V>) -> bool {
45 self.len() == other.len() &&
46 self.iter().zip(other.iter()).all(|(a, b)| a == b)
47 }
48 }
49
50 // Lexicographical comparison
51 fn lt<K: Ord + TotalOrd, V: Ord>(a: &TreeMap<K, V>,
52 b: &TreeMap<K, V>) -> bool {
53 // the Zip iterator is as long as the shortest of a and b.
54 for ((key_a, value_a), (key_b, value_b)) in a.iter().zip(b.iter()) {
55 if *key_a < *key_b { return true; }
56 if *key_a > *key_b { return false; }
57 if *value_a < *value_b { return true; }
58 if *value_a > *value_b { return false; }
59 }
60
61 a.len() < b.len()
62 }
63
64 impl<K: Ord + TotalOrd, V: Ord> Ord for TreeMap<K, V> {
65 #[inline]
66 fn lt(&self, other: &TreeMap<K, V>) -> bool { lt(self, other) }
67 #[inline]
68 fn le(&self, other: &TreeMap<K, V>) -> bool { !lt(other, self) }
69 #[inline]
70 fn ge(&self, other: &TreeMap<K, V>) -> bool { !lt(self, other) }
71 #[inline]
72 fn gt(&self, other: &TreeMap<K, V>) -> bool { lt(other, self) }
73 }
74
75 impl<K: TotalOrd, V> Container for TreeMap<K, V> {
76 /// Return the number of elements in the map
77 fn len(&self) -> uint { self.length }
78
79 /// Return true if the map contains no elements
80 fn is_empty(&self) -> bool { self.root.is_none() }
81 }
82
83 impl<K: TotalOrd, V> Mutable for TreeMap<K, V> {
84 /// Clear the map, removing all key-value pairs.
85 fn clear(&mut self) {
86 self.root = None;
87 self.length = 0
88 }
89 }
90
91 impl<K: TotalOrd, V> Map<K, V> for TreeMap<K, V> {
92 /// Return a reference to the value corresponding to the key
93 fn find<'a>(&'a self, key: &K) -> Option<&'a V> {
94 let mut current: &'a Option<~TreeNode<K, V>> = &self.root;
95 loop {
96 match *current {
97 Some(ref r) => {
98 match key.cmp(&r.key) {
99 Less => current = &r.left,
100 Greater => current = &r.right,
101 Equal => return Some(&r.value)
102 }
103 }
104 None => return None
105 }
106 }
107 }
108 }
109
110 impl<K: TotalOrd, V> MutableMap<K, V> for TreeMap<K, V> {
111 /// Return a mutable reference to the value corresponding to the key
112 #[inline]
113 fn find_mut<'a>(&'a mut self, key: &K) -> Option<&'a mut V> {
114 find_mut(&mut self.root, key)
115 }
116
117 /// Insert a key-value pair from the map. If the key already had a value
118 /// present in the map, that value is returned. Otherwise None is returned.
119 fn swap(&mut self, key: K, value: V) -> Option<V> {
120 let ret = insert(&mut self.root, key, value);
121 if ret.is_none() { self.length += 1 }
122 ret
123 }
124
125 /// Removes a key from the map, returning the value at the key if the key
126 /// was previously in the map.
127 fn pop(&mut self, key: &K) -> Option<V> {
128 let ret = remove(&mut self.root, key);
129 if ret.is_some() { self.length -= 1 }
130 ret
131 }
132 }
133
134 impl<K: TotalOrd, V> TreeMap<K, V> {
135 /// Create an empty TreeMap
136 pub fn new() -> TreeMap<K, V> { TreeMap{root: None, length: 0} }
137
138 /// Iterate over the map and mutate the contained values
139 pub fn mutate_values(&mut self, f: &fn(&K, &mut V) -> bool) -> bool {
140 mutate_values(&mut self.root, f)
141 }
142
143 /// Get a lazy iterator over the key-value pairs in the map.
144 /// Requires that it be frozen (immutable).
145 pub fn iter<'a>(&'a self) -> TreeMapIterator<'a, K, V> {
146 TreeMapIterator {
147 stack: ~[],
148 node: &self.root,
149 remaining_min: self.length,
150 remaining_max: self.length
151 }
152 }
153
154 /// Get a lazy reverse iterator over the key-value pairs in the map.
155 /// Requires that it be frozen (immutable).
156 pub fn rev_iter<'a>(&'a self) -> TreeMapRevIterator<'a, K, V> {
157 TreeMapRevIterator{iter: self.iter()}
158 }
159
160 /// Get a lazy iterator that should be initialized using
161 /// `iter_traverse_left`/`iter_traverse_right`/`iter_traverse_complete`.
162 fn iter_for_traversal<'a>(&'a self) -> TreeMapIterator<'a, K, V> {
163 TreeMapIterator {
164 stack: ~[],
165 node: &self.root,
166 remaining_min: 0,
167 remaining_max: self.length
168 }
169 }
170
171 /// Return a lazy iterator to the first key-value pair whose key is not less than `k`
172 /// If all keys in map are less than `k` an empty iterator is returned.
173 pub fn lower_bound_iter<'a>(&'a self, k: &K) -> TreeMapIterator<'a, K, V> {
174 let mut iter: TreeMapIterator<'a, K, V> = self.iter_for_traversal();
175 loop {
176 match *iter.node {
177 Some(ref r) => {
178 match k.cmp(&r.key) {
179 Less => iter_traverse_left(&mut iter),
180 Greater => iter_traverse_right(&mut iter),
181 Equal => {
182 iter_traverse_complete(&mut iter);
183 return iter;
184 }
185 }
186 }
187 None => {
188 iter_traverse_complete(&mut iter);
189 return iter;
190 }
191 }
192 }
193 }
194
195 /// Return a lazy iterator to the first key-value pair whose key is greater than `k`
196 /// If all keys in map are not greater than `k` an empty iterator is returned.
197 pub fn upper_bound_iter<'a>(&'a self, k: &K) -> TreeMapIterator<'a, K, V> {
198 let mut iter: TreeMapIterator<'a, K, V> = self.iter_for_traversal();
199 loop {
200 match *iter.node {
201 Some(ref r) => {
202 match k.cmp(&r.key) {
203 Less => iter_traverse_left(&mut iter),
204 Greater => iter_traverse_right(&mut iter),
205 Equal => iter_traverse_right(&mut iter)
206 }
207 }
208 None => {
209 iter_traverse_complete(&mut iter);
210 return iter;
211 }
212 }
213 }
214 }
215
216 /// Get a lazy iterator that consumes the treemap.
217 pub fn move_iter(self) -> TreeMapMoveIterator<K, V> {
218 let TreeMap { root: root, length: length } = self;
219 let stk = match root {
220 None => ~[],
221 Some(~tn) => ~[tn]
222 };
223 TreeMapMoveIterator {
224 stack: stk,
225 remaining: length
226 }
227 }
228 }
229
230 /// Lazy forward iterator over a map
231 pub struct TreeMapIterator<'self, K, V> {
232 priv stack: ~[&'self ~TreeNode<K, V>],
233 priv node: &'self Option<~TreeNode<K, V>>,
234 priv remaining_min: uint,
235 priv remaining_max: uint
236 }
237
238 impl<'self, K, V> TreeMapIterator<'self, K, V> {
239 #[inline(always)]
240 fn next_(&mut self, forward: bool) -> Option<(&'self K, &'self V)> {
241 while !self.stack.is_empty() || self.node.is_some() {
242 match *self.node {
243 Some(ref x) => {
244 self.stack.push(x);
245 self.node = if forward { &x.left } else { &x.right };
246 }
247 None => {
248 let res = self.stack.pop();
249 self.node = if forward { &res.right } else { &res.left };
250 self.remaining_max -= 1;
251 if self.remaining_min > 0 {
252 self.remaining_min -= 1;
253 }
254 return Some((&res.key, &res.value));
255 }
256 }
257 }
258 None
259 }
260 }
261
262 impl<'self, K, V> Iterator<(&'self K, &'self V)> for TreeMapIterator<'self, K, V> {
263 /// Advance the iterator to the next node (in order) and return a
264 /// tuple with a reference to the key and value. If there are no
265 /// more nodes, return `None`.
266 fn next(&mut self) -> Option<(&'self K, &'self V)> {
267 self.next_(true)
268 }
269
270 #[inline]
271 fn size_hint(&self) -> (uint, Option<uint>) {
272 (self.remaining_min, Some(self.remaining_max))
273 }
274 }
275
276 /// Lazy backward iterator over a map
277 pub struct TreeMapRevIterator<'self, K, V> {
278 priv iter: TreeMapIterator<'self, K, V>,
279 }
280
281 impl<'self, K, V> Iterator<(&'self K, &'self V)> for TreeMapRevIterator<'self, K, V> {
282 /// Advance the iterator to the next node (in order) and return a
283 /// tuple with a reference to the key and value. If there are no
284 /// more nodes, return `None`.
285 fn next(&mut self) -> Option<(&'self K, &'self V)> {
286 self.iter.next_(false)
287 }
288
289 #[inline]
290 fn size_hint(&self) -> (uint, Option<uint>) {
291 self.iter.size_hint()
292 }
293 }
294
295 /// iter_traverse_left, iter_traverse_right and iter_traverse_complete are used to
296 /// initialize TreeMapIterator pointing to element inside tree structure.
297 ///
298 /// They should be used in following manner:
299 /// - create iterator using TreeMap::iter_for_traversal
300 /// - find required node using `iter_traverse_left`/`iter_traverse_right`
301 /// (current node is `TreeMapIterator::node` field)
302 /// - complete initialization with `iter_traverse_complete`
303 #[inline]
304 fn iter_traverse_left<'a, K, V>(it: &mut TreeMapIterator<'a, K, V>) {
305 let node = it.node.get_ref();
306 it.stack.push(node);
307 it.node = &node.left;
308 }
309
310 #[inline]
311 fn iter_traverse_right<'a, K, V>(it: &mut TreeMapIterator<'a, K, V>) {
312 it.node = &(it.node.get_ref().right);
313 }
314
315 /// iter_traverse_left, iter_traverse_right and iter_traverse_complete are used to
316 /// initialize TreeMapIterator pointing to element inside tree structure.
317 ///
318 /// Completes traversal. Should be called before using iterator.
319 /// Iteration will start from `self.node`.
320 /// If `self.node` is None iteration will start from last node from which we
321 /// traversed left.
322 #[inline]
323 fn iter_traverse_complete<'a, K, V>(it: &mut TreeMapIterator<'a, K, V>) {
324 static none: Option<~TreeNode<K, V>> = None;
325 match *it.node {
326 Some(ref n) => {
327 it.stack.push(n);
328 it.node = &none;
329 }
330 None => ()
331 }
332 }
333
334 /// Lazy forward iterator over a map that consumes the map while iterating
335 pub struct TreeMapMoveIterator<K, V> {
336 priv stack: ~[TreeNode<K, V>],
337 priv remaining: uint
338 }
339
340 impl<K, V> Iterator<(K, V)> for TreeMapMoveIterator<K,V> {
341 #[inline]
342 fn next(&mut self) -> Option<(K, V)> {
343 while !self.stack.is_empty() {
344 let TreeNode {
345 key: key,
346 value: value,
347 left: left,
348 right: right,
349 level: level
350 } = self.stack.pop();
351
352 match left {
353 Some(~left) => {
354 let n = TreeNode {
355 key: key,
356 value: value,
357 left: None,
358 right: right,
359 level: level
360 };
361 self.stack.push(n);
362 self.stack.push(left);
363 }
364 None => {
365 match right {
366 Some(~right) => self.stack.push(right),
367 None => ()
368 }
369 self.remaining -= 1;
370 return Some((key, value))
371 }
372 }
373 }
374 None
375 }
376
377 #[inline]
378 fn size_hint(&self) -> (uint, Option<uint>) {
379 (self.remaining, Some(self.remaining))
380 }
381
382 }
383
384 impl<'self, T> Iterator<&'self T> for TreeSetIterator<'self, T> {
385 /// Advance the iterator to the next node (in order). If there are no more nodes, return `None`.
386 #[inline]
387 fn next(&mut self) -> Option<&'self T> {
388 do self.iter.next().map_move |(value, _)| { value }
389 }
390 }
391
392 impl<'self, T> Iterator<&'self T> for TreeSetRevIterator<'self, T> {
393 /// Advance the iterator to the next node (in order). If there are no more nodes, return `None`.
394 #[inline]
395 fn next(&mut self) -> Option<&'self T> {
396 do self.iter.next().map |&(value, _)| { value }
397 }
398 }
399
400 /// A implementation of the `Set` trait on top of the `TreeMap` container. The
401 /// only requirement is that the type of the elements contained ascribes to the
402 /// `TotalOrd` trait.
403 pub struct TreeSet<T> {
404 priv map: TreeMap<T, ()>
405 }
406
407 impl<T: Eq + TotalOrd> Eq for TreeSet<T> {
408 #[inline]
409 fn eq(&self, other: &TreeSet<T>) -> bool { self.map == other.map }
410 #[inline]
411 fn ne(&self, other: &TreeSet<T>) -> bool { self.map != other.map }
412 }
413
414 impl<T: Ord + TotalOrd> Ord for TreeSet<T> {
415 #[inline]
416 fn lt(&self, other: &TreeSet<T>) -> bool { self.map < other.map }
417 #[inline]
418 fn le(&self, other: &TreeSet<T>) -> bool { self.map <= other.map }
419 #[inline]
420 fn ge(&self, other: &TreeSet<T>) -> bool { self.map >= other.map }
421 #[inline]
422 fn gt(&self, other: &TreeSet<T>) -> bool { self.map > other.map }
423 }
424
425 impl<T: TotalOrd> Container for TreeSet<T> {
426 /// Return the number of elements in the set
427 #[inline]
428 fn len(&self) -> uint { self.map.len() }
429
430 /// Return true if the set contains no elements
431 #[inline]
432 fn is_empty(&self) -> bool { self.map.is_empty() }
433 }
434
435 impl<T: TotalOrd> Mutable for TreeSet<T> {
436 /// Clear the set, removing all values.
437 #[inline]
438 fn clear(&mut self) { self.map.clear() }
439 }
440
441 impl<T: TotalOrd> Set<T> for TreeSet<T> {
442 /// Return true if the set contains a value
443 #[inline]
444 fn contains(&self, value: &T) -> bool {
445 self.map.contains_key(value)
446 }
447
448 /// Return true if the set has no elements in common with `other`.
449 /// This is equivalent to checking for an empty intersection.
450 fn is_disjoint(&self, other: &TreeSet<T>) -> bool {
451 self.intersection(other).next().is_none()
452 }
453
454 /// Return true if the set is a subset of another
455 #[inline]
456 fn is_subset(&self, other: &TreeSet<T>) -> bool {
457 other.is_superset(self)
458 }
459
460 /// Return true if the set is a superset of another
461 fn is_superset(&self, other: &TreeSet<T>) -> bool {
462 let mut x = self.iter();
463 let mut y = other.iter();
464 let mut a = x.next();
465 let mut b = y.next();
466 while b.is_some() {
467 if a.is_none() {
468 return false
469 }
470
471 let a1 = a.unwrap();
472 let b1 = b.unwrap();
473
474 match a1.cmp(b1) {
475 Less => (),
476 Greater => return false,
477 Equal => b = y.next(),
478 }
479
480 a = x.next();
481 }
482 true
483 }
484 }
485
486 impl<T: TotalOrd> MutableSet<T> for TreeSet<T> {
487 /// Add a value to the set. Return true if the value was not already
488 /// present in the set.
489 #[inline]
490 fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()) }
491
492 /// Remove a value from the set. Return true if the value was
493 /// present in the set.
494 #[inline]
495 fn remove(&mut self, value: &T) -> bool { self.map.remove(value) }
496 }
497
498 impl<T: TotalOrd> TreeSet<T> {
499 /// Create an empty TreeSet
500 #[inline]
501 pub fn new() -> TreeSet<T> { TreeSet{map: TreeMap::new()} }
502
503 /// Get a lazy iterator over the values in the set.
504 /// Requires that it be frozen (immutable).
505 #[inline]
506 pub fn iter<'a>(&'a self) -> TreeSetIterator<'a, T> {
507 TreeSetIterator{iter: self.map.iter()}
508 }
509
510 /// Get a lazy iterator over the values in the set.
511 /// Requires that it be frozen (immutable).
512 #[inline]
513 pub fn rev_iter<'a>(&'a self) -> TreeSetRevIterator<'a, T> {
514 TreeSetRevIterator{iter: self.map.rev_iter()}
515 }
516
517 /// Get a lazy iterator pointing to the first value not less than `v` (greater or equal).
518 /// If all elements in the set are less than `v` empty iterator is returned.
519 #[inline]
520 pub fn lower_bound_iter<'a>(&'a self, v: &T) -> TreeSetIterator<'a, T> {
521 TreeSetIterator{iter: self.map.lower_bound_iter(v)}
522 }
523
524 /// Get a lazy iterator pointing to the first value greater than `v`.
525 /// If all elements in the set are not greater than `v` empty iterator is returned.
526 #[inline]
527 pub fn upper_bound_iter<'a>(&'a self, v: &T) -> TreeSetIterator<'a, T> {
528 TreeSetIterator{iter: self.map.upper_bound_iter(v)}
529 }
530
531 /// Visit the values (in-order) representing the difference
532 pub fn difference<'a>(&'a self, other: &'a TreeSet<T>) -> Difference<'a, T> {
533 Difference{a: self.iter().peekable(), b: other.iter().peekable()}
534 }
535
536 /// Visit the values (in-order) representing the symmetric difference
537 pub fn symmetric_difference<'a>(&'a self, other: &'a TreeSet<T>)
538 -> SymDifference<'a, T> {
539 SymDifference{a: self.iter().peekable(), b: other.iter().peekable()}
540 }
541
542 /// Visit the values (in-order) representing the intersection
543 pub fn intersection<'a>(&'a self, other: &'a TreeSet<T>)
544 -> Intersection<'a, T> {
545 Intersection{a: self.iter().peekable(), b: other.iter().peekable()}
546 }
547
548 /// Visit the values (in-order) representing the union
549 pub fn union<'a>(&'a self, other: &'a TreeSet<T>) -> Union<'a, T> {
550 Union{a: self.iter().peekable(), b: other.iter().peekable()}
551 }
552 }
553
554 /// Lazy forward iterator over a set
555 pub struct TreeSetIterator<'self, T> {
556 priv iter: TreeMapIterator<'self, T, ()>
557 }
558
559 /// Lazy backward iterator over a set
560 pub struct TreeSetRevIterator<'self, T> {
561 priv iter: TreeMapRevIterator<'self, T, ()>
562 }
563
564 /// Lazy iterator producing elements in the set difference (in-order)
565 pub struct Difference<'self, T> {
566 priv a: Peekable<&'self T, TreeSetIterator<'self, T>>,
567 priv b: Peekable<&'self T, TreeSetIterator<'self, T>>,
568 }
569
570 /// Lazy iterator producing elements in the set symmetric difference (in-order)
571 pub struct SymDifference<'self, T> {
572 priv a: Peekable<&'self T, TreeSetIterator<'self, T>>,
573 priv b: Peekable<&'self T, TreeSetIterator<'self, T>>,
574 }
575
576 /// Lazy iterator producing elements in the set intersection (in-order)
577 pub struct Intersection<'self, T> {
578 priv a: Peekable<&'self T, TreeSetIterator<'self, T>>,
579 priv b: Peekable<&'self T, TreeSetIterator<'self, T>>,
580 }
581
582 /// Lazy iterator producing elements in the set intersection (in-order)
583 pub struct Union<'self, T> {
584 priv a: Peekable<&'self T, TreeSetIterator<'self, T>>,
585 priv b: Peekable<&'self T, TreeSetIterator<'self, T>>,
586 }
587
588 /// Compare `x` and `y`, but return `short` if x is None and `long` if y is None
589 fn cmp_opt<T: TotalOrd>(x: Option<&T>, y: Option<&T>,
590 short: Ordering, long: Ordering) -> Ordering {
591 match (x, y) {
592 (None , _ ) => short,
593 (_ , None ) => long,
594 (Some(x1), Some(y1)) => x1.cmp(y1),
595 }
596 }
597
598 impl<'self, T: TotalOrd> Iterator<&'self T> for Difference<'self, T> {
599 fn next(&mut self) -> Option<&'self T> {
600 loop {
601 match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) {
602 Less => return self.a.next(),
603 Equal => { self.a.next(); self.b.next(); }
604 Greater => { self.b.next(); }
605 }
606 }
607 }
608 }
609
610 impl<'self, T: TotalOrd> Iterator<&'self T> for SymDifference<'self, T> {
611 fn next(&mut self) -> Option<&'self T> {
612 loop {
613 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
614 Less => return self.a.next(),
615 Equal => { self.a.next(); self.b.next(); }
616 Greater => return self.b.next(),
617 }
618 }
619 }
620 }
621
622 impl<'self, T: TotalOrd> Iterator<&'self T> for Intersection<'self, T> {
623 fn next(&mut self) -> Option<&'self T> {
624 loop {
625 let o_cmp = match (self.a.peek(), self.b.peek()) {
626 (None , _ ) => None,
627 (_ , None ) => None,
628 (Some(a1), Some(b1)) => Some(a1.cmp(b1)),
629 };
630 match o_cmp {
631 None => return None,
632 Some(Less) => { self.a.next(); }
633 Some(Equal) => { self.b.next(); return self.a.next() }
634 Some(Greater) => { self.b.next(); }
635 }
636 }
637 }
638 }
639
640 impl<'self, T: TotalOrd> Iterator<&'self T> for Union<'self, T> {
641 fn next(&mut self) -> Option<&'self T> {
642 loop {
643 match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
644 Less => return self.a.next(),
645 Equal => { self.b.next(); return self.a.next() }
646 Greater => return self.b.next(),
647 }
648 }
649 }
650 }
651
652
653 // Nodes keep track of their level in the tree, starting at 1 in the
654 // leaves and with a red child sharing the level of the parent.
655 #[deriving(Clone)]
656 struct TreeNode<K, V> {
657 key: K,
658 value: V,
659 left: Option<~TreeNode<K, V>>,
660 right: Option<~TreeNode<K, V>>,
661 level: uint
662 }
663
664 impl<K: TotalOrd, V> TreeNode<K, V> {
665 /// Creates a new tree node.
666 #[inline]
667 pub fn new(key: K, value: V) -> TreeNode<K, V> {
668 TreeNode{key: key, value: value, left: None, right: None, level: 1}
669 }
670 }
671
672 fn mutate_values<'r, K: TotalOrd, V>(node: &'r mut Option<~TreeNode<K, V>>,
673 f: &fn(&'r K, &'r mut V) -> bool)
674 -> bool {
675 match *node {
676 Some(~TreeNode{key: ref key, value: ref mut value, left: ref mut left,
677 right: ref mut right, _}) => {
678 if !mutate_values(left, |k,v| f(k,v)) { return false }
679 if !f(key, value) { return false }
680 if !mutate_values(right, |k,v| f(k,v)) { return false }
681 }
682 None => return false
683 }
684 true
685 }
686
687 // Remove left horizontal link by rotating right
688 fn skew<K: TotalOrd, V>(node: &mut ~TreeNode<K, V>) {
689 if node.left.map_default(false, |x| x.level == node.level) {
690 let mut save = node.left.take_unwrap();
691 swap(&mut node.left, &mut save.right); // save.right now None
692 swap(node, &mut save);
693 node.right = Some(save);
694 }
695 }
696
697 // Remove dual horizontal link by rotating left and increasing level of
698 // the parent
699 fn split<K: TotalOrd, V>(node: &mut ~TreeNode<K, V>) {
700 if node.right.map_default(false,
701 |x| x.right.map_default(false, |y| y.level == node.level)) {
702 let mut save = node.right.take_unwrap();
703 swap(&mut node.right, &mut save.left); // save.left now None
704 save.level += 1;
705 swap(node, &mut save);
706 node.left = Some(save);
707 }
708 }
709
710 fn find_mut<'r, K: TotalOrd, V>(node: &'r mut Option<~TreeNode<K, V>>,
711 key: &K)
712 -> Option<&'r mut V> {
713 match *node {
714 Some(ref mut x) => {
715 match key.cmp(&x.key) {
716 Less => find_mut(&mut x.left, key),
717 Greater => find_mut(&mut x.right, key),
718 Equal => Some(&mut x.value),
719 }
720 }
721 None => None
722 }
723 }
724
725 fn insert<K: TotalOrd, V>(node: &mut Option<~TreeNode<K, V>>,
726 key: K, value: V) -> Option<V> {
727 match *node {
728 Some(ref mut save) => {
729 match key.cmp(&save.key) {
730 Less => {
731 let inserted = insert(&mut save.left, key, value);
732 skew(save);
733 split(save);
734 inserted
735 }
736 Greater => {
737 let inserted = insert(&mut save.right, key, value);
738 skew(save);
739 split(save);
740 inserted
741 }
742 Equal => {
743 save.key = key;
744 Some(replace(&mut save.value, value))
745 }
746 }
747 }
748 None => {
749 *node = Some(~TreeNode::new(key, value));
750 None
751 }
752 }
753 }
754
755 fn remove<K: TotalOrd, V>(node: &mut Option<~TreeNode<K, V>>,
756 key: &K) -> Option<V> {
757 fn heir_swap<K: TotalOrd, V>(node: &mut ~TreeNode<K, V>,
758 child: &mut Option<~TreeNode<K, V>>) {
759 // *could* be done without recursion, but it won't borrow check
760 for x in child.mut_iter() {
761 if x.right.is_some() {
762 heir_swap(node, &mut x.right);
763 } else {
764 swap(&mut node.key, &mut x.key);
765 swap(&mut node.value, &mut x.value);
766 }
767 }
768 }
769
770 match *node {
771 None => {
772 return None; // bottom of tree
773 }
774 Some(ref mut save) => {
775 let (ret, rebalance) = match key.cmp(&save.key) {
776 Less => (remove(&mut save.left, key), true),
777 Greater => (remove(&mut save.right, key), true),
778 Equal => {
779 if save.left.is_some() {
780 if save.right.is_some() {
781 let mut left = save.left.take_unwrap();
782 if left.right.is_some() {
783 heir_swap(save, &mut left.right);
784 } else {
785 swap(&mut save.key, &mut left.key);
786 swap(&mut save.value, &mut left.value);
787 }
788 save.left = Some(left);
789 (remove(&mut save.left, key), true)
790 } else {
791 let new = save.left.take_unwrap();
792 let ~TreeNode{value, _} = replace(save, new);
793 *save = save.left.take_unwrap();
794 (Some(value), true)
795 }
796 } else if save.right.is_some() {
797 let new = save.right.take_unwrap();
798 let ~TreeNode{value, _} = replace(save, new);
799 (Some(value), true)
800 } else {
801 (None, false)
802 }
803 }
804 };
805
806 if rebalance {
807 let left_level = save.left.map_default(0, |x| x.level);
808 let right_level = save.right.map_default(0, |x| x.level);
809
810 // re-balance, if necessary
811 if left_level < save.level - 1 || right_level < save.level - 1 {
812 save.level -= 1;
813
814 if right_level > save.level {
815 for x in save.right.mut_iter() { x.level = save.level }
816 }
817
818 skew(save);
819
820 for right in save.right.mut_iter() {
821 skew(right);
822 for x in right.right.mut_iter() { skew(x) }
823 }
824
825 split(save);
826 for x in save.right.mut_iter() { split(x) }
827 }
828
829 return ret;
830 }
831 }
832 }
833 return match node.take() {
834 Some(~TreeNode{value, _}) => Some(value), None => fail!()
835 };
836 }
837
838 impl<K: TotalOrd, V> FromIterator<(K, V)> for TreeMap<K, V> {
839 fn from_iterator<T: Iterator<(K, V)>>(iter: &mut T) -> TreeMap<K, V> {
840 let mut map = TreeMap::new();
841 map.extend(iter);
842 map
843 }
844 }
845
846 impl<K: TotalOrd, V> Extendable<(K, V)> for TreeMap<K, V> {
847 #[inline]
848 fn extend<T: Iterator<(K, V)>>(&mut self, iter: &mut T) {
849 for (k, v) in *iter {
850 self.insert(k, v);
851 }
852 }
853 }
854
855 impl<T: TotalOrd> FromIterator<T> for TreeSet<T> {
856 fn from_iterator<Iter: Iterator<T>>(iter: &mut Iter) -> TreeSet<T> {
857 let mut set = TreeSet::new();
858 set.extend(iter);
859 set
860 }
861 }
862
863 impl<T: TotalOrd> Extendable<T> for TreeSet<T> {
864 #[inline]
865 fn extend<Iter: Iterator<T>>(&mut self, iter: &mut Iter) {
866 for elem in *iter {
867 self.insert(elem);
868 }
869 }
870 }
871
872 #[cfg(test)]
873 mod test_treemap {
874
875 use super::*;
876
877 use std::rand::Rng;
878 use std::rand;
879
880 #[test]
881 fn find_empty() {
882 let m: TreeMap<int,int> = TreeMap::new();
883 assert!(m.find(&5) == None);
884 }
885
886 #[test]
887 fn find_not_found() {
888 let mut m = TreeMap::new();
889 assert!(m.insert(1, 2));
890 assert!(m.insert(5, 3));
891 assert!(m.insert(9, 3));
892 assert_eq!(m.find(&2), None);
893 }
894
895 #[test]
896 fn test_find_mut() {
897 let mut m = TreeMap::new();
898 assert!(m.insert(1, 12));
899 assert!(m.insert(2, 8));
900 assert!(m.insert(5, 14));
901 let new = 100;
902 match m.find_mut(&5) {
903 None => fail!(), Some(x) => *x = new
904 }
905 assert_eq!(m.find(&5), Some(&new));
906 }
907
908 #[test]
909 fn insert_replace() {
910 let mut m = TreeMap::new();
911 assert!(m.insert(5, 2));
912 assert!(m.insert(2, 9));
913 assert!(!m.insert(2, 11));
914 assert_eq!(m.find(&2).unwrap(), &11);
915 }
916
917 #[test]
918 fn test_clear() {
919 let mut m = TreeMap::new();
920 m.clear();
921 assert!(m.insert(5, 11));
922 assert!(m.insert(12, -3));
923 assert!(m.insert(19, 2));
924 m.clear();
925 assert!(m.find(&5).is_none());
926 assert!(m.find(&12).is_none());
927 assert!(m.find(&19).is_none());
928 assert!(m.is_empty());
929 }
930
931 #[test]
932 fn u8_map() {
933 let mut m = TreeMap::new();
934
935 let k1 = "foo".as_bytes();
936 let k2 = "bar".as_bytes();
937 let v1 = "baz".as_bytes();
938 let v2 = "foobar".as_bytes();
939
940 m.insert(k1.clone(), v1.clone());
941 m.insert(k2.clone(), v2.clone());
942
943 assert_eq!(m.find(&k2), Some(&v2));
944 assert_eq!(m.find(&k1), Some(&v1));
945 }
946
947 fn check_equal<K: Eq + TotalOrd, V: Eq>(ctrl: &[(K, V)],
948 map: &TreeMap<K, V>) {
949 assert_eq!(ctrl.is_empty(), map.is_empty());
950 for x in ctrl.iter() {
951 let &(ref k, ref v) = x;
952 assert!(map.find(k).unwrap() == v)
953 }
954 for (map_k, map_v) in map.iter() {
955 let mut found = false;
956 for x in ctrl.iter() {
957 let &(ref ctrl_k, ref ctrl_v) = x;
958 if *map_k == *ctrl_k {
959 assert!(*map_v == *ctrl_v);
960 found = true;
961 break;
962 }
963 }
964 assert!(found);
965 }
966 }
967
968 fn check_left<K: TotalOrd, V>(node: &Option<~TreeNode<K, V>>,
969 parent: &~TreeNode<K, V>) {
970 match *node {
971 Some(ref r) => {
972 assert_eq!(r.key.cmp(&parent.key), Less);
973 assert!(r.level == parent.level - 1); // left is black
974 check_left(&r.left, r);
975 check_right(&r.right, r, false);
976 }
977 None => assert!(parent.level == 1) // parent is leaf
978 }
979 }
980
981 fn check_right<K: TotalOrd, V>(node: &Option<~TreeNode<K, V>>,
982 parent: &~TreeNode<K, V>,
983 parent_red: bool) {
984 match *node {
985 Some(ref r) => {
986 assert_eq!(r.key.cmp(&parent.key), Greater);
987 let red = r.level == parent.level;
988 if parent_red { assert!(!red) } // no dual horizontal links
989 // Right red or black
990 assert!(red || r.level == parent.level - 1);
991 check_left(&r.left, r);
992 check_right(&r.right, r, red);
993 }
994 None => assert!(parent.level == 1) // parent is leaf
995 }
996 }
997
998 fn check_structure<K: TotalOrd, V>(map: &TreeMap<K, V>) {
999 match map.root {
1000 Some(ref r) => {
1001 check_left(&r.left, r);
1002 check_right(&r.right, r, false);
1003 }
1004 None => ()
1005 }
1006 }
1007
1008 #[test]
1009 fn test_rand_int() {
1010 let mut map: TreeMap<int,int> = TreeMap::new();
1011 let mut ctrl = ~[];
1012
1013 check_equal(ctrl, &map);
1014 assert!(map.find(&5).is_none());
1015
1016 let mut rng = rand::IsaacRng::new_seeded(&[42]);
1017
1018 do 3.times {
1019 do 90.times {
1020 let k = rng.gen();
1021 let v = rng.gen();
1022 if !ctrl.iter().any(|x| x == &(k, v)) {
1023 assert!(map.insert(k, v));
1024 ctrl.push((k, v));
1025 check_structure(&map);
1026 check_equal(ctrl, &map);
1027 }
1028 }
1029
1030 do 30.times {
1031 let r = rng.gen_integer_range(0, ctrl.len());
1032 let (key, _) = ctrl.remove(r);
1033 assert!(map.remove(&key));
1034 check_structure(&map);
1035 check_equal(ctrl, &map);
1036 }
1037 }
1038 }
1039
1040 #[test]
1041 fn test_len() {
1042 let mut m = TreeMap::new();
1043 assert!(m.insert(3, 6));
1044 assert_eq!(m.len(), 1);
1045 assert!(m.insert(0, 0));
1046 assert_eq!(m.len(), 2);
1047 assert!(m.insert(4, 8));
1048 assert_eq!(m.len(), 3);
1049 assert!(m.remove(&3));
1050 assert_eq!(m.len(), 2);
1051 assert!(!m.remove(&5));
1052 assert_eq!(m.len(), 2);
1053 assert!(m.insert(2, 4));
1054 assert_eq!(m.len(), 3);
1055 assert!(m.insert(1, 2));
1056 assert_eq!(m.len(), 4);
1057 }
1058
1059 #[test]
1060 fn test_iterator() {
1061 let mut m = TreeMap::new();
1062
1063 assert!(m.insert(3, 6));
1064 assert!(m.insert(0, 0));
1065 assert!(m.insert(4, 8));
1066 assert!(m.insert(2, 4));
1067 assert!(m.insert(1, 2));
1068
1069 let mut n = 0;
1070 for (k, v) in m.iter() {
1071 assert_eq!(*k, n);
1072 assert_eq!(*v, n * 2);
1073 n += 1;
1074 }
1075 assert_eq!(n, 5);
1076 }
1077
1078 #[test]
1079 fn test_interval_iteration() {
1080 let mut m = TreeMap::new();
1081 for i in range(1, 100) {
1082 assert!(m.insert(i * 2, i * 4));
1083 }
1084
1085 for i in range(1, 198) {
1086 let mut lb_it = m.lower_bound_iter(&i);
1087 let (&k, &v) = lb_it.next().unwrap();
1088 let lb = i + i % 2;
1089 assert_eq!(lb, k);
1090 assert_eq!(lb * 2, v);
1091
1092 let mut ub_it = m.upper_bound_iter(&i);
1093 let (&k, &v) = ub_it.next().unwrap();
1094 let ub = i + 2 - i % 2;
1095 assert_eq!(ub, k);
1096 assert_eq!(ub * 2, v);
1097 }
1098 let mut end_it = m.lower_bound_iter(&199);
1099 assert_eq!(end_it.next(), None);
1100 }
1101
1102 #[test]
1103 fn test_rev_iter() {
1104 let mut m = TreeMap::new();
1105
1106 assert!(m.insert(3, 6));
1107 assert!(m.insert(0, 0));
1108 assert!(m.insert(4, 8));
1109 assert!(m.insert(2, 4));
1110 assert!(m.insert(1, 2));
1111
1112 let mut n = 4;
1113 for (k, v) in m.rev_iter() {
1114 assert_eq!(*k, n);
1115 assert_eq!(*v, n * 2);
1116 n -= 1;
1117 }
1118 }
1119
1120 #[test]
1121 fn test_eq() {
1122 let mut a = TreeMap::new();
1123 let mut b = TreeMap::new();
1124
1125 assert!(a == b);
1126 assert!(a.insert(0, 5));
1127 assert!(a != b);
1128 assert!(b.insert(0, 4));
1129 assert!(a != b);
1130 assert!(a.insert(5, 19));
1131 assert!(a != b);
1132 assert!(!b.insert(0, 5));
1133 assert!(a != b);
1134 assert!(b.insert(5, 19));
1135 assert!(a == b);
1136 }
1137
1138 #[test]
1139 fn test_lt() {
1140 let mut a = TreeMap::new();
1141 let mut b = TreeMap::new();
1142
1143 assert!(!(a < b) && !(b < a));
1144 assert!(b.insert(0, 5));
1145 assert!(a < b);
1146 assert!(a.insert(0, 7));
1147 assert!(!(a < b) && b < a);
1148 assert!(b.insert(-2, 0));
1149 assert!(b < a);
1150 assert!(a.insert(-5, 2));
1151 assert!(a < b);
1152 assert!(a.insert(6, 2));
1153 assert!(a < b && !(b < a));
1154 }
1155
1156 #[test]
1157 fn test_ord() {
1158 let mut a = TreeMap::new();
1159 let mut b = TreeMap::new();
1160
1161 assert!(a <= b && a >= b);
1162 assert!(a.insert(1, 1));
1163 assert!(a > b && a >= b);
1164 assert!(b < a && b <= a);
1165 assert!(b.insert(2, 2));
1166 assert!(b > a && b >= a);
1167 assert!(a < b && a <= b);
1168 }
1169
1170 #[test]
1171 fn test_lazy_iterator() {
1172 let mut m = TreeMap::new();
1173 let (x1, y1) = (2, 5);
1174 let (x2, y2) = (9, 12);
1175 let (x3, y3) = (20, -3);
1176 let (x4, y4) = (29, 5);
1177 let (x5, y5) = (103, 3);
1178
1179 assert!(m.insert(x1, y1));
1180 assert!(m.insert(x2, y2));
1181 assert!(m.insert(x3, y3));
1182 assert!(m.insert(x4, y4));
1183 assert!(m.insert(x5, y5));
1184
1185 let m = m;
1186 let mut a = m.iter();
1187
1188 assert_eq!(a.next().unwrap(), (&x1, &y1));
1189 assert_eq!(a.next().unwrap(), (&x2, &y2));
1190 assert_eq!(a.next().unwrap(), (&x3, &y3));
1191 assert_eq!(a.next().unwrap(), (&x4, &y4));
1192 assert_eq!(a.next().unwrap(), (&x5, &y5));
1193
1194 assert!(a.next().is_none());
1195
1196 let mut b = m.iter();
1197
1198 let expected = [(&x1, &y1), (&x2, &y2), (&x3, &y3), (&x4, &y4),
1199 (&x5, &y5)];
1200 let mut i = 0;
1201
1202 for x in b {
1203 assert_eq!(expected[i], x);
1204 i += 1;
1205
1206 if i == 2 {
1207 break
1208 }
1209 }
1210
1211 for x in b {
1212 assert_eq!(expected[i], x);
1213 i += 1;
1214 }
1215 }
1216
1217 #[test]
1218 fn test_from_iter() {
1219 let xs = ~[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
1220
1221 let map: TreeMap<int, int> = xs.iter().map(|&x| x).collect();
1222
1223 for &(k, v) in xs.iter() {
1224 assert_eq!(map.find(&k), Some(&v));
1225 }
1226 }
1227
1228 }
1229
1230 #[cfg(test)]
1231 mod bench {
1232
1233 use super::*;
1234 use test::BenchHarness;
1235 use container::bench::*;
1236
1237 // Find seq
1238 #[bench]
1239 pub fn insert_rand_100(bh: &mut BenchHarness) {
1240 let mut m : TreeMap<uint,uint> = TreeMap::new();
1241 insert_rand_n(100, &mut m, bh);
1242 }
1243
1244 #[bench]
1245 pub fn insert_rand_10_000(bh: &mut BenchHarness) {
1246 let mut m : TreeMap<uint,uint> = TreeMap::new();
1247 insert_rand_n(10_000, &mut m, bh);
1248 }
1249
1250 // Insert seq
1251 #[bench]
1252 pub fn insert_seq_100(bh: &mut BenchHarness) {
1253 let mut m : TreeMap<uint,uint> = TreeMap::new();
1254 insert_seq_n(100, &mut m, bh);
1255 }
1256
1257 #[bench]
1258 pub fn insert_seq_10_000(bh: &mut BenchHarness) {
1259 let mut m : TreeMap<uint,uint> = TreeMap::new();
1260 insert_seq_n(10_000, &mut m, bh);
1261 }
1262
1263 // Find rand
1264 #[bench]
1265 pub fn find_rand_100(bh: &mut BenchHarness) {
1266 let mut m : TreeMap<uint,uint> = TreeMap::new();
1267 find_rand_n(100, &mut m, bh);
1268 }
1269
1270 #[bench]
1271 pub fn find_rand_10_000(bh: &mut BenchHarness) {
1272 let mut m : TreeMap<uint,uint> = TreeMap::new();
1273 find_rand_n(10_000, &mut m, bh);
1274 }
1275
1276 // Find seq
1277 #[bench]
1278 pub fn find_seq_100(bh: &mut BenchHarness) {
1279 let mut m : TreeMap<uint,uint> = TreeMap::new();
1280 find_seq_n(100, &mut m, bh);
1281 }
1282
1283 #[bench]
1284 pub fn find_seq_10_000(bh: &mut BenchHarness) {
1285 let mut m : TreeMap<uint,uint> = TreeMap::new();
1286 find_seq_n(10_000, &mut m, bh);
1287 }
1288 }
1289
1290 #[cfg(test)]
1291 mod test_set {
1292
1293 use super::*;
1294
1295 #[test]
1296 fn test_clear() {
1297 let mut s = TreeSet::new();
1298 s.clear();
1299 assert!(s.insert(5));
1300 assert!(s.insert(12));
1301 assert!(s.insert(19));
1302 s.clear();
1303 assert!(!s.contains(&5));
1304 assert!(!s.contains(&12));
1305 assert!(!s.contains(&19));
1306 assert!(s.is_empty());
1307 }
1308
1309 #[test]
1310 fn test_disjoint() {
1311 let mut xs = TreeSet::new();
1312 let mut ys = TreeSet::new();
1313 assert!(xs.is_disjoint(&ys));
1314 assert!(ys.is_disjoint(&xs));
1315 assert!(xs.insert(5));
1316 assert!(ys.insert(11));
1317 assert!(xs.is_disjoint(&ys));
1318 assert!(ys.is_disjoint(&xs));
1319 assert!(xs.insert(7));
1320 assert!(xs.insert(19));
1321 assert!(xs.insert(4));
1322 assert!(ys.insert(2));
1323 assert!(ys.insert(-11));
1324 assert!(xs.is_disjoint(&ys));
1325 assert!(ys.is_disjoint(&xs));
1326 assert!(ys.insert(7));
1327 assert!(!xs.is_disjoint(&ys));
1328 assert!(!ys.is_disjoint(&xs));
1329 }
1330
1331 #[test]
1332 fn test_subset_and_superset() {
1333 let mut a = TreeSet::new();
1334 assert!(a.insert(0));
1335 assert!(a.insert(5));
1336 assert!(a.insert(11));
1337 assert!(a.insert(7));
1338
1339 let mut b = TreeSet::new();
1340 assert!(b.insert(0));
1341 assert!(b.insert(7));
1342 assert!(b.insert(19));
1343 assert!(b.insert(250));
1344 assert!(b.insert(11));
1345 assert!(b.insert(200));
1346
1347 assert!(!a.is_subset(&b));
1348 assert!(!a.is_superset(&b));
1349 assert!(!b.is_subset(&a));
1350 assert!(!b.is_superset(&a));
1351
1352 assert!(b.insert(5));
1353
1354 assert!(a.is_subset(&b));
1355 assert!(!a.is_superset(&b));
1356 assert!(!b.is_subset(&a));
1357 assert!(b.is_superset(&a));
1358 }
1359
1360 #[test]
1361 fn test_iterator() {
1362 let mut m = TreeSet::new();
1363
1364 assert!(m.insert(3));
1365 assert!(m.insert(0));
1366 assert!(m.insert(4));
1367 assert!(m.insert(2));
1368 assert!(m.insert(1));
1369
1370 let mut n = 0;
1371 for x in m.iter() {
1372 assert_eq!(*x, n);
1373 n += 1
1374 }
1375 }
1376
1377 #[test]
1378 fn test_rev_iter() {
1379 let mut m = TreeSet::new();
1380
1381 assert!(m.insert(3));
1382 assert!(m.insert(0));
1383 assert!(m.insert(4));
1384 assert!(m.insert(2));
1385 assert!(m.insert(1));
1386
1387 let mut n = 4;
1388 for x in m.rev_iter() {
1389 assert_eq!(*x, n);
1390 n -= 1;
1391 }
1392 }
1393
1394 fn check(a: &[int], b: &[int], expected: &[int],
1395 f: &fn(&TreeSet<int>, &TreeSet<int>, f: &fn(&int) -> bool) -> bool) {
1396 let mut set_a = TreeSet::new();
1397 let mut set_b = TreeSet::new();
1398
1399 for x in a.iter() { assert!(set_a.insert(*x)) }
1400 for y in b.iter() { assert!(set_b.insert(*y)) }
1401
1402 let mut i = 0;
1403 do f(&set_a, &set_b) |x| {
1404 assert_eq!(*x, expected[i]);
1405 i += 1;
1406 true
1407 };
1408 assert_eq!(i, expected.len());
1409 }
1410
1411 #[test]
1412 fn test_intersection() {
1413 fn check_intersection(a: &[int], b: &[int], expected: &[int]) {
1414 check(a, b, expected, |x, y, f| x.intersection(y).advance(f))
1415 }
1416
1417 check_intersection([], [], []);
1418 check_intersection([1, 2, 3], [], []);
1419 check_intersection([], [1, 2, 3], []);
1420 check_intersection([2], [1, 2, 3], [2]);
1421 check_intersection([1, 2, 3], [2], [2]);
1422 check_intersection([11, 1, 3, 77, 103, 5, -5],
1423 [2, 11, 77, -9, -42, 5, 3],
1424 [3, 5, 11, 77]);
1425 }
1426
1427 #[test]
1428 fn test_difference() {
1429 fn check_difference(a: &[int], b: &[int], expected: &[int]) {
1430 check(a, b, expected, |x, y, f| x.difference(y).advance(f))
1431 }
1432
1433 check_difference([], [], []);
1434 check_difference([1, 12], [], [1, 12]);
1435 check_difference([], [1, 2, 3, 9], []);
1436 check_difference([1, 3, 5, 9, 11],
1437 [3, 9],
1438 [1, 5, 11]);
1439 check_difference([-5, 11, 22, 33, 40, 42],
1440 [-12, -5, 14, 23, 34, 38, 39, 50],
1441 [11, 22, 33, 40, 42]);
1442 }
1443
1444 #[test]
1445 fn test_symmetric_difference() {
1446 fn check_symmetric_difference(a: &[int], b: &[int],
1447 expected: &[int]) {
1448 check(a, b, expected, |x, y, f| x.symmetric_difference(y).advance(f))
1449 }
1450
1451 check_symmetric_difference([], [], []);
1452 check_symmetric_difference([1, 2, 3], [2], [1, 3]);
1453 check_symmetric_difference([2], [1, 2, 3], [1, 3]);
1454 check_symmetric_difference([1, 3, 5, 9, 11],
1455 [-2, 3, 9, 14, 22],
1456 [-2, 1, 5, 11, 14, 22]);
1457 }
1458
1459 #[test]
1460 fn test_union() {
1461 fn check_union(a: &[int], b: &[int],
1462 expected: &[int]) {
1463 check(a, b, expected, |x, y, f| x.union(y).advance(f))
1464 }
1465
1466 check_union([], [], []);
1467 check_union([1, 2, 3], [2], [1, 2, 3]);
1468 check_union([2], [1, 2, 3], [1, 2, 3]);
1469 check_union([1, 3, 5, 9, 11, 16, 19, 24],
1470 [-2, 1, 5, 9, 13, 19],
1471 [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24]);
1472 }
1473
1474 #[test]
1475 fn test_zip() {
1476 let mut x = TreeSet::new();
1477 x.insert(5u);
1478 x.insert(12u);
1479 x.insert(11u);
1480
1481 let mut y = TreeSet::new();
1482 y.insert("foo");
1483 y.insert("bar");
1484
1485 let x = x;
1486 let y = y;
1487 let mut z = x.iter().zip(y.iter());
1488
1489 // FIXME: #5801: this needs a type hint to compile...
1490 let result: Option<(&uint, & &'static str)> = z.next();
1491 assert_eq!(result.unwrap(), (&5u, & &"bar"));
1492
1493 let result: Option<(&uint, & &'static str)> = z.next();
1494 assert_eq!(result.unwrap(), (&11u, & &"foo"));
1495
1496 let result: Option<(&uint, & &'static str)> = z.next();
1497 assert!(result.is_none());
1498 }
1499
1500 #[test]
1501 fn test_swap() {
1502 let mut m = TreeMap::new();
1503 assert_eq!(m.swap(1, 2), None);
1504 assert_eq!(m.swap(1, 3), Some(2));
1505 assert_eq!(m.swap(1, 4), Some(3));
1506 }
1507
1508 #[test]
1509 fn test_pop() {
1510 let mut m = TreeMap::new();
1511 m.insert(1, 2);
1512 assert_eq!(m.pop(&1), Some(2));
1513 assert_eq!(m.pop(&1), None);
1514 }
1515
1516 #[test]
1517 fn test_from_iter() {
1518 let xs = ~[1, 2, 3, 4, 5, 6, 7, 8, 9];
1519
1520 let set: TreeSet<int> = xs.iter().map(|&x| x).collect();
1521
1522 for x in xs.iter() {
1523 assert!(set.contains(x));
1524 }
1525 }
1526 }
libextra/treemap.rs:655:19-655:19 -struct- definition:
#[deriving(Clone)]
struct TreeNode<K, V> {
references:-676: Some(~TreeNode{key: ref key, value: ref mut value, left: ref mut left,
655: #[deriving(Clone)]
354: let n = TreeNode {
699: fn split<K: TotalOrd, V>(node: &mut ~TreeNode<K, V>) {
798: let ~TreeNode{value, _} = replace(save, new);
94: let mut current: &'a Option<~TreeNode<K, V>> = &self.root;
233: priv node: &'self Option<~TreeNode<K, V>>,
668: TreeNode{key: key, value: value, left: None, right: None, level: 1}
336: priv stack: ~[TreeNode<K, V>],
710: fn find_mut<'r, K: TotalOrd, V>(node: &'r mut Option<~TreeNode<K, V>>,
834: Some(~TreeNode{value, _}) => Some(value), None => fail!()
672: fn mutate_values<'r, K: TotalOrd, V>(node: &'r mut Option<~TreeNode<K, V>>,
39: priv root: Option<~TreeNode<K, V>>,
755: fn remove<K: TotalOrd, V>(node: &mut Option<~TreeNode<K, V>>,
655: #[deriving(Clone)]
324: static none: Option<~TreeNode<K, V>> = None;
660: right: Option<~TreeNode<K, V>>,
792: let ~TreeNode{value, _} = replace(save, new);
725: fn insert<K: TotalOrd, V>(node: &mut Option<~TreeNode<K, V>>,
664: impl<K: TotalOrd, V> TreeNode<K, V> {
232: priv stack: ~[&'self ~TreeNode<K, V>],
659: left: Option<~TreeNode<K, V>>,
344: let TreeNode {
667: pub fn new(key: K, value: V) -> TreeNode<K, V> {
688: fn skew<K: TotalOrd, V>(node: &mut ~TreeNode<K, V>) {
757: fn heir_swap<K: TotalOrd, V>(node: &mut ~TreeNode<K, V>,
655: #[deriving(Clone)]
758: child: &mut Option<~TreeNode<K, V>>) {
655: #[deriving(Clone)]
libextra/treemap.rs:322:10-322:10 -fn- definition:
#[inline]
fn iter_traverse_complete<'a, K, V>(it: &mut TreeMapIterator<'a, K, V>) {
references:-182: iter_traverse_complete(&mut iter);
209: iter_traverse_complete(&mut iter);
188: iter_traverse_complete(&mut iter);
libextra/treemap.rs:570:80-570:80 -struct- definition:
/// Lazy iterator producing elements in the set symmetric difference (in-order)
pub struct SymDifference<'self, T> {
references:-610: impl<'self, T: TotalOrd> Iterator<&'self T> for SymDifference<'self, T> {
538: -> SymDifference<'a, T> {
539: SymDifference{a: self.iter().peekable(), b: other.iter().peekable()}
libextra/treemap.rs:724:1-724:1 -fn- definition:
fn insert<K: TotalOrd, V>(node: &mut Option<~TreeNode<K, V>>,
references:-737: let inserted = insert(&mut save.right, key, value);
731: let inserted = insert(&mut save.left, key, value);
120: let ret = insert(&mut self.root, key, value);
libextra/treemap.rs:554:37-554:37 -struct- definition:
/// Lazy forward iterator over a set
pub struct TreeSetIterator<'self, T> {
references:-567: priv b: Peekable<&'self T, TreeSetIterator<'self, T>>,
520: pub fn lower_bound_iter<'a>(&'a self, v: &T) -> TreeSetIterator<'a, T> {
578: priv a: Peekable<&'self T, TreeSetIterator<'self, T>>,
585: priv b: Peekable<&'self T, TreeSetIterator<'self, T>>,
579: priv b: Peekable<&'self T, TreeSetIterator<'self, T>>,
507: TreeSetIterator{iter: self.map.iter()}
573: priv b: Peekable<&'self T, TreeSetIterator<'self, T>>,
566: priv a: Peekable<&'self T, TreeSetIterator<'self, T>>,
584: priv a: Peekable<&'self T, TreeSetIterator<'self, T>>,
527: pub fn upper_bound_iter<'a>(&'a self, v: &T) -> TreeSetIterator<'a, T> {
572: priv a: Peekable<&'self T, TreeSetIterator<'self, T>>,
521: TreeSetIterator{iter: self.map.lower_bound_iter(v)}
506: pub fn iter<'a>(&'a self) -> TreeSetIterator<'a, T> {
384: impl<'self, T> Iterator<&'self T> for TreeSetIterator<'self, T> {
528: TreeSetIterator{iter: self.map.upper_bound_iter(v)}
libextra/treemap.rs:402:22-402:22 -struct- definition:
/// `TotalOrd` trait.
pub struct TreeSet<T> {
references:-549: pub fn union<'a>(&'a self, other: &'a TreeSet<T>) -> Union<'a, T> {
416: fn lt(&self, other: &TreeSet<T>) -> bool { self.map < other.map }
501: pub fn new() -> TreeSet<T> { TreeSet{map: TreeMap::new()} }
855: impl<T: TotalOrd> FromIterator<T> for TreeSet<T> {
425: impl<T: TotalOrd> Container for TreeSet<T> {
450: fn is_disjoint(&self, other: &TreeSet<T>) -> bool {
543: pub fn intersection<'a>(&'a self, other: &'a TreeSet<T>)
456: fn is_subset(&self, other: &TreeSet<T>) -> bool {
501: pub fn new() -> TreeSet<T> { TreeSet{map: TreeMap::new()} }
409: fn eq(&self, other: &TreeSet<T>) -> bool { self.map == other.map }
537: pub fn symmetric_difference<'a>(&'a self, other: &'a TreeSet<T>)
435: impl<T: TotalOrd> Mutable for TreeSet<T> {
863: impl<T: TotalOrd> Extendable<T> for TreeSet<T> {
486: impl<T: TotalOrd> MutableSet<T> for TreeSet<T> {
461: fn is_superset(&self, other: &TreeSet<T>) -> bool {
418: fn le(&self, other: &TreeSet<T>) -> bool { self.map <= other.map }
422: fn gt(&self, other: &TreeSet<T>) -> bool { self.map > other.map }
498: impl<T: TotalOrd> TreeSet<T> {
441: impl<T: TotalOrd> Set<T> for TreeSet<T> {
407: impl<T: Eq + TotalOrd> Eq for TreeSet<T> {
532: pub fn difference<'a>(&'a self, other: &'a TreeSet<T>) -> Difference<'a, T> {
420: fn ge(&self, other: &TreeSet<T>) -> bool { self.map >= other.map }
414: impl<T: Ord + TotalOrd> Ord for TreeSet<T> {
856: fn from_iterator<Iter: Iterator<T>>(iter: &mut Iter) -> TreeSet<T> {
411: fn ne(&self, other: &TreeSet<T>) -> bool { self.map != other.map }
libextra/serialize.rs:
891: > Decodable<D> for TreeSet<T> {
892: fn decode(d: &mut D) -> TreeSet<T> {
876: > Encodable<S> for TreeSet<T> {
libextra/treemap.rs:588:81-588:81 -fn- definition:
/// Compare `x` and `y`, but return `short` if x is None and `long` if y is None
fn cmp_opt<T: TotalOrd>(x: Option<&T>, y: Option<&T>,
references:-613: match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
643: match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
601: match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) {
libextra/treemap.rs:559:38-559:38 -struct- definition:
/// Lazy backward iterator over a set
pub struct TreeSetRevIterator<'self, T> {
references:-513: pub fn rev_iter<'a>(&'a self) -> TreeSetRevIterator<'a, T> {
392: impl<'self, T> Iterator<&'self T> for TreeSetRevIterator<'self, T> {
514: TreeSetRevIterator{iter: self.map.rev_iter()}
libextra/treemap.rs:757:4-757:4 -fn- definition:
fn heir_swap<K: TotalOrd, V>(node: &mut ~TreeNode<K, V>,
child: &mut Option<~TreeNode<K, V>>) {
references:-762: heir_swap(node, &mut x.right);
783: heir_swap(save, &mut left.right);
libextra/treemap.rs:334:75-334:75 -struct- definition:
/// Lazy forward iterator over a map that consumes the map while iterating
pub struct TreeMapMoveIterator<K, V> {
references:-217: pub fn move_iter(self) -> TreeMapMoveIterator<K, V> {
223: TreeMapMoveIterator {
340: impl<K, V> Iterator<(K, V)> for TreeMapMoveIterator<K,V> {
libextra/treemap.rs:50:30-50:30 -fn- definition:
// Lexicographical comparison
fn lt<K: Ord + TotalOrd, V: Ord>(a: &TreeMap<K, V>,
references:-72: fn gt(&self, other: &TreeMap<K, V>) -> bool { lt(other, self) }
66: fn lt(&self, other: &TreeMap<K, V>) -> bool { lt(self, other) }
68: fn le(&self, other: &TreeMap<K, V>) -> bool { !lt(other, self) }
70: fn ge(&self, other: &TreeMap<K, V>) -> bool { !lt(self, other) }
libextra/treemap.rs:564:70-564:70 -struct- definition:
/// Lazy iterator producing elements in the set difference (in-order)
pub struct Difference<'self, T> {
references:-532: pub fn difference<'a>(&'a self, other: &'a TreeSet<T>) -> Difference<'a, T> {
533: Difference{a: self.iter().peekable(), b: other.iter().peekable()}
598: impl<'self, T: TotalOrd> Iterator<&'self T> for Difference<'self, T> {
libextra/treemap.rs:687:49-687:49 -fn- definition:
// Remove left horizontal link by rotating right
fn skew<K: TotalOrd, V>(node: &mut ~TreeNode<K, V>) {
references:-738: skew(save);
818: skew(save);
821: skew(right);
822: for x in right.right.mut_iter() { skew(x) }
732: skew(save);
libextra/treemap.rs:37:19-37:19 -struct- definition:
#[deriving(Clone)]
pub struct TreeMap<K, V> {
references:-68: fn le(&self, other: &TreeMap<K, V>) -> bool { !lt(other, self) }
70: fn ge(&self, other: &TreeMap<K, V>) -> bool { !lt(self, other) }
134: impl<K: TotalOrd, V> TreeMap<K, V> {
218: let TreeMap { root: root, length: length } = self;
37: #[deriving(Clone)]
64: impl<K: Ord + TotalOrd, V: Ord> Ord for TreeMap<K, V> {
136: pub fn new() -> TreeMap<K, V> { TreeMap{root: None, length: 0} }
838: impl<K: TotalOrd, V> FromIterator<(K, V)> for TreeMap<K, V> {
37: #[deriving(Clone)]
52: b: &TreeMap<K, V>) -> bool {
839: fn from_iterator<T: Iterator<(K, V)>>(iter: &mut T) -> TreeMap<K, V> {
83: impl<K: TotalOrd, V> Mutable for TreeMap<K, V> {
404: priv map: TreeMap<T, ()>
43: impl<K: Eq + TotalOrd, V: Eq> Eq for TreeMap<K, V> {
37: #[deriving(Clone)]
136: pub fn new() -> TreeMap<K, V> { TreeMap{root: None, length: 0} }
91: impl<K: TotalOrd, V> Map<K, V> for TreeMap<K, V> {
110: impl<K: TotalOrd, V> MutableMap<K, V> for TreeMap<K, V> {
51: fn lt<K: Ord + TotalOrd, V: Ord>(a: &TreeMap<K, V>,
75: impl<K: TotalOrd, V> Container for TreeMap<K, V> {
66: fn lt(&self, other: &TreeMap<K, V>) -> bool { lt(self, other) }
44: fn eq(&self, other: &TreeMap<K, V>) -> bool {
846: impl<K: TotalOrd, V> Extendable<(K, V)> for TreeMap<K, V> {
37: #[deriving(Clone)]
72: fn gt(&self, other: &TreeMap<K, V>) -> bool { lt(other, self) }
libextra/json.rs:
44: pub type Object = TreeMap<~str, Json>;
1286: impl<A:ToJson> ToJson for TreeMap<~str, A> {
libextra/workcache.rs:
113: struct KindMap(TreeMap<~str, ~str>);
226: type FreshnessMap = TreeMap<~str,extern fn(&str,&str)->bool>;
110: struct WorkMap(TreeMap<~str, KindMap>);
(132)libextra/test.rs:
(103)(121)libextra/serialize.rs:
(842)(860)(859)libextra/treemap.rs:310:10-310:10 -fn- definition:
#[inline]
fn iter_traverse_right<'a, K, V>(it: &mut TreeMapIterator<'a, K, V>) {
references:-180: Greater => iter_traverse_right(&mut iter),
204: Greater => iter_traverse_right(&mut iter),
205: Equal => iter_traverse_right(&mut iter)
libextra/treemap.rs:582:72-582:72 -struct- definition:
/// Lazy iterator producing elements in the set intersection (in-order)
pub struct Union<'self, T> {
references:-549: pub fn union<'a>(&'a self, other: &'a TreeSet<T>) -> Union<'a, T> {
640: impl<'self, T: TotalOrd> Iterator<&'self T> for Union<'self, T> {
550: Union{a: self.iter().peekable(), b: other.iter().peekable()}
libextra/treemap.rs:276:38-276:38 -struct- definition:
/// Lazy backward iterator over a map
pub struct TreeMapRevIterator<'self, K, V> {
references:-157: TreeMapRevIterator{iter: self.iter()}
281: impl<'self, K, V> Iterator<(&'self K, &'self V)> for TreeMapRevIterator<'self, K, V> {
156: pub fn rev_iter<'a>(&'a self) -> TreeMapRevIterator<'a, K, V> {
561: priv iter: TreeMapRevIterator<'self, T, ()>
libextra/treemap.rs:671:1-671:1 -fn- definition:
fn mutate_values<'r, K: TotalOrd, V>(node: &'r mut Option<~TreeNode<K, V>>,
references:-680: if !mutate_values(right, |k,v| f(k,v)) { return false }
678: if !mutate_values(left, |k,v| f(k,v)) { return false }
140: mutate_values(&mut self.root, f)
libextra/treemap.rs:709:1-709:1 -fn- definition:
fn find_mut<'r, K: TotalOrd, V>(node: &'r mut Option<~TreeNode<K, V>>,
references:-716: Less => find_mut(&mut x.left, key),
114: find_mut(&mut self.root, key)
717: Greater => find_mut(&mut x.right, key),
libextra/treemap.rs:576:72-576:72 -struct- definition:
/// Lazy iterator producing elements in the set intersection (in-order)
pub struct Intersection<'self, T> {
references:-544: -> Intersection<'a, T> {
622: impl<'self, T: TotalOrd> Iterator<&'self T> for Intersection<'self, T> {
545: Intersection{a: self.iter().peekable(), b: other.iter().peekable()}
libextra/treemap.rs:698:14-698:14 -fn- definition:
// the parent
fn split<K: TotalOrd, V>(node: &mut ~TreeNode<K, V>) {
references:-825: split(save);
739: split(save);
733: split(save);
826: for x in save.right.mut_iter() { split(x) }
libextra/treemap.rs:303:10-303:10 -fn- definition:
#[inline]
fn iter_traverse_left<'a, K, V>(it: &mut TreeMapIterator<'a, K, V>) {
references:-203: Less => iter_traverse_left(&mut iter),
179: Less => iter_traverse_left(&mut iter),
libextra/treemap.rs:754:1-754:1 -fn- definition:
fn remove<K: TotalOrd, V>(node: &mut Option<~TreeNode<K, V>>,
references:-789: (remove(&mut save.left, key), true)
777: Greater => (remove(&mut save.right, key), true),
776: Less => (remove(&mut save.left, key), true),
128: let ret = remove(&mut self.root, key);
libextra/treemap.rs:230:37-230:37 -struct- definition:
/// Lazy forward iterator over a map
pub struct TreeMapIterator<'self, K, V> {
references:-278: priv iter: TreeMapIterator<'self, K, V>,
556: priv iter: TreeMapIterator<'self, T, ()>
198: let mut iter: TreeMapIterator<'a, K, V> = self.iter_for_traversal();
145: pub fn iter<'a>(&'a self) -> TreeMapIterator<'a, K, V> {
304: fn iter_traverse_left<'a, K, V>(it: &mut TreeMapIterator<'a, K, V>) {
323: fn iter_traverse_complete<'a, K, V>(it: &mut TreeMapIterator<'a, K, V>) {
311: fn iter_traverse_right<'a, K, V>(it: &mut TreeMapIterator<'a, K, V>) {
162: fn iter_for_traversal<'a>(&'a self) -> TreeMapIterator<'a, K, V> {
238: impl<'self, K, V> TreeMapIterator<'self, K, V> {
173: pub fn lower_bound_iter<'a>(&'a self, k: &K) -> TreeMapIterator<'a, K, V> {
146: TreeMapIterator {
197: pub fn upper_bound_iter<'a>(&'a self, k: &K) -> TreeMapIterator<'a, K, V> {
262: impl<'self, K, V> Iterator<(&'self K, &'self V)> for TreeMapIterator<'self, K, V> {
174: let mut iter: TreeMapIterator<'a, K, V> = self.iter_for_traversal();
163: TreeMapIterator {