-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathmap.rs
1953 lines (1725 loc) · 61.1 KB
/
map.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-2014 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.
//! Ordered maps and sets, implemented as simple tries.
pub use self::Entry::*;
use self::TrieNode::*;
use std::default::Default;
use std::fmt;
use std::fmt::Show;
use std::mem::zeroed;
use std::mem;
use std::ops::{Slice, SliceMut};
use std::uint;
use std::iter;
use std::ptr;
use std::hash::{Writer, Hash};
use std::slice::{Items, MutItems};
use std::slice;
// FIXME(conventions): implement bounded iterators
// FIXME(conventions): implement into_iter
// FIXME(conventions): replace each_reverse by making iter DoubleEnded
// FIXME: #5244: need to manually update the InternalNode constructor
const SHIFT: uint = 4;
const SIZE: uint = 1 << SHIFT;
const MASK: uint = SIZE - 1;
// The number of chunks that the key is divided into. Also the maximum depth of the TrieMap.
const MAX_DEPTH: uint = uint::BITS / SHIFT;
/// A map implemented as a radix trie.
///
/// Keys are split into sequences of 4 bits, which are used to place elements in
/// 16-entry arrays which are nested to form a tree structure. Inserted elements are placed
/// as close to the top of the tree as possible. The most significant bits of the key are used to
/// assign the key to a node/bucket in the first layer. If there are no other elements keyed by
/// the same 4 bits in the first layer, a leaf node will be created in the first layer.
/// When keys coincide, the next 4 bits are used to assign the node to a bucket in the next layer,
/// with this process continuing until an empty spot is found or there are no more bits left in the
/// key. As a result, the maximum depth using 32-bit `uint` keys is 8. The worst collisions occur
/// for very small numbers. For example, 1 and 2 are identical in all but their least significant
/// 4 bits. If both numbers are used as keys, a chain of maximum length will be created to
/// differentiate them.
///
/// # Examples
///
/// ```
/// use collect::TrieMap;
///
/// let mut map = TrieMap::new();
/// map.insert(27, "Olaf");
/// map.insert(1, "Edgar");
/// map.insert(13, "Ruth");
/// map.insert(1, "Martin");
///
/// assert_eq!(map.len(), 3);
/// assert_eq!(map.get(&1), Some(&"Martin"));
///
/// if !map.contains_key(&90) {
/// println!("Nobody is keyed 90");
/// }
///
/// // Update a key
/// match map.get_mut(&1) {
/// Some(value) => *value = "Olga",
/// None => (),
/// }
///
/// map.remove(&13);
/// assert_eq!(map.len(), 2);
///
/// // Print the key value pairs, ordered by key.
/// for (key, value) in map.iter() {
/// // Prints `1: Olga` then `27: Olaf`
/// println!("{}: {}", key, value);
/// }
///
/// map.clear();
/// assert!(map.is_empty());
/// ```
#[deriving(Clone)]
pub struct TrieMap<T> {
root: InternalNode<T>,
length: uint
}
// An internal node holds SIZE child nodes, which may themselves contain more internal nodes.
//
// Throughout this implementation, "idx" is used to refer to a section of key that is used
// to access a node. The layer of the tree directly below the root corresponds to idx 0.
struct InternalNode<T> {
// The number of direct children which are external (i.e. that store a value).
count: uint,
children: [TrieNode<T>, ..SIZE]
}
// Each child of an InternalNode may be internal, in which case nesting continues,
// external (containing a value), or empty
#[deriving(Clone)]
enum TrieNode<T> {
Internal(Box<InternalNode<T>>),
External(uint, T),
Nothing
}
impl<T: PartialEq> PartialEq for TrieMap<T> {
fn eq(&self, other: &TrieMap<T>) -> bool {
self.len() == other.len() &&
self.iter().zip(other.iter()).all(|(a, b)| a == b)
}
}
impl<T: Eq> Eq for TrieMap<T> {}
impl<T: PartialOrd> PartialOrd for TrieMap<T> {
#[inline]
fn partial_cmp(&self, other: &TrieMap<T>) -> Option<Ordering> {
iter::order::partial_cmp(self.iter(), other.iter())
}
}
impl<T: Ord> Ord for TrieMap<T> {
#[inline]
fn cmp(&self, other: &TrieMap<T>) -> Ordering {
iter::order::cmp(self.iter(), other.iter())
}
}
impl<T: Show> Show for TrieMap<T> {
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<T> Default for TrieMap<T> {
#[inline]
fn default() -> TrieMap<T> { TrieMap::new() }
}
impl<T> TrieMap<T> {
/// Creates an empty `TrieMap`.
///
/// # Examples
///
/// ```
/// use collect::TrieMap;
/// let mut map: TrieMap<&str> = TrieMap::new();
/// ```
#[inline]
#[unstable = "matches collection reform specification, waiting for dust to settle"]
pub fn new() -> TrieMap<T> {
TrieMap{root: InternalNode::new(), length: 0}
}
/// Visits all key-value pairs in reverse order. Aborts traversal when `f` returns `false`.
/// Returns `true` if `f` returns `true` for all elements.
///
/// # Examples
///
/// ```
/// use collect::TrieMap;
/// let map: TrieMap<&str> = [(1, "a"), (2, "b"), (3, "c")].iter().map(|&x| x).collect();
///
/// let mut vec = Vec::new();
/// assert_eq!(true, map.each_reverse(|&key, &value| { vec.push((key, value)); true }));
/// assert_eq!(vec, vec![(3, "c"), (2, "b"), (1, "a")]);
///
/// // Stop when we reach 2
/// let mut vec = Vec::new();
/// assert_eq!(false, map.each_reverse(|&key, &value| { vec.push(value); key != 2 }));
/// assert_eq!(vec, vec!["c", "b"]);
/// ```
#[inline]
pub fn each_reverse<'a>(&'a self, f: |&uint, &'a T| -> bool) -> bool {
self.root.each_reverse(f)
}
/// Gets an iterator visiting all keys in ascending order by the keys.
/// The iterator's element type is `uint`.
#[unstable = "matches collection reform specification, waiting for dust to settle"]
pub fn keys<'r>(&'r self) -> Keys<'r, T> {
fn first<A, B>((a, _): (A, B)) -> A { a }
self.iter().map(first)
}
/// Gets an iterator visiting all values in ascending order by the keys.
/// The iterator's element type is `&'r T`.
#[unstable = "matches collection reform specification, waiting for dust to settle"]
pub fn values<'r>(&'r self) -> Values<'r, T> {
fn second<A, B>((_, b): (A, B)) -> B { b }
self.iter().map(second)
}
/// Gets an iterator over the key-value pairs in the map, ordered by keys.
///
/// # Examples
///
/// ```
/// use collect::TrieMap;
/// let map: TrieMap<&str> = [(3, "c"), (1, "a"), (2, "b")].iter().map(|&x| x).collect();
///
/// for (key, value) in map.iter() {
/// println!("{}: {}", key, value);
/// }
/// ```
#[unstable = "matches collection reform specification, waiting for dust to settle"]
pub fn iter<'a>(&'a self) -> Entries<'a, T> {
let mut iter = unsafe {Entries::new()};
iter.stack[0] = self.root.children.iter();
iter.length = 1;
iter.remaining_min = self.length;
iter.remaining_max = self.length;
iter
}
/// Gets an iterator over the key-value pairs in the map, with the
/// ability to mutate the values.
///
/// # Examples
///
/// ```
/// use collect::TrieMap;
/// let mut map: TrieMap<int> = [(1, 2), (2, 4), (3, 6)].iter().map(|&x| x).collect();
///
/// for (key, value) in map.iter_mut() {
/// *value = -(key as int);
/// }
///
/// assert_eq!(map.get(&1), Some(&-1));
/// assert_eq!(map.get(&2), Some(&-2));
/// assert_eq!(map.get(&3), Some(&-3));
/// ```
#[unstable = "matches collection reform specification, waiting for dust to settle"]
pub fn iter_mut<'a>(&'a mut self) -> MutEntries<'a, T> {
let mut iter = unsafe {MutEntries::new()};
iter.stack[0] = self.root.children.iter_mut();
iter.length = 1;
iter.remaining_min = self.length;
iter.remaining_max = self.length;
iter
}
/// Return the number of elements in the map.
///
/// # Examples
///
/// ```
/// use collect::TrieMap;
///
/// let mut a = TrieMap::new();
/// assert_eq!(a.len(), 0);
/// a.insert(1, "a");
/// assert_eq!(a.len(), 1);
/// ```
#[inline]
#[unstable = "matches collection reform specification, waiting for dust to settle"]
pub fn len(&self) -> uint { self.length }
/// Return true if the map contains no elements.
///
/// # Examples
///
/// ```
/// use collect::TrieMap;
///
/// let mut a = TrieMap::new();
/// assert!(a.is_empty());
/// a.insert(1, "a");
/// assert!(!a.is_empty());
/// ```
#[inline]
#[unstable = "matches collection reform specification, waiting for dust to settle"]
pub fn is_empty(&self) -> bool { self.len() == 0 }
/// Clears the map, removing all values.
///
/// # Examples
///
/// ```
/// use collect::TrieMap;
///
/// let mut a = TrieMap::new();
/// a.insert(1, "a");
/// a.clear();
/// assert!(a.is_empty());
/// ```
#[inline]
#[unstable = "matches collection reform specification, waiting for dust to settle"]
pub fn clear(&mut self) {
self.root = InternalNode::new();
self.length = 0;
}
/// Deprecated: renamed to `get`.
#[deprecated = "renamed to `get`"]
pub fn find(&self, key: &uint) -> Option<&T> {
self.get(key)
}
/// Returns a reference to the value corresponding to the key.
///
/// # Examples
///
/// ```
/// use collect::TrieMap;
///
/// let mut map = TrieMap::new();
/// map.insert(1, "a");
/// assert_eq!(map.get(&1), Some(&"a"));
/// assert_eq!(map.get(&2), None);
/// ```
#[inline]
#[unstable = "matches collection reform specification, waiting for dust to settle"]
pub fn get(&self, key: &uint) -> Option<&T> {
let mut node = &self.root;
let mut idx = 0;
loop {
match node.children[chunk(*key, idx)] {
Internal(ref x) => node = &**x,
External(stored, ref value) => {
if stored == *key {
return Some(value)
} else {
return None
}
}
Nothing => return None
}
idx += 1;
}
}
/// Returns true if the map contains a value for the specified key.
///
/// # Examples
///
/// ```
/// use collect::TrieMap;
///
/// let mut map = TrieMap::new();
/// map.insert(1, "a");
/// assert_eq!(map.contains_key(&1), true);
/// assert_eq!(map.contains_key(&2), false);
/// ```
#[inline]
#[unstable = "matches collection reform specification, waiting for dust to settle"]
pub fn contains_key(&self, key: &uint) -> bool {
self.get(key).is_some()
}
/// Deprecated: renamed to `get_mut`.
#[deprecated = "renamed to `get_mut`"]
pub fn find_mut(&mut self, key: &uint) -> Option<&mut T> {
self.get_mut(key)
}
/// Returns a mutable reference to the value corresponding to the key.
///
/// # Examples
///
/// ```
/// use collect::TrieMap;
///
/// let mut map = TrieMap::new();
/// map.insert(1, "a");
/// match map.get_mut(&1) {
/// Some(x) => *x = "b",
/// None => (),
/// }
/// assert_eq!(map[1], "b");
/// ```
#[inline]
#[unstable = "matches collection reform specification, waiting for dust to settle"]
pub fn get_mut<'a>(&'a mut self, key: &uint) -> Option<&'a mut T> {
find_mut(&mut self.root.children[chunk(*key, 0)], *key, 1)
}
/// Deprecated: Renamed to `insert`.
#[deprecated = "Renamed to `insert`"]
pub fn swap(&mut self, key: uint, value: T) -> Option<T> {
self.insert(key, value)
}
/// Inserts a key-value pair from the map. If the key already had a value
/// present in the map, that value is returned. Otherwise, `None` is returned.
///
/// # Examples
///
/// ```
/// use collect::TrieMap;
///
/// let mut map = TrieMap::new();
/// assert_eq!(map.insert(37, "a"), None);
/// assert_eq!(map.is_empty(), false);
///
/// map.insert(37, "b");
/// assert_eq!(map.insert(37, "c"), Some("b"));
/// assert_eq!(map[37], "c");
/// ```
#[unstable = "matches collection reform specification, waiting for dust to settle"]
pub fn insert(&mut self, key: uint, value: T) -> Option<T> {
let (_, old_val) = insert(&mut self.root.count,
&mut self.root.children[chunk(key, 0)],
key, value, 1);
if old_val.is_none() { self.length += 1 }
old_val
}
/// Deprecated: Renamed to `remove`.
#[deprecated = "Renamed to `remove`"]
pub fn pop(&mut self, key: &uint) -> Option<T> {
self.remove(key)
}
/// Removes a key from the map, returning the value at the key if the key
/// was previously in the map.
///
/// # Examples
///
/// ```
/// use collect::TrieMap;
///
/// let mut map = TrieMap::new();
/// map.insert(1, "a");
/// assert_eq!(map.remove(&1), Some("a"));
/// assert_eq!(map.remove(&1), None);
/// ```
#[unstable = "matches collection reform specification, waiting for dust to settle"]
pub fn remove(&mut self, key: &uint) -> Option<T> {
let ret = remove(&mut self.root.count,
&mut self.root.children[chunk(*key, 0)],
*key, 1);
if ret.is_some() { self.length -= 1 }
ret
}
}
// 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. (see also
// `item!` below.)
macro_rules! addr { ($e:expr) => { $e } }
macro_rules! bound {
($iterator_name:ident,
// the current treemap
self = $this:expr,
// the key to look for
key = $key:expr,
// are we looking at the upper bound?
is_upper = $upper:expr,
// method names for slicing/iterating.
slice_from = $slice_from:ident,
iter = $iter:ident,
// see the comment on `addr!`, this is just an optional mut, but
// there's no 0-or-1 repeats yet.
mutability = $($mut_:tt)*) => {
{
// # For `mut`
// We need an unsafe pointer here because we are borrowing
// mutable references to the internals of each of these
// mutable nodes, while still using the outer node.
//
// However, we're allowed to flaunt rustc like this because we
// never actually modify the "shape" of the nodes. The only
// place that mutation is can actually occur is of the actual
// values of the TrieMap (as the return value of the
// iterator), i.e. we can never cause a deallocation of any
// InternalNodes so the raw pointer is always valid.
//
// # For non-`mut`
// We like sharing code so much that even a little unsafe won't
// stop us.
let this = $this;
let mut node = unsafe {
mem::transmute::<_, uint>(&this.root) as *mut InternalNode<T>
};
let key = $key;
let mut it = unsafe {$iterator_name::new()};
// everything else is zero'd, as we want.
it.remaining_max = this.length;
// this addr is necessary for the `Internal` pattern.
addr!(loop {
let children = unsafe {addr!(& $($mut_)* (*node).children)};
// it.length is the current depth in the iterator and the
// current depth through the `uint` key we've traversed.
let child_id = chunk(key, it.length);
let (slice_idx, ret) = match children[child_id] {
Internal(ref $($mut_)* n) => {
node = unsafe {
mem::transmute::<_, uint>(&**n)
as *mut InternalNode<T>
};
(child_id + 1, false)
}
External(stored, _) => {
(if stored < key || ($upper && stored == key) {
child_id + 1
} else {
child_id
}, true)
}
Nothing => {
(child_id + 1, true)
}
};
// push to the stack.
it.stack[it.length] = children.$slice_from(&slice_idx).$iter();
it.length += 1;
if ret { return it }
})
}
}
}
impl<T> TrieMap<T> {
// If `upper` is true then returns upper_bound else returns lower_bound.
#[inline]
fn bound<'a>(&'a self, key: uint, upper: bool) -> Entries<'a, T> {
bound!(Entries, self = self,
key = key, is_upper = upper,
slice_from = slice_from_or_fail, iter = iter,
mutability = )
}
/// Gets an iterator pointing to the first key-value pair whose key is not less than `key`.
/// If all keys in the map are less than `key` an empty iterator is returned.
///
/// # Examples
///
/// ```
/// use collect::TrieMap;
/// let map: TrieMap<&str> = [(2, "a"), (4, "b"), (6, "c")].iter().map(|&x| x).collect();
///
/// assert_eq!(map.lower_bound(4).next(), Some((4, &"b")));
/// assert_eq!(map.lower_bound(5).next(), Some((6, &"c")));
/// assert_eq!(map.lower_bound(10).next(), None);
/// ```
pub fn lower_bound<'a>(&'a self, key: uint) -> Entries<'a, T> {
self.bound(key, false)
}
/// Gets an iterator pointing to the first key-value pair whose key is greater than `key`.
/// If all keys in the map are not greater than `key` an empty iterator is returned.
///
/// # Examples
///
/// ```
/// use collect::TrieMap;
/// let map: TrieMap<&str> = [(2, "a"), (4, "b"), (6, "c")].iter().map(|&x| x).collect();
///
/// assert_eq!(map.upper_bound(4).next(), Some((6, &"c")));
/// assert_eq!(map.upper_bound(5).next(), Some((6, &"c")));
/// assert_eq!(map.upper_bound(10).next(), None);
/// ```
pub fn upper_bound<'a>(&'a self, key: uint) -> Entries<'a, T> {
self.bound(key, true)
}
// If `upper` is true then returns upper_bound else returns lower_bound.
#[inline]
fn bound_mut<'a>(&'a mut self, key: uint, upper: bool) -> MutEntries<'a, T> {
bound!(MutEntries, self = self,
key = key, is_upper = upper,
slice_from = slice_from_or_fail_mut, iter = iter_mut,
mutability = mut)
}
/// Gets an iterator pointing to the first key-value pair whose key is not less than `key`.
/// If all keys in the map are less than `key` an empty iterator is returned.
///
/// # Examples
///
/// ```
/// use collect::TrieMap;
/// let mut map: TrieMap<&str> = [(2, "a"), (4, "b"), (6, "c")].iter().map(|&x| x).collect();
///
/// assert_eq!(map.lower_bound_mut(4).next(), Some((4, &mut "b")));
/// assert_eq!(map.lower_bound_mut(5).next(), Some((6, &mut "c")));
/// assert_eq!(map.lower_bound_mut(10).next(), None);
///
/// for (key, value) in map.lower_bound_mut(4) {
/// *value = "changed";
/// }
///
/// assert_eq!(map.get(&2), Some(&"a"));
/// assert_eq!(map.get(&4), Some(&"changed"));
/// assert_eq!(map.get(&6), Some(&"changed"));
/// ```
pub fn lower_bound_mut<'a>(&'a mut self, key: uint) -> MutEntries<'a, T> {
self.bound_mut(key, false)
}
/// Gets an iterator pointing to the first key-value pair whose key is greater than `key`.
/// If all keys in the map are not greater than `key` an empty iterator is returned.
///
/// # Examples
///
/// ```
/// use collect::TrieMap;
/// let mut map: TrieMap<&str> = [(2, "a"), (4, "b"), (6, "c")].iter().map(|&x| x).collect();
///
/// assert_eq!(map.upper_bound_mut(4).next(), Some((6, &mut "c")));
/// assert_eq!(map.upper_bound_mut(5).next(), Some((6, &mut "c")));
/// assert_eq!(map.upper_bound_mut(10).next(), None);
///
/// for (key, value) in map.upper_bound_mut(4) {
/// *value = "changed";
/// }
///
/// assert_eq!(map.get(&2), Some(&"a"));
/// assert_eq!(map.get(&4), Some(&"b"));
/// assert_eq!(map.get(&6), Some(&"changed"));
/// ```
pub fn upper_bound_mut<'a>(&'a mut self, key: uint) -> MutEntries<'a, T> {
self.bound_mut(key, true)
}
}
impl<T> FromIterator<(uint, T)> for TrieMap<T> {
fn from_iter<Iter: Iterator<(uint, T)>>(iter: Iter) -> TrieMap<T> {
let mut map = TrieMap::new();
map.extend(iter);
map
}
}
impl<T> Extend<(uint, T)> for TrieMap<T> {
fn extend<Iter: Iterator<(uint, T)>>(&mut self, mut iter: Iter) {
for (k, v) in iter {
self.insert(k, v);
}
}
}
impl<S: Writer, T: Hash<S>> Hash<S> for TrieMap<T> {
fn hash(&self, state: &mut S) {
for elt in self.iter() {
elt.hash(state);
}
}
}
impl<T> Index<uint, T> for TrieMap<T> {
#[inline]
fn index<'a>(&'a self, i: &uint) -> &'a T {
self.get(i).expect("key not present")
}
}
impl<T> IndexMut<uint, T> for TrieMap<T> {
#[inline]
fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut T {
self.get_mut(i).expect("key not present")
}
}
impl<T:Clone> Clone for InternalNode<T> {
#[inline]
fn clone(&self) -> InternalNode<T> {
let ch = &self.children;
InternalNode {
count: self.count,
children: [ch[0].clone(), ch[1].clone(), ch[2].clone(), ch[3].clone(),
ch[4].clone(), ch[5].clone(), ch[6].clone(), ch[7].clone(),
ch[8].clone(), ch[9].clone(), ch[10].clone(), ch[11].clone(),
ch[12].clone(), ch[13].clone(), ch[14].clone(), ch[15].clone()]}
}
}
impl<T> InternalNode<T> {
#[inline]
fn new() -> InternalNode<T> {
// FIXME: #5244: [Nothing, ..SIZE] should be possible without implicit
// copyability
InternalNode{count: 0,
children: [Nothing, Nothing, Nothing, Nothing,
Nothing, Nothing, Nothing, Nothing,
Nothing, Nothing, Nothing, Nothing,
Nothing, Nothing, Nothing, Nothing]}
}
}
impl<T> InternalNode<T> {
fn each_reverse<'a>(&'a self, f: |&uint, &'a T| -> bool) -> bool {
for elt in self.children.iter().rev() {
match *elt {
Internal(ref x) => if !x.each_reverse(|i,t| f(i,t)) { return false },
External(k, ref v) => if !f(&k, v) { return false },
Nothing => ()
}
}
true
}
}
// if this was done via a trait, the key could be generic
#[inline]
fn chunk(n: uint, idx: uint) -> uint {
let sh = uint::BITS - (SHIFT * (idx + 1));
(n >> sh) & MASK
}
fn find_mut<'r, T>(child: &'r mut TrieNode<T>, key: uint, idx: uint) -> Option<&'r mut T> {
match *child {
External(stored, ref mut value) if stored == key => Some(value),
External(..) => None,
Internal(ref mut x) => find_mut(&mut x.children[chunk(key, idx)], key, idx + 1),
Nothing => None
}
}
/// Inserts a new node for the given key and value, at or below `start_node`.
///
/// The index (`idx`) is the index of the next node, such that the start node
/// was accessed via parent.children[chunk(key, idx - 1)].
///
/// The count is the external node counter for the start node's parent,
/// which will be incremented only if `start_node` is transformed into a *new* external node.
///
/// Returns a mutable reference to the inserted value and an optional previous value.
fn insert<'a, T>(count: &mut uint, start_node: &'a mut TrieNode<T>, key: uint, value: T, idx: uint)
-> (&'a mut T, Option<T>) {
// We branch twice to avoid having to do the `replace` when we
// don't need to; this is much faster, especially for keys that
// have long shared prefixes.
match *start_node {
Nothing => {
*count += 1;
*start_node = External(key, value);
match *start_node {
External(_, ref mut value_ref) => return (value_ref, None),
_ => unreachable!()
}
}
Internal(box ref mut x) => {
return insert(&mut x.count, &mut x.children[chunk(key, idx)], key, value, idx + 1);
}
External(stored_key, ref mut stored_value) if stored_key == key => {
// Swap in the new value and return the old.
let old_value = mem::replace(stored_value, value);
return (stored_value, Some(old_value));
}
_ => {}
}
// Conflict, an external node with differing keys.
// We replace the old node by an internal one, then re-insert the two values beneath it.
match mem::replace(start_node, Internal(box InternalNode::new())) {
External(stored_key, stored_value) => {
match *start_node {
Internal(box ref mut new_node) => {
// Re-insert the old value.
insert(&mut new_node.count,
&mut new_node.children[chunk(stored_key, idx)],
stored_key, stored_value, idx + 1);
// Insert the new value, and return a reference to it directly.
insert(&mut new_node.count,
&mut new_node.children[chunk(key, idx)],
key, value, idx + 1)
}
// Value that was just copied disappeared.
_ => unreachable!()
}
}
// Logic error in previous match.
_ => unreachable!(),
}
}
fn remove<T>(count: &mut uint, child: &mut TrieNode<T>, key: uint,
idx: uint) -> Option<T> {
let (ret, this) = match *child {
External(stored, _) if stored == key => {
match mem::replace(child, Nothing) {
External(_, value) => (Some(value), true),
_ => unreachable!()
}
}
External(..) => (None, false),
Internal(box ref mut x) => {
let ret = remove(&mut x.count, &mut x.children[chunk(key, idx)],
key, idx + 1);
(ret, x.count == 0)
}
Nothing => (None, false)
};
if this {
*child = Nothing;
*count -= 1;
}
return ret;
}
/// A view into a single entry in a TrieMap, which may be vacant or occupied.
pub enum Entry<'a, T: 'a> {
/// An occupied entry.
Occupied(OccupiedEntry<'a, T>),
/// A vacant entry.
Vacant(VacantEntry<'a, T>)
}
/// A view into an occupied entry in a TrieMap.
pub struct OccupiedEntry<'a, T: 'a> {
search_stack: SearchStack<'a, T>
}
/// A view into a vacant entry in a TrieMap.
pub struct VacantEntry<'a, T: 'a> {
search_stack: SearchStack<'a, T>
}
/// A list of nodes encoding a path from the root of a TrieMap to a node.
///
/// Invariants:
/// * The last node is either `External` or `Nothing`.
/// * Pointers at indexes less than `length` can be safely dereferenced.
struct SearchStack<'a, T: 'a> {
map: &'a mut TrieMap<T>,
length: uint,
key: uint,
items: [*mut TrieNode<T>, ..MAX_DEPTH]
}
impl<'a, T> SearchStack<'a, T> {
/// Creates a new search-stack with empty entries.
fn new(map: &'a mut TrieMap<T>, key: uint) -> SearchStack<'a, T> {
SearchStack {
map: map,
length: 0,
key: key,
items: [ptr::null_mut(), ..MAX_DEPTH]
}
}
fn push(&mut self, node: *mut TrieNode<T>) {
self.length += 1;
self.items[self.length - 1] = node;
}
fn peek(&self) -> *mut TrieNode<T> {
self.items[self.length - 1]
}
fn peek_ref(&self) -> &'a mut TrieNode<T> {
unsafe {
&mut *self.items[self.length - 1]
}
}
fn pop_ref(&mut self) -> &'a mut TrieNode<T> {
self.length -= 1;
unsafe {
&mut *self.items[self.length]
}
}
fn is_empty(&self) -> bool {
self.length == 0
}
fn get_ref(&self, idx: uint) -> &'a mut TrieNode<T> {
assert!(idx < self.length);
unsafe {
&mut *self.items[idx]
}
}
}
// Implementation of SearchStack creation logic.
// Once a SearchStack has been created the Entry methods are relatively straight-forward.
impl<T> TrieMap<T> {
/// Gets the given key's corresponding entry in the map for in-place manipulation.
#[inline]
pub fn entry<'a>(&'a mut self, key: uint) -> Entry<'a, T> {
// Create an empty search stack.
let mut search_stack = SearchStack::new(self, key);
// Unconditionally add the corresponding node from the first layer.
let first_node = &mut search_stack.map.root.children[chunk(key, 0)] as *mut _;
search_stack.push(first_node);
// While no appropriate slot is found, keep descending down the Trie,
// adding nodes to the search stack.
let search_successful: bool;
loop {
match unsafe { next_child(search_stack.peek(), key, search_stack.length) } {
(Some(child), _) => search_stack.push(child),
(None, success) => {
search_successful = success;
break;
}
}
}
if search_successful {
Occupied(OccupiedEntry { search_stack: search_stack })
} else {
Vacant(VacantEntry { search_stack: search_stack })
}
}
}
/// Get a mutable pointer to the next child of a node, given a key and an idx.
///
/// The idx is the index of the next child, such that `node` was accessed via
/// parent.children[chunk(key, idx - 1)].
///
/// Returns a tuple with an optional mutable pointer to the next child, and
/// a boolean flag to indicate whether the external key node was found.
///
/// This function is safe only if `node` points to a valid `TrieNode`.
#[inline]
unsafe fn next_child<'a, T>(node: *mut TrieNode<T>, key: uint, idx: uint)
-> (Option<*mut TrieNode<T>>, bool) {
match *node {
// If the node is internal, tell the caller to descend further.
Internal(box ref mut node_internal) => {
(Some(&mut node_internal.children[chunk(key, idx)] as *mut _), false)
},
// If the node is external or empty, the search is complete.
// If the key doesn't match, node expansion will be done upon
// insertion. If it does match, we've found our node.
External(stored_key, _) if stored_key == key => (None, true),
External(..) | Nothing => (None, false)
}
}
// NB: All these methods assume a correctly constructed occupied entry (matching the given key).
impl<'a, T> OccupiedEntry<'a, T> {
/// Gets a reference to the value in the entry.
#[inline]
pub fn get(&self) -> &T {
match *self.search_stack.peek_ref() {
External(_, ref value) => value,
// Invalid SearchStack, non-external last node.
_ => unreachable!()
}
}
/// Gets a mutable reference to the value in the entry.
#[inline]
pub fn get_mut(&mut self) -> &mut T {
match *self.search_stack.peek_ref() {
External(_, ref mut value) => value,
// Invalid SearchStack, non-external last node.
_ => unreachable!()
}
}
/// Converts the OccupiedEntry into a mutable reference to the value in the entry,
/// with a lifetime bound to the map itself.
#[inline]
pub fn into_mut(self) -> &'a mut T {
match *self.search_stack.peek_ref() {
External(_, ref mut value) => value,
// Invalid SearchStack, non-external last node.
_ => unreachable!()
}
}
/// Sets the value of the entry, and returns the entry's old value.
#[inline]
pub fn set(&mut self, value: T) -> T {
match *self.search_stack.peek_ref() {
External(_, ref mut stored_value) => {
mem::replace(stored_value, value)
}
// Invalid SearchStack, non-external last node.
_ => unreachable!()
}
}