/
treemap.rs
1826 lines (1570 loc) · 52.9 KB
/
treemap.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! An ordered map and set implemented as self-balancing binary search
//! trees. The only requirement for the types is that the key implements
//! `Ord`.
use core::prelude::*;
use alloc::owned::Box;
use core::default::Default;
use core::fmt;
use core::fmt::Show;
use core::iter::Peekable;
use core::iter;
use core::mem::{replace, swap};
use core::ptr;
use {Collection, Mutable, Set, MutableSet, MutableMap, Map};
use vec::Vec;
// This is implemented as an AA tree, which is a simplified variation of
// a red-black tree where red (horizontal) nodes can only be added
// as a right child. The time complexity is the same, and re-balancing
// operations are more frequent but also cheaper.
// Future improvements:
// range search - O(log n) retrieval of an iterator from some key
// (possibly) implement the overloads Python does for sets:
// * intersection: &
// * difference: -
// * symmetric difference: ^
// * union: |
// These would be convenient since the methods work like `each`
#[allow(missing_doc)]
#[deriving(Clone)]
pub struct TreeMap<K, V> {
root: Option<Box<TreeNode<K, V>>>,
length: uint
}
impl<K: PartialEq + Ord, V: PartialEq> PartialEq for TreeMap<K, V> {
fn eq(&self, other: &TreeMap<K, V>) -> bool {
self.len() == other.len() &&
self.iter().zip(other.iter()).all(|(a, b)| a == b)
}
}
// Lexicographical comparison
fn lt<K: PartialOrd + Ord, V: PartialOrd>(a: &TreeMap<K, V>,
b: &TreeMap<K, V>) -> bool {
// the Zip iterator is as long as the shortest of a and b.
for ((key_a, value_a), (key_b, value_b)) in a.iter().zip(b.iter()) {
if *key_a < *key_b { return true; }
if *key_a > *key_b { return false; }
if *value_a < *value_b { return true; }
if *value_a > *value_b { return false; }
}
a.len() < b.len()
}
impl<K: PartialOrd + Ord, V: PartialOrd> PartialOrd for TreeMap<K, V> {
#[inline]
fn lt(&self, other: &TreeMap<K, V>) -> bool { lt(self, other) }
}
impl<K: Ord + Show, V: Show> Show for TreeMap<K, V> {
#[cfg(stage0)]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, r"\{"));
for (i, (k, v)) in self.iter().enumerate() {
if i != 0 { try!(write!(f, ", ")); }
try!(write!(f, "{}: {}", *k, *v));
}
write!(f, r"\}")
}
#[cfg(not(stage0))]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "{{"));
for (i, (k, v)) in self.iter().enumerate() {
if i != 0 { try!(write!(f, ", ")); }
try!(write!(f, "{}: {}", *k, *v));
}
write!(f, "}}")
}
}
impl<K: Ord, V> Collection for TreeMap<K, V> {
fn len(&self) -> uint { self.length }
}
impl<K: Ord, V> Mutable for TreeMap<K, V> {
fn clear(&mut self) {
self.root = None;
self.length = 0
}
}
impl<K: Ord, V> Map<K, V> for TreeMap<K, V> {
fn find<'a>(&'a self, key: &K) -> Option<&'a V> {
let mut current: &'a Option<Box<TreeNode<K, V>>> = &self.root;
loop {
match *current {
Some(ref r) => {
match key.cmp(&r.key) {
Less => current = &r.left,
Greater => current = &r.right,
Equal => return Some(&r.value)
}
}
None => return None
}
}
}
}
impl<K: Ord, V> MutableMap<K, V> for TreeMap<K, V> {
#[inline]
fn find_mut<'a>(&'a mut self, key: &K) -> Option<&'a mut V> {
find_mut(&mut self.root, key)
}
fn swap(&mut self, key: K, value: V) -> Option<V> {
let ret = insert(&mut self.root, key, value);
if ret.is_none() { self.length += 1 }
ret
}
fn pop(&mut self, key: &K) -> Option<V> {
let ret = remove(&mut self.root, key);
if ret.is_some() { self.length -= 1 }
ret
}
}
impl<K: Ord, V> Default for TreeMap<K,V> {
#[inline]
fn default() -> TreeMap<K, V> { TreeMap::new() }
}
impl<K: Ord, V> TreeMap<K, V> {
/// Create an empty TreeMap
pub fn new() -> TreeMap<K, V> { TreeMap{root: None, length: 0} }
/// Get a lazy iterator over the key-value pairs in the map.
/// Requires that it be frozen (immutable).
pub fn iter<'a>(&'a self) -> Entries<'a, K, V> {
Entries {
stack: vec!(),
node: deref(&self.root),
remaining_min: self.length,
remaining_max: self.length
}
}
/// Get a lazy reverse iterator over the key-value pairs in the map.
/// Requires that it be frozen (immutable).
pub fn rev_iter<'a>(&'a self) -> RevEntries<'a, K, V> {
RevEntries{iter: self.iter()}
}
/// Get a lazy forward iterator over the key-value pairs in the
/// map, with the values being mutable.
pub fn mut_iter<'a>(&'a mut self) -> MutEntries<'a, K, V> {
MutEntries {
stack: vec!(),
node: mut_deref(&mut self.root),
remaining_min: self.length,
remaining_max: self.length
}
}
/// Get a lazy reverse iterator over the key-value pairs in the
/// map, with the values being mutable.
pub fn mut_rev_iter<'a>(&'a mut self) -> RevMutEntries<'a, K, V> {
RevMutEntries{iter: self.mut_iter()}
}
/// Get a lazy iterator that consumes the treemap.
pub fn move_iter(self) -> MoveEntries<K, V> {
let TreeMap { root: root, length: length } = self;
let stk = match root {
None => vec!(),
Some(box tn) => vec!(tn)
};
MoveEntries {
stack: stk,
remaining: length
}
}
}
// range iterators.
macro_rules! bound_setup {
// initialiser of the iterator to manipulate
($iter:expr,
// whether we are looking for the lower or upper bound.
$is_lower_bound:expr) => {
{
let mut iter = $iter;
loop {
if !iter.node.is_null() {
let node_k = unsafe {&(*iter.node).key};
match k.cmp(node_k) {
Less => iter.traverse_left(),
Greater => iter.traverse_right(),
Equal => {
if $is_lower_bound {
iter.traverse_complete();
return iter;
} else {
iter.traverse_right()
}
}
}
} else {
iter.traverse_complete();
return iter;
}
}
}
}
}
impl<K: Ord, V> TreeMap<K, V> {
/// Get a lazy iterator that should be initialized using
/// `traverse_left`/`traverse_right`/`traverse_complete`.
fn iter_for_traversal<'a>(&'a self) -> Entries<'a, K, V> {
Entries {
stack: vec!(),
node: deref(&self.root),
remaining_min: 0,
remaining_max: self.length
}
}
/// Return a lazy iterator to the first key-value pair whose key is not less than `k`
/// If all keys in map are less than `k` an empty iterator is returned.
pub fn lower_bound<'a>(&'a self, k: &K) -> Entries<'a, K, V> {
bound_setup!(self.iter_for_traversal(), true)
}
/// Return a lazy iterator to the first key-value pair whose key is greater than `k`
/// If all keys in map are not greater than `k` an empty iterator is returned.
pub fn upper_bound<'a>(&'a self, k: &K) -> Entries<'a, K, V> {
bound_setup!(self.iter_for_traversal(), false)
}
/// Get a lazy iterator that should be initialized using
/// `traverse_left`/`traverse_right`/`traverse_complete`.
fn mut_iter_for_traversal<'a>(&'a mut self) -> MutEntries<'a, K, V> {
MutEntries {
stack: vec!(),
node: mut_deref(&mut self.root),
remaining_min: 0,
remaining_max: self.length
}
}
/// Return a lazy value iterator to the first key-value pair (with
/// the value being mutable) whose key is not less than `k`.
///
/// If all keys in map are less than `k` an empty iterator is
/// returned.
pub fn mut_lower_bound<'a>(&'a mut self, k: &K) -> MutEntries<'a, K, V> {
bound_setup!(self.mut_iter_for_traversal(), true)
}
/// Return a lazy iterator to the first key-value pair (with the
/// value being mutable) whose key is greater than `k`.
///
/// If all keys in map are not greater than `k` an empty iterator
/// is returned.
pub fn mut_upper_bound<'a>(&'a mut self, k: &K) -> MutEntries<'a, K, V> {
bound_setup!(self.mut_iter_for_traversal(), false)
}
}
/// Lazy forward iterator over a map
pub struct Entries<'a, K, V> {
stack: Vec<&'a TreeNode<K, V>>,
// See the comment on MutEntries; this is just to allow
// code-sharing (for this immutable-values iterator it *could* very
// well be Option<&'a TreeNode<K,V>>).
node: *TreeNode<K, V>,
remaining_min: uint,
remaining_max: uint
}
/// Lazy backward iterator over a map
pub struct RevEntries<'a, K, V> {
iter: Entries<'a, K, V>,
}
/// Lazy forward iterator over a map that allows for the mutation of
/// the values.
pub struct MutEntries<'a, K, V> {
stack: Vec<&'a mut TreeNode<K, V>>,
// Unfortunately, we require some unsafe-ness to get around the
// fact that we would be storing a reference *into* one of the
// nodes in the stack.
//
// As far as the compiler knows, this would let us invalidate the
// reference by assigning a new value to this node's position in
// its parent, which would cause this current one to be
// deallocated so this reference would be invalid. (i.e. the
// compilers complaints are 100% correct.)
//
// However, as far as you humans reading this code know (or are
// about to know, if you haven't read far enough down yet), we are
// only reading from the TreeNode.{left,right} fields. the only
// thing that is ever mutated is the .value field (although any
// actual mutation that happens is done externally, by the
// iterator consumer). So, don't be so concerned, rustc, we've got
// it under control.
//
// (This field can legitimately be null.)
node: *mut TreeNode<K, V>,
remaining_min: uint,
remaining_max: uint
}
/// Lazy backward iterator over a map
pub struct RevMutEntries<'a, K, V> {
iter: MutEntries<'a, K, V>,
}
// FIXME #5846 we want to be able to choose between &x and &mut x
// (with many different `x`) below, so we need to optionally pass mut
// as a tt, but the only thing we can do with a `tt` is pass them to
// other macros, so this takes the `& <mutability> <operand>` token
// sequence and forces their evaluation as an expression.
macro_rules! addr { ($e:expr) => { $e }}
// putting an optional mut into type signatures
macro_rules! item { ($i:item) => { $i }}
macro_rules! define_iterator {
($name:ident,
$rev_name:ident,
// the function to go from &m Option<Box<TreeNode>> to *m TreeNode
deref = $deref:ident,
// see comment on `addr!`, this is just an optional `mut`, but
// there's no support for 0-or-1 repeats.
addr_mut = $($addr_mut:tt)*
) => {
// private methods on the forward iterator (item!() for the
// addr_mut in the next_ return value)
item!(impl<'a, K, V> $name<'a, K, V> {
#[inline(always)]
fn next_(&mut self, forward: bool) -> Option<(&'a K, &'a $($addr_mut)* V)> {
while !self.stack.is_empty() || !self.node.is_null() {
if !self.node.is_null() {
let node = unsafe {addr!(& $($addr_mut)* *self.node)};
{
let next_node = if forward {
addr!(& $($addr_mut)* node.left)
} else {
addr!(& $($addr_mut)* node.right)
};
self.node = $deref(next_node);
}
self.stack.push(node);
} else {
let node = self.stack.pop().unwrap();
let next_node = if forward {
addr!(& $($addr_mut)* node.right)
} else {
addr!(& $($addr_mut)* node.left)
};
self.node = $deref(next_node);
self.remaining_max -= 1;
if self.remaining_min > 0 {
self.remaining_min -= 1;
}
return Some((&node.key, addr!(& $($addr_mut)* node.value)));
}
}
None
}
/// traverse_left, traverse_right and traverse_complete are
/// used to initialize Entries/MutEntries
/// pointing to element inside tree structure.
///
/// They should be used in following manner:
/// - create iterator using TreeMap::[mut_]iter_for_traversal
/// - find required node using `traverse_left`/`traverse_right`
/// (current node is `Entries::node` field)
/// - complete initialization with `traverse_complete`
///
/// After this, iteration will start from `self.node`. If
/// `self.node` is None iteration will start from last
/// node from which we traversed left.
#[inline]
fn traverse_left(&mut self) {
let node = unsafe {addr!(& $($addr_mut)* *self.node)};
self.node = $deref(addr!(& $($addr_mut)* node.left));
self.stack.push(node);
}
#[inline]
fn traverse_right(&mut self) {
let node = unsafe {addr!(& $($addr_mut)* *self.node)};
self.node = $deref(addr!(& $($addr_mut)* node.right));
}
#[inline]
fn traverse_complete(&mut self) {
if !self.node.is_null() {
unsafe {
self.stack.push(addr!(& $($addr_mut)* *self.node));
}
self.node = ptr::RawPtr::null();
}
}
})
// the forward Iterator impl.
item!(impl<'a, K, V> Iterator<(&'a K, &'a $($addr_mut)* V)> for $name<'a, K, V> {
/// Advance the iterator to the next node (in order) and return a
/// tuple with a reference to the key and value. If there are no
/// more nodes, return `None`.
fn next(&mut self) -> Option<(&'a K, &'a $($addr_mut)* V)> {
self.next_(true)
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
(self.remaining_min, Some(self.remaining_max))
}
})
// the reverse Iterator impl.
item!(impl<'a, K, V> Iterator<(&'a K, &'a $($addr_mut)* V)> for $rev_name<'a, K, V> {
fn next(&mut self) -> Option<(&'a K, &'a $($addr_mut)* V)> {
self.iter.next_(false)
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
self.iter.size_hint()
}
})
}
} // end of define_iterator
define_iterator! {
Entries,
RevEntries,
deref = deref,
// immutable, so no mut
addr_mut =
}
define_iterator! {
MutEntries,
RevMutEntries,
deref = mut_deref,
addr_mut = mut
}
fn deref<'a, K, V>(node: &'a Option<Box<TreeNode<K, V>>>) -> *TreeNode<K, V> {
match *node {
Some(ref n) => {
let n: &TreeNode<K, V> = *n;
n as *TreeNode<K, V>
}
None => ptr::null()
}
}
fn mut_deref<K, V>(x: &mut Option<Box<TreeNode<K, V>>>)
-> *mut TreeNode<K, V> {
match *x {
Some(ref mut n) => {
let n: &mut TreeNode<K, V> = *n;
n as *mut TreeNode<K, V>
}
None => ptr::mut_null()
}
}
/// Lazy forward iterator over a map that consumes the map while iterating
pub struct MoveEntries<K, V> {
stack: Vec<TreeNode<K, V>>,
remaining: uint
}
impl<K, V> Iterator<(K, V)> for MoveEntries<K,V> {
#[inline]
fn next(&mut self) -> Option<(K, V)> {
while !self.stack.is_empty() {
let TreeNode {
key: key,
value: value,
left: left,
right: right,
level: level
} = self.stack.pop().unwrap();
match left {
Some(box left) => {
let n = TreeNode {
key: key,
value: value,
left: None,
right: right,
level: level
};
self.stack.push(n);
self.stack.push(left);
}
None => {
match right {
Some(box right) => self.stack.push(right),
None => ()
}
self.remaining -= 1;
return Some((key, value))
}
}
}
None
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
(self.remaining, Some(self.remaining))
}
}
impl<'a, T> Iterator<&'a T> for SetItems<'a, T> {
#[inline]
fn next(&mut self) -> Option<&'a T> {
self.iter.next().map(|(value, _)| value)
}
}
impl<'a, T> Iterator<&'a T> for RevSetItems<'a, T> {
#[inline]
fn next(&mut self) -> Option<&'a T> {
self.iter.next().map(|(value, _)| value)
}
}
/// A implementation of the `Set` trait on top of the `TreeMap` container. The
/// only requirement is that the type of the elements contained ascribes to the
/// `Ord` trait.
#[deriving(Clone)]
pub struct TreeSet<T> {
map: TreeMap<T, ()>
}
impl<T: PartialEq + Ord> PartialEq for TreeSet<T> {
#[inline]
fn eq(&self, other: &TreeSet<T>) -> bool { self.map == other.map }
}
impl<T: PartialOrd + Ord> PartialOrd for TreeSet<T> {
#[inline]
fn lt(&self, other: &TreeSet<T>) -> bool { self.map < other.map }
}
impl<T: Ord + Show> Show for TreeSet<T> {
#[cfg(stage0)]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, r"\{"));
for (i, x) in self.iter().enumerate() {
if i != 0 { try!(write!(f, ", ")); }
try!(write!(f, "{}", *x));
}
write!(f, r"\}")
}
#[cfg(not(stage0))]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "{{"));
for (i, x) in self.iter().enumerate() {
if i != 0 { try!(write!(f, ", ")); }
try!(write!(f, "{}", *x));
}
write!(f, "}}")
}
}
impl<T: Ord> Collection for TreeSet<T> {
#[inline]
fn len(&self) -> uint { self.map.len() }
}
impl<T: Ord> Mutable for TreeSet<T> {
#[inline]
fn clear(&mut self) { self.map.clear() }
}
impl<T: Ord> Set<T> for TreeSet<T> {
#[inline]
fn contains(&self, value: &T) -> bool {
self.map.contains_key(value)
}
fn is_disjoint(&self, other: &TreeSet<T>) -> bool {
self.intersection(other).next().is_none()
}
fn is_subset(&self, other: &TreeSet<T>) -> bool {
let mut x = self.iter();
let mut y = other.iter();
let mut a = x.next();
let mut b = y.next();
while a.is_some() {
if b.is_none() {
return false;
}
let a1 = a.unwrap();
let b1 = b.unwrap();
match b1.cmp(a1) {
Less => (),
Greater => return false,
Equal => a = x.next(),
}
b = y.next();
}
true
}
}
impl<T: Ord> MutableSet<T> for TreeSet<T> {
#[inline]
fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()) }
#[inline]
fn remove(&mut self, value: &T) -> bool { self.map.remove(value) }
}
impl<T: Ord> Default for TreeSet<T> {
#[inline]
fn default() -> TreeSet<T> { TreeSet::new() }
}
impl<T: Ord> TreeSet<T> {
/// Create an empty TreeSet
#[inline]
pub fn new() -> TreeSet<T> { TreeSet{map: TreeMap::new()} }
/// Get a lazy iterator over the values in the set.
/// Requires that it be frozen (immutable).
#[inline]
pub fn iter<'a>(&'a self) -> SetItems<'a, T> {
SetItems{iter: self.map.iter()}
}
/// Get a lazy iterator over the values in the set.
/// Requires that it be frozen (immutable).
#[inline]
pub fn rev_iter<'a>(&'a self) -> RevSetItems<'a, T> {
RevSetItems{iter: self.map.rev_iter()}
}
/// Get a lazy iterator that consumes the set.
#[inline]
pub fn move_iter(self) -> MoveSetItems<T> {
self.map.move_iter().map(|(value, _)| value)
}
/// Get a lazy iterator pointing to the first value not less than `v` (greater or equal).
/// If all elements in the set are less than `v` empty iterator is returned.
#[inline]
pub fn lower_bound<'a>(&'a self, v: &T) -> SetItems<'a, T> {
SetItems{iter: self.map.lower_bound(v)}
}
/// Get a lazy iterator pointing to the first value greater than `v`.
/// If all elements in the set are not greater than `v` empty iterator is returned.
#[inline]
pub fn upper_bound<'a>(&'a self, v: &T) -> SetItems<'a, T> {
SetItems{iter: self.map.upper_bound(v)}
}
/// Visit the values (in-order) representing the difference
pub fn difference<'a>(&'a self, other: &'a TreeSet<T>) -> DifferenceItems<'a, T> {
DifferenceItems{a: self.iter().peekable(), b: other.iter().peekable()}
}
/// Visit the values (in-order) representing the symmetric difference
pub fn symmetric_difference<'a>(&'a self, other: &'a TreeSet<T>)
-> SymDifferenceItems<'a, T> {
SymDifferenceItems{a: self.iter().peekable(), b: other.iter().peekable()}
}
/// Visit the values (in-order) representing the intersection
pub fn intersection<'a>(&'a self, other: &'a TreeSet<T>)
-> IntersectionItems<'a, T> {
IntersectionItems{a: self.iter().peekable(), b: other.iter().peekable()}
}
/// Visit the values (in-order) representing the union
pub fn union<'a>(&'a self, other: &'a TreeSet<T>) -> UnionItems<'a, T> {
UnionItems{a: self.iter().peekable(), b: other.iter().peekable()}
}
}
/// Lazy forward iterator over a set
pub struct SetItems<'a, T> {
iter: Entries<'a, T, ()>
}
/// Lazy backward iterator over a set
pub struct RevSetItems<'a, T> {
iter: RevEntries<'a, T, ()>
}
/// Lazy forward iterator over a set that consumes the set while iterating
pub type MoveSetItems<T> = iter::Map<'static, (T, ()), T, MoveEntries<T, ()>>;
/// Lazy iterator producing elements in the set difference (in-order)
pub struct DifferenceItems<'a, T> {
a: Peekable<&'a T, SetItems<'a, T>>,
b: Peekable<&'a T, SetItems<'a, T>>,
}
/// Lazy iterator producing elements in the set symmetric difference (in-order)
pub struct SymDifferenceItems<'a, T> {
a: Peekable<&'a T, SetItems<'a, T>>,
b: Peekable<&'a T, SetItems<'a, T>>,
}
/// Lazy iterator producing elements in the set intersection (in-order)
pub struct IntersectionItems<'a, T> {
a: Peekable<&'a T, SetItems<'a, T>>,
b: Peekable<&'a T, SetItems<'a, T>>,
}
/// Lazy iterator producing elements in the set union (in-order)
pub struct UnionItems<'a, T> {
a: Peekable<&'a T, SetItems<'a, T>>,
b: Peekable<&'a T, SetItems<'a, T>>,
}
/// Compare `x` and `y`, but return `short` if x is None and `long` if y is None
fn cmp_opt<T: Ord>(x: Option<&T>, y: Option<&T>,
short: Ordering, long: Ordering) -> Ordering {
match (x, y) {
(None , _ ) => short,
(_ , None ) => long,
(Some(x1), Some(y1)) => x1.cmp(y1),
}
}
impl<'a, T: Ord> Iterator<&'a T> for DifferenceItems<'a, T> {
fn next(&mut self) -> Option<&'a T> {
loop {
match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) {
Less => return self.a.next(),
Equal => { self.a.next(); self.b.next(); }
Greater => { self.b.next(); }
}
}
}
}
impl<'a, T: Ord> Iterator<&'a T> for SymDifferenceItems<'a, T> {
fn next(&mut self) -> Option<&'a T> {
loop {
match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
Less => return self.a.next(),
Equal => { self.a.next(); self.b.next(); }
Greater => return self.b.next(),
}
}
}
}
impl<'a, T: Ord> Iterator<&'a T> for IntersectionItems<'a, T> {
fn next(&mut self) -> Option<&'a T> {
loop {
let o_cmp = match (self.a.peek(), self.b.peek()) {
(None , _ ) => None,
(_ , None ) => None,
(Some(a1), Some(b1)) => Some(a1.cmp(b1)),
};
match o_cmp {
None => return None,
Some(Less) => { self.a.next(); }
Some(Equal) => { self.b.next(); return self.a.next() }
Some(Greater) => { self.b.next(); }
}
}
}
}
impl<'a, T: Ord> Iterator<&'a T> for UnionItems<'a, T> {
fn next(&mut self) -> Option<&'a T> {
loop {
match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) {
Less => return self.a.next(),
Equal => { self.b.next(); return self.a.next() }
Greater => return self.b.next(),
}
}
}
}
// Nodes keep track of their level in the tree, starting at 1 in the
// leaves and with a red child sharing the level of the parent.
#[deriving(Clone)]
struct TreeNode<K, V> {
key: K,
value: V,
left: Option<Box<TreeNode<K, V>>>,
right: Option<Box<TreeNode<K, V>>>,
level: uint
}
impl<K: Ord, V> TreeNode<K, V> {
/// Creates a new tree node.
#[inline]
pub fn new(key: K, value: V) -> TreeNode<K, V> {
TreeNode{key: key, value: value, left: None, right: None, level: 1}
}
}
// Remove left horizontal link by rotating right
fn skew<K: Ord, V>(node: &mut Box<TreeNode<K, V>>) {
if node.left.as_ref().map_or(false, |x| x.level == node.level) {
let mut save = node.left.take_unwrap();
swap(&mut node.left, &mut save.right); // save.right now None
swap(node, &mut save);
node.right = Some(save);
}
}
// Remove dual horizontal link by rotating left and increasing level of
// the parent
fn split<K: Ord, V>(node: &mut Box<TreeNode<K, V>>) {
if node.right.as_ref().map_or(false,
|x| x.right.as_ref().map_or(false, |y| y.level == node.level)) {
let mut save = node.right.take_unwrap();
swap(&mut node.right, &mut save.left); // save.left now None
save.level += 1;
swap(node, &mut save);
node.left = Some(save);
}
}
fn find_mut<'r, K: Ord, V>(node: &'r mut Option<Box<TreeNode<K, V>>>,
key: &K)
-> Option<&'r mut V> {
match *node {
Some(ref mut x) => {
match key.cmp(&x.key) {
Less => find_mut(&mut x.left, key),
Greater => find_mut(&mut x.right, key),
Equal => Some(&mut x.value),
}
}
None => None
}
}
fn insert<K: Ord, V>(node: &mut Option<Box<TreeNode<K, V>>>,
key: K, value: V) -> Option<V> {
match *node {
Some(ref mut save) => {
match key.cmp(&save.key) {
Less => {
let inserted = insert(&mut save.left, key, value);
skew(save);
split(save);
inserted
}
Greater => {
let inserted = insert(&mut save.right, key, value);
skew(save);
split(save);
inserted
}
Equal => {
save.key = key;
Some(replace(&mut save.value, value))
}
}
}
None => {
*node = Some(box TreeNode::new(key, value));
None
}
}
}
fn remove<K: Ord, V>(node: &mut Option<Box<TreeNode<K, V>>>,
key: &K) -> Option<V> {
fn heir_swap<K: Ord, V>(node: &mut Box<TreeNode<K, V>>,
child: &mut Option<Box<TreeNode<K, V>>>) {
// *could* be done without recursion, but it won't borrow check
for x in child.mut_iter() {
if x.right.is_some() {
heir_swap(node, &mut x.right);
} else {
swap(&mut node.key, &mut x.key);
swap(&mut node.value, &mut x.value);
}
}
}
match *node {
None => {
return None; // bottom of tree
}
Some(ref mut save) => {
let (ret, rebalance) = match key.cmp(&save.key) {
Less => (remove(&mut save.left, key), true),
Greater => (remove(&mut save.right, key), true),
Equal => {
if save.left.is_some() {
if save.right.is_some() {
let mut left = save.left.take_unwrap();
if left.right.is_some() {
heir_swap(save, &mut left.right);
} else {
swap(&mut save.key, &mut left.key);
swap(&mut save.value, &mut left.value);
}
save.left = Some(left);
(remove(&mut save.left, key), true)
} else {
let new = save.left.take_unwrap();
let box TreeNode{value, ..} = replace(save, new);
*save = save.left.take_unwrap();
(Some(value), true)
}
} else if save.right.is_some() {
let new = save.right.take_unwrap();
let box TreeNode{value, ..} = replace(save, new);
(Some(value), true)
} else {
(None, false)
}
}
};
if rebalance {
let left_level = save.left.as_ref().map_or(0, |x| x.level);
let right_level = save.right.as_ref().map_or(0, |x| x.level);
// re-balance, if necessary
if left_level < save.level - 1 || right_level < save.level - 1 {
save.level -= 1;
if right_level > save.level {
for x in save.right.mut_iter() { x.level = save.level }
}
skew(save);
for right in save.right.mut_iter() {
skew(right);
for x in right.right.mut_iter() { skew(x) }
}
split(save);
for x in save.right.mut_iter() { split(x) }
}
return ret;
}
}
}
return match node.take() {