This repository has been archived by the owner on Jan 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathhamt.rs
1771 lines (1523 loc) · 65.1 KB
/
hamt.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 (c) 2013, 2014, 2015, 2016 Michael Woerister
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//! A Hash Array Mapped Trie implementation based on the
//! [Ideal Hash Trees](http://lampwww.epfl.ch/papers/idealhashtrees.pdf) paper by Phil Bagwell.
//! This is the datastructure used by Scala's and Clojure's standard library as map implementation.
//! The idea to use a special *collision node* to deal with hash collisions is taken from Clojure's
//! implementation.
use std::hash::{Hasher, Hash};
use std::mem;
use std::ptr;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::default::Default;
use std::sync::Arc;
use item_store::{ItemStore, ShareStore};
use std::collections::hash_map::DefaultHasher as StdHasher;
use libc;
#[cfg(not(double_wide_nodes))]
type MaskType = u32;
#[cfg(not(double_wide_nodes))]
type EntryTypesType = u64;
#[cfg(not(double_wide_nodes))]
const ENTRY_TYPES_MAX: EntryTypesType = ::std::u64::MAX;
#[cfg(double_wide_nodes)]
type MaskType = u64;
#[cfg(double_wide_nodes)]
type EntryTypesType = u128;
#[cfg(double_wide_nodes)]
const ENTRY_TYPES_MAX: EntryTypesType = ::std::u128::MAX;
//=-------------------------------------------------------------------------------------------------
// NodeRef
//=-------------------------------------------------------------------------------------------------
// A smart pointer for handling node lifetimes, very similar to sync::Arc.
struct NodeRef<K, V, IS, H> {
ptr: *mut UnsafeNode<K, V, IS, H>
}
// NodeRef knows if it is the only reference to a given node and can thus safely decide to allow for
// mutable access to the referenced node. This type indicates whether mutable access could be
// acquired.
enum BorrowedNodeRef<'a, K, V, IS, H>
where K: 'a,
V: 'a,
IS: 'a,
H: 'a
{
Exclusive(&'a mut UnsafeNode<K, V, IS, H>),
Shared(&'a UnsafeNode<K, V, IS, H>),
}
impl<K, V, IS, H> NodeRef<K, V, IS, H>
where K: Eq+Send+Sync,
V: Send+Sync,
IS: ItemStore<K, V>,
H: Hasher
{
fn borrow<'a>(&'a self) -> &'a UnsafeNode<K, V, IS, H> {
unsafe {
mem::transmute(self.ptr)
}
}
fn borrow_mut<'a>(&'a mut self) -> &'a mut UnsafeNode<K, V, IS, H> {
unsafe {
debug_assert!((*self.ptr).ref_count.load(Ordering::SeqCst) == 1);
mem::transmute(self.ptr)
}
}
// Try to safely gain mutable access to the referenced node. This can be used to safely make
// in-place modifications instead of unnecessarily copying data.
fn try_borrow_owned<'a>(&'a mut self) -> BorrowedNodeRef<'a, K, V, IS, H> {
unsafe {
if (*self.ptr).ref_count.load(Ordering::SeqCst) == 1 {
BorrowedNodeRef::Exclusive(mem::transmute(self.ptr))
} else {
BorrowedNodeRef::Shared(mem::transmute(self.ptr))
}
}
}
}
impl<K, V, IS, H> Drop for NodeRef<K, V, IS, H> {
fn drop(&mut self) {
unsafe {
let node: &mut UnsafeNode<K, V, IS, H> = mem::transmute(self.ptr);
let old_count = node.ref_count.fetch_sub(1, Ordering::SeqCst);
debug_assert!(old_count >= 1);
if old_count == 1 {
node.destroy();
}
}
}
}
impl<K, V, IS, H> Clone for NodeRef<K, V, IS, H> {
fn clone(&self) -> NodeRef<K, V, IS, H> {
unsafe {
let node: &mut UnsafeNode<K, V, IS, H> = mem::transmute(self.ptr);
let old_count = node.ref_count.fetch_add(1, Ordering::SeqCst);
debug_assert!(old_count >= 1);
}
NodeRef { ptr: self.ptr }
}
}
//=-------------------------------------------------------------------------------------------------
// UnsafeNode
//=-------------------------------------------------------------------------------------------------
// The number of hash-value bits used per tree-level.
const BITS_PER_LEVEL: usize = 5;
// The deepest level the tree can have. Collision-nodes are use at this depth to avoid any further
// recursion.
const LAST_LEVEL: usize = (64 / BITS_PER_LEVEL) - 1;
// Used to mask off any unused bits from the hash key at a given level.
const LEVEL_BIT_MASK: u64 = (1 << BITS_PER_LEVEL) - 1;
// The minimum node capacity.
const MIN_CAPACITY: usize = 4;
// This struct should have the correct alignment for node entries.
struct AlignmentStruct<K, V, IS, H> {
_a: Arc<Vec<IS>>,
_b: IS,
_c: *const (),
_k: ::std::marker::PhantomData<K>,
_v: ::std::marker::PhantomData<V>,
_h: ::std::marker::PhantomData<H>,
}
// Bit signature of node entry types. Every node contains a single u64 designating the kinds of all
// its entries, which can either be a key-value pair, a reference to a sub-tree, or a
// collision-entry, containing a linear list of colliding key-value pairs.
const KVP_ENTRY: usize = 0b01;
const SUBTREE_ENTRY: usize = 0b10;
const COLLISION_ENTRY: usize = 0b11;
const INVALID_ENTRY: usize = 0b00;
// The central node type used by the implementation. Note that this struct just represents the
// header of the node data. The actual entries are allocated directly after this header, starting
// at the address of the `__entries` field.
#[repr(C)]
struct UnsafeNode<K, V, IS, H> {
// The current number of references to this node.
ref_count: AtomicUsize,
// The entry types of the of this node. Each two bits encode the type of one entry
// (key-value pair, subtree ref, or collision entry). See get_entry_type_code() and the above
// constants to learn about the encoding.
entry_types: EntryTypesType,
// A mask stating at which local keys (an integer between 0 and 31) an entry is exists.
mask: MaskType,
// The maximum number of entries this node can store.
capacity: u8,
// An artificial field ensuring the correct alignment of entries behind this header.
__entries: [AlignmentStruct<K, V, IS, H>; 0],
}
// A temporary reference to a node entry's content. This is a safe wrapper around the unsafe,
// low-level bitmask-based memory representation of node entries.
enum NodeEntryRef<'a, K, V, IS, H>
where K: 'a,
V: 'a,
IS: 'a,
H: 'a
{
Collision(&'a Arc<Vec<IS>>),
Item(&'a IS),
SubTree(&'a NodeRef<K, V, IS, H>)
}
impl<'a, K, V, IS, H> NodeEntryRef<'a, K, V, IS, H>
where K: Send+Sync,
V: Send+Sync,
IS: ItemStore<K, V>
{
// Clones the contents of a NodeEntryRef into a NodeEntryOwned value to be used elsewhere.
fn clone_out(&self) -> NodeEntryOwned<K, V, IS, H> {
match *self {
NodeEntryRef::Collision(r) => NodeEntryOwned::Collision(r.clone()),
NodeEntryRef::Item(is) => NodeEntryOwned::Item(is.clone()),
NodeEntryRef::SubTree(r) => NodeEntryOwned::SubTree(r.clone()),
}
}
}
// The same as NodeEntryRef but allowing for mutable access to the referenced node entry.
enum NodeEntryMutRef<'a, K, V, IS, H>
where K: 'a,
V: 'a,
IS: 'a,
H: 'a
{
Collision(&'a mut Arc<Vec<IS>>),
Item(&'a mut IS),
SubTree(&'a mut NodeRef<K, V, IS, H>)
}
// Similar to NodeEntryRef, but actually owning the entry data, so it can be moved around.
enum NodeEntryOwned<K, V, IS, H> {
Collision(Arc<Vec<IS>>),
Item(IS),
SubTree(NodeRef<K, V, IS, H>)
}
// This datatype is used to communicate between consecutive tree-levels about what to do when
// a change has occured below. When removing something from a subtree it sometimes makes sense to
// remove the entire subtree and replace it with a directly contained key-value pair in order to
// safe space and---later on during searches---time.
enum RemovalResult<K, V, IS, H> {
// Don't do anything
NoChange,
// Replace the sub-tree entry with another sub-tree entry pointing to the given node
ReplaceSubTree(NodeRef<K, V, IS, H>),
// Collapse the sub-tree into a singe-item entry
CollapseSubTree(IS),
// Completely remove the entry
KillSubTree
}
// impl UnsafeNode
impl<'a, K, V, IS, H> UnsafeNode<K, V, IS, H>
where K: 'a,
V: 'a,
IS: 'a,
H: 'a
{
// Retrieve the type code of the entry with the given index. Is always one of
// {KVP_ENTRY, SUBTREE_ENTRY, COLLISION_ENTRY}
fn get_entry_type_code(&self, index: usize) -> usize {
debug_assert!(index < self.entry_count());
let type_code = ((self.entry_types >> (index * 2)) & 0b11) as usize;
debug_assert!(type_code != INVALID_ENTRY);
type_code
}
// Set the type code of the entry with the given index. Must be one of
// {KVP_ENTRY, SUBTREE_ENTRY, COLLISION_ENTRY}
fn set_entry_type_code(&mut self, index: usize, type_code: usize) {
debug_assert!(index < self.entry_count());
debug_assert!(type_code <= 0b11 && type_code != INVALID_ENTRY);
self.entry_types = (self.entry_types & !(0b11 << (index * 2))) |
((type_code as EntryTypesType) << (index * 2));
}
// Get a raw pointer the an entry.
fn get_entry_ptr(&self, index: usize) -> *const u8 {
debug_assert!(index < self.entry_count());
unsafe {
let base: *const u8 = mem::transmute(&self.__entries);
base.offset((index * UnsafeNode::<K, V, IS, H>::node_entry_size()) as isize)
}
}
// Get a temporary, readonly reference to a node entry.
fn get_entry(&'a self, index: usize) -> NodeEntryRef<'a, K, V, IS, H> {
let entry_ptr = self.get_entry_ptr(index);
unsafe {
match self.get_entry_type_code(index) {
KVP_ENTRY => NodeEntryRef::Item(mem::transmute(entry_ptr)),
SUBTREE_ENTRY => NodeEntryRef::SubTree(mem::transmute(entry_ptr)),
COLLISION_ENTRY => NodeEntryRef::Collision(mem::transmute(entry_ptr)),
_ => panic!("Invalid entry type code")
}
}
}
// Get a temporary, mutable reference to a node entry.
fn get_entry_mut(&'a mut self, index: usize) -> NodeEntryMutRef<'a, K, V, IS, H> {
let entry_ptr = self.get_entry_ptr(index);
unsafe {
match self.get_entry_type_code(index) {
KVP_ENTRY => NodeEntryMutRef::Item(mem::transmute(entry_ptr)),
SUBTREE_ENTRY => NodeEntryMutRef::SubTree(mem::transmute(entry_ptr)),
COLLISION_ENTRY => NodeEntryMutRef::Collision(mem::transmute(entry_ptr)),
_ => panic!("Invalid entry type code")
}
}
}
// Initialize the entry with the given data. This will set the correct type
// code for the entry and move the given value to the correct memory
// position. It will not modify the nodes entry mask.
fn init_entry(&mut self, index: usize, entry: NodeEntryOwned<K, V, IS, H>) {
let entry_ptr = self.get_entry_ptr(index);
unsafe {
match entry {
NodeEntryOwned::Item(kvp) => {
ptr::write(mem::transmute(entry_ptr), kvp);
self.set_entry_type_code(index, KVP_ENTRY);
}
NodeEntryOwned::SubTree(node_ref) => {
ptr::write(mem::transmute(entry_ptr), node_ref);
self.set_entry_type_code(index, SUBTREE_ENTRY);
}
NodeEntryOwned::Collision(arc) => {
ptr::write(mem::transmute(entry_ptr), arc);
self.set_entry_type_code(index, COLLISION_ENTRY);
}
}
}
}
// The current number of entries stored in the node. Always <= the node's capacity.
fn entry_count(&self) -> usize {
bit_count(self.mask)
}
// The size in bytes of one node entry, containing any necessary padding bytes.
fn node_entry_size() -> usize {
::std::cmp::max(
mem::size_of::<IS>(),
::std::cmp::max(
mem::size_of::<Arc<Vec<IS>>>(),
mem::size_of::<NodeRef<K, V, IS, H>>(),
)
)
}
// Allocates a new node instance with the given mask and capacity. The memory for the node is
// allocated from the exchange heap. The capacity of the node is fixed from here on after.
// The entries (including the entry_types bitfield) is not initialized by this call. Entries
// must be initialized properly with init_entry() after allocation.
fn alloc(mask: MaskType, capacity: usize) -> NodeRef<K, V, IS, H> {
debug_assert!(size_of_zero_entry_array::<K, V, IS, H>() == 0);
fn size_of_zero_entry_array<K, V, IS, H>() -> usize {
let node: UnsafeNode<K, V, IS, H> = UnsafeNode {
ref_count: AtomicUsize::new(0),
entry_types: 0,
mask: 0,
capacity: 0,
__entries: [],
};
mem::size_of_val(&node.__entries)
}
let align = mem::align_of::<AlignmentStruct<K, V, IS, H>>();
let entry_count = bit_count(mask);
debug_assert!(entry_count <= capacity);
let header_size = align_to(mem::size_of::<UnsafeNode<K, V, IS, H>>(), align);
let node_size = header_size + capacity * UnsafeNode::<K, V, IS, H>::node_entry_size();
unsafe {
let node_ptr: *mut UnsafeNode<K, V, IS, H> = mem::transmute(allocate(node_size, align));
ptr::write(&mut (*node_ptr).ref_count, AtomicUsize::new(1));
ptr::write(&mut (*node_ptr).entry_types, 0);
ptr::write(&mut (*node_ptr).mask, mask);
ptr::write(&mut (*node_ptr).capacity, capacity as u8);
NodeRef { ptr: node_ptr }
}
}
// Destroy the given node by first `dropping` all contained entries and then free the node's
// memory.
fn destroy(&mut self) {
unsafe {
for i in (0 .. self.entry_count()) {
self.drop_entry(i)
}
// Let's use malloc and free for raw memory allocation so this library
// build on 'stable':
let align = mem::align_of::<AlignmentStruct<K, V, IS, H>>();
let header_size = align_to(mem::size_of::<UnsafeNode<K, V, IS, H>>(), align);
let node_size = header_size + (self.capacity as usize) * UnsafeNode::<K, V, IS, H>::node_entry_size();
deallocate(mem::transmute(self), node_size, align);
}
}
// Drops a single entry. Does not modify the entry_types or mask field of the node, just calls
// the destructor of the entry at the given index.
unsafe fn drop_entry(&mut self, index: usize) {
// destroy the contained object, trick from Rc
match self.get_entry_mut(index) {
NodeEntryMutRef::Item(item_ref) => {
let _ = ptr::read(item_ref as *mut IS as *const IS);
}
NodeEntryMutRef::Collision(item_ref) => {
let _ = ptr::read(item_ref as *mut Arc<Vec<IS>> as *const Arc<Vec<IS>>);
}
NodeEntryMutRef::SubTree(item_ref) => {
let _ = ptr::read(item_ref as *mut NodeRef<K, V, IS, H> as *const NodeRef<K, V, IS, H>);
}
}
}
}
// impl UnsafeNode (continued)
impl<K, V, IS, H> UnsafeNode<K, V, IS, H>
where K: Eq+Send+Sync+Hash,
V: Send+Sync,
IS: ItemStore<K, V>,
H: Hasher+Default
{
// Insert a new key-value pair into the tree. The existing tree is not modified and a new tree
// is created. This new tree will share most nodes with the existing one.
fn insert(&self,
// The *remaining* hash value. For every level down the tree, this value is shifted
// to the right by `BITS_PER_LEVEL`
hash: u64,
// The current level of the tree
level: usize,
// The key-value pair to be inserted
new_kvp: IS,
// The number of newly inserted items. Must be set to either 0 (if an existing item is
// replaced) or 1 (if there was not item with the given key yet). Used to keep track
// of the trees total item count
insertion_count: &mut usize)
// Reference to the new tree containing the inserted element
-> NodeRef<K, V, IS, H> {
debug_assert!(level <= LAST_LEVEL);
let local_key = (hash & LEVEL_BIT_MASK) as usize;
// See if the slot is free
if (self.mask & (1 << local_key)) == 0 {
// If yes, then fill it with a single-item entry
*insertion_count = 1;
let new_node = self.copy_with_new_entry(local_key, NodeEntryOwned::Item(new_kvp));
return new_node;
}
let index = get_index(self.mask, local_key);
match self.get_entry(index) {
NodeEntryRef::Item(existing_kvp_ref) => {
let existing_key = existing_kvp_ref.key();
if *existing_key == *new_kvp.key() {
*insertion_count = 0;
// Replace entry for the given key
self.copy_with_new_entry(local_key, NodeEntryOwned::Item(new_kvp))
} else if level != LAST_LEVEL {
*insertion_count = 1;
// There already is an entry with different key but same hash value, so push
// everything down one level:
// 1. build the hashes for the level below
let new_hash = hash >> BITS_PER_LEVEL;
let existing_hash = hash_of::<K, H>(&existing_key) >> (BITS_PER_LEVEL * (level + 1));
// 2. create the sub tree, containing the two items
let new_sub_tree = UnsafeNode::new_with_entries(new_kvp,
new_hash,
existing_kvp_ref,
existing_hash,
level + 1);
// 3. return a copy of this node with the single-item entry replaced by the new
// subtree entry
self.copy_with_new_entry(local_key, NodeEntryOwned::SubTree(new_sub_tree))
} else {
*insertion_count = 1;
// If we have already exhausted all bits from the hash value, put everything in
// collision node
let items = vec!(new_kvp, existing_kvp_ref.clone());
self.copy_with_new_entry(local_key, NodeEntryOwned::Collision(Arc::new(items)))
}
}
NodeEntryRef::Collision(items_arc) => {
debug_assert!(level == LAST_LEVEL);
let items = &*items_arc;
let position = items.iter().position(|kvp2| *kvp2.key() == *new_kvp.key());
let new_items = match position {
None => {
*insertion_count = 1;
let mut new_items = Vec::with_capacity(items.len() + 1);
new_items.push(new_kvp);
new_items.extend(items.iter().cloned());
new_items
}
Some(position) => {
*insertion_count = 0;
let item_count = items.len();
let mut new_items = Vec::with_capacity(item_count);
if position > 0 {
new_items.extend(items.iter().take(position).cloned());
}
new_items.push(new_kvp);
if position < item_count - 1 {
new_items.extend(items.iter().skip(position + 1).cloned());
}
debug_assert!(new_items.len() == item_count);
new_items
}
};
self.copy_with_new_entry(local_key, NodeEntryOwned::Collision(Arc::new(new_items)))
}
NodeEntryRef::SubTree(sub_tree_ref) => {
let new_sub_tree = sub_tree_ref.borrow().insert(hash >> BITS_PER_LEVEL,
level + 1,
new_kvp,
insertion_count);
self.copy_with_new_entry(local_key, NodeEntryOwned::SubTree(new_sub_tree))
}
}
}
// Same as `insert()` above, but will do the insertion in-place (i.e. without copying) if the
// node has enough capacity. Note, that we already have made sure at this point that there is
// only exactly one reference to the node (otherwise we wouldn't have `&mut self`), so it is
// safe to modify it in-place.
// If there is not enough space for a new entry, then fall back to copying via a regular call
// to `insert()`.
fn try_insert_in_place(&mut self,
hash: u64,
level: usize,
new_kvp: IS,
insertion_count: &mut usize)
-> Option<NodeRef<K, V, IS, H>> {
debug_assert!(level <= LAST_LEVEL);
let local_key = (hash & LEVEL_BIT_MASK) as usize;
// See if the slot is free
if (self.mask & (1 << local_key)) == 0 {
if self.entry_count() < self.capacity as usize {
// If yes, then fill it with a single-item entry
*insertion_count = 1;
self.insert_entry_in_place(local_key, NodeEntryOwned::Item(new_kvp));
return None;
} else {
// else fall back to copying
return Some(self.insert(hash, level, new_kvp, insertion_count));
}
}
let index = get_index(self.mask, local_key);
// If there is no space left in this node but we would need it, again fall back to copying
if self.entry_count() == self.capacity as usize &&
self.get_entry_type_code(index) != SUBTREE_ENTRY {
return Some(self.insert(hash, level, new_kvp, insertion_count));
}
let new_entry = match self.get_entry_mut(index) {
NodeEntryMutRef::Item(existing_kvp_ref) => {
let existing_key = existing_kvp_ref.key();
if *existing_key == *new_kvp.key() {
*insertion_count = 0;
// Replace entry for the given key
Some(NodeEntryOwned::Item(new_kvp))
} else if level != LAST_LEVEL {
*insertion_count = 1;
// There already is an entry with different key but same hash value, so push
// everything down one level:
// 1. build the hashes for the level below
let new_hash = hash >> BITS_PER_LEVEL;
let existing_hash = hash_of::<K, H>(existing_key) >> (BITS_PER_LEVEL * (level + 1));
// 2. create the sub tree, containing the two items
let new_sub_tree = UnsafeNode::new_with_entries(new_kvp,
new_hash,
existing_kvp_ref,
existing_hash,
level + 1);
// 3. replace the ItemEntryRef entry with the subtree entry
Some(NodeEntryOwned::SubTree(new_sub_tree))
} else {
*insertion_count = 1;
// If we have already exhausted all bits from the hash value, put everything in
// collision node
let items = vec!(new_kvp, existing_kvp_ref.clone());
let collision_entry = NodeEntryOwned::Collision(Arc::new(items));
Some(collision_entry)
}
}
NodeEntryMutRef::Collision(items) => {
debug_assert!(level == LAST_LEVEL);
let position = items.iter().position(|kvp2| *kvp2.key() == *new_kvp.key());
let new_items = match position {
None => {
*insertion_count = 1;
let mut new_items = Vec::with_capacity(items.len() + 1);
new_items.push(new_kvp);
new_items.extend(items.iter().cloned());
new_items
}
Some(position) => {
*insertion_count = 0;
let item_count = items.len();
let mut new_items = Vec::with_capacity(item_count);
if position > 0 {
new_items.extend(items.iter().take(position).cloned());
}
new_items.push(new_kvp);
if position < item_count - 1 {
new_items.extend(items.iter().skip(position + 1).cloned());
}
debug_assert!(new_items.len() == item_count);
new_items
}
};
Some(NodeEntryOwned::Collision(Arc::new(new_items)))
}
NodeEntryMutRef::SubTree(subtree_mut_ref) => {
match subtree_mut_ref.try_borrow_owned() {
BorrowedNodeRef::Shared(subtree) => {
Some(NodeEntryOwned::SubTree(subtree.insert(hash >> BITS_PER_LEVEL,
level + 1,
new_kvp,
insertion_count)))
}
BorrowedNodeRef::Exclusive(subtree) => {
match subtree.try_insert_in_place(hash >> BITS_PER_LEVEL,
level + 1,
new_kvp.clone(),
insertion_count) {
Some(new_sub_tree) => Some(NodeEntryOwned::SubTree(new_sub_tree)),
None => None
}
}
}
}
};
match new_entry {
Some(e) => {
self.insert_entry_in_place(local_key, e);
}
None => {
/* No new entry to be inserted, because the subtree could be modified in-place */
}
}
return None;
}
// Remove the item with the given key from the tree. Parameters correspond to this of
// `insert()`. The result tells the call (the parent level in the tree) what it should do.
fn remove(&self,
hash: u64,
level: usize,
key: &K,
removal_count: &mut usize)
-> RemovalResult<K, V, IS, H> {
debug_assert!(level <= LAST_LEVEL);
let local_key = (hash & LEVEL_BIT_MASK) as usize;
if (self.mask & (1 << local_key)) == 0 {
*removal_count = 0;
return RemovalResult::NoChange;
}
let index = get_index(self.mask, local_key);
match self.get_entry(index) {
NodeEntryRef::Item(existing_kvp_ref) => {
if *existing_kvp_ref.key() == *key {
*removal_count = 1;
self.collapse_kill_or_change(local_key, index)
} else {
*removal_count = 0;
RemovalResult::NoChange
}
}
NodeEntryRef::Collision(items_arc) => {
debug_assert!(level == LAST_LEVEL);
let items = &*items_arc;
let position = items.iter().position(|kvp| *kvp.key() == *key);
match position {
None => {
*removal_count = 0;
RemovalResult::NoChange
},
Some(position) => {
*removal_count = 1;
let item_count = items.len() - 1;
// The new entry can either still be a collision node, or it can be a simple
// single-item node if the hash collision has been resolved by the removal
let new_entry = if item_count > 1 {
let mut new_items = Vec::with_capacity(item_count);
if position > 0 {
new_items.extend(items.iter().take(position).cloned());
}
if position < item_count - 1 {
new_items.extend(items.iter().skip(position + 1).cloned());
}
debug_assert!(new_items.len() == item_count);
NodeEntryOwned::Collision(Arc::new(new_items))
} else {
debug_assert!(items.len() == 2);
debug_assert!(position == 0 || position == 1);
let index_of_remaining_item = 1 - position;
let kvp = items[index_of_remaining_item].clone();
NodeEntryOwned::Item(kvp)
};
let new_sub_tree = self.copy_with_new_entry(local_key, new_entry);
RemovalResult::ReplaceSubTree(new_sub_tree)
}
}
}
NodeEntryRef::SubTree(sub_tree_ref) => {
let result = sub_tree_ref.borrow().remove(hash >> BITS_PER_LEVEL,
level + 1,
key,
removal_count);
match result {
RemovalResult::NoChange => RemovalResult::NoChange,
RemovalResult::ReplaceSubTree(x) => {
RemovalResult::ReplaceSubTree(
self.copy_with_new_entry(local_key,
NodeEntryOwned::SubTree(x)))
}
RemovalResult::CollapseSubTree(kvp) => {
if bit_count(self.mask) == 1 {
RemovalResult::CollapseSubTree(kvp)
} else {
RemovalResult::ReplaceSubTree(
self.copy_with_new_entry(local_key,
NodeEntryOwned::Item(kvp)))
}
},
RemovalResult::KillSubTree => {
self.collapse_kill_or_change(local_key, index)
}
}
}
}
}
// Same as `remove()` but will do the modification in-place. As with `try_insert_in_place()` we
// already have made sure at this point that there is only exactly one reference to the node
// (otherwise we wouldn't have `&mut self`), so it is safe to modify it in-place.
fn remove_in_place(&mut self,
hash: u64,
level: usize,
key: &K,
removal_count: &mut usize)
-> RemovalResult<K, V, IS, H> {
debug_assert!(level <= LAST_LEVEL);
let local_key = (hash & LEVEL_BIT_MASK) as usize;
let mask = self.mask;
if (mask & (1 << local_key)) == 0 {
*removal_count = 0;
return RemovalResult::NoChange;
}
let index = get_index(mask, local_key);
enum Action<K, V, IS, H> {
CollapseKillOrChange,
NoAction,
ReplaceEntry(NodeEntryOwned<K, V, IS, H>)
}
let action: Action<K, V, IS, H> = match self.get_entry_mut(index) {
NodeEntryMutRef::Item(existing_kvp_ref) => {
if *existing_kvp_ref.key() == *key {
*removal_count = 1;
Action::CollapseKillOrChange
} else {
*removal_count = 0;
Action::NoAction
}
}
NodeEntryMutRef::Collision(items) => {
debug_assert!(level == LAST_LEVEL);
let position = items.iter().position(|kvp| *kvp.key() == *key);
match position {
None => {
*removal_count = 0;
Action::NoAction
},
Some(position) => {
*removal_count = 1;
let item_count = items.len() - 1;
// The new entry can either still be a collision node, or it can be a simple
// single-item node if the hash collision has been resolved by the removal
let new_entry = if item_count > 1 {
let mut new_items = Vec::with_capacity(item_count);
if position > 0 {
new_items.extend(items.iter().take(position).cloned());
}
if position < item_count - 1 {
new_items.extend(items.iter().skip(position + 1).cloned());
}
debug_assert!(new_items.len() == item_count);
NodeEntryOwned::Collision(Arc::new(new_items))
} else {
debug_assert!(items.len() == 2);
debug_assert!(position == 0 || position == 1);
let index_of_remaining_item = 1 - position;
let kvp = (**items)[index_of_remaining_item].clone();
NodeEntryOwned::Item(kvp)
};
Action::ReplaceEntry(new_entry)
}
}
}
NodeEntryMutRef::SubTree(sub_tree_ref) => {
let result = match sub_tree_ref.try_borrow_owned() {
BorrowedNodeRef::Shared(node_ref) => node_ref.remove(hash >> BITS_PER_LEVEL,
level + 1,
key,
removal_count),
BorrowedNodeRef::Exclusive(node_ref) => node_ref.remove_in_place(hash >> BITS_PER_LEVEL,
level + 1,
key,
removal_count)
};
match result {
RemovalResult::NoChange => Action::NoAction,
RemovalResult::ReplaceSubTree(x) => {
Action::ReplaceEntry(NodeEntryOwned::SubTree(x))
}
RemovalResult::CollapseSubTree(kvp) => {
if bit_count(mask) == 1 {
return RemovalResult::CollapseSubTree(kvp);
}
Action::ReplaceEntry(NodeEntryOwned::Item(kvp))
},
RemovalResult::KillSubTree => {
Action::CollapseKillOrChange
}
}
}
};
match action {
Action::NoAction => RemovalResult::NoChange,
Action::CollapseKillOrChange => self.collapse_kill_or_change_in_place(local_key, index),
Action::ReplaceEntry(new_entry) => {
self.insert_entry_in_place(local_key, new_entry);
RemovalResult::NoChange
}
}
}
// Determines how the parent node should handle the removal of the entry at local_key from this
// node.
fn collapse_kill_or_change(&self,
local_key: usize,
entry_index: usize)
-> RemovalResult<K, V, IS, H> {
let new_entry_count = bit_count(self.mask) - 1;
if new_entry_count > 1 {
RemovalResult::ReplaceSubTree(self.copy_without_entry(local_key))
} else if new_entry_count == 1 {
let other_index = 1 - entry_index;
match self.get_entry(other_index) {
NodeEntryRef::Item(kvp_ref) => {
RemovalResult::CollapseSubTree(kvp_ref.clone())
}
_ => RemovalResult::ReplaceSubTree(self.copy_without_entry(local_key))
}
} else {
debug_assert!(new_entry_count == 0);
RemovalResult::KillSubTree
}
}
// Same as `collapse_kill_or_change()` but will do the modification in-place.
fn collapse_kill_or_change_in_place(&mut self,
local_key: usize,
entry_index: usize)
-> RemovalResult<K, V, IS, H> {
let new_entry_count = self.entry_count() - 1;
if new_entry_count > 1 {
self.remove_entry_in_place(local_key);
RemovalResult::NoChange
} else if new_entry_count == 1 {
let other_index = 1 - entry_index;
match self.get_entry(other_index) {
NodeEntryRef::Item(kvp_ref) => {
return RemovalResult::CollapseSubTree(kvp_ref.clone())
}
_ => { /* */ }
}
self.remove_entry_in_place(local_key);
RemovalResult::NoChange
} else {
debug_assert!(new_entry_count == 0);
RemovalResult::KillSubTree
}
}
// Copies this node with a new entry at `local_key`. Might replace an old entry.
fn copy_with_new_entry(&self,
local_key: usize,
new_entry: NodeEntryOwned<K, V, IS, H>)
-> NodeRef<K, V, IS, H> {
let replace_old_entry = (self.mask & (1 << local_key)) != 0;
let new_mask: MaskType = self.mask | (1 << local_key);
let mut new_node_ref = UnsafeNode::alloc(new_mask, self.expanded_capacity());
{
let new_node = new_node_ref.borrow_mut();
let index = get_index(new_mask, local_key);
let mut old_i = 0;
let mut new_i = 0;
// Copy up to index
while old_i < index {
new_node.init_entry(new_i, self.get_entry(old_i).clone_out());
old_i += 1;
new_i += 1;
}
// Add new entry
new_node.init_entry(new_i, new_entry);
new_i += 1;
if replace_old_entry {
// Skip the replaced value
old_i += 1;
}
// Copy the rest
while old_i < self.entry_count() {
new_node.init_entry(new_i, self.get_entry(old_i).clone_out());
old_i += 1;
new_i += 1;
}
debug_assert!(new_i == new_node.entry_count() as usize);
}
return new_node_ref;
}
// Inserts a new node entry in-place. Will take care of modifying node entry data, including the
// node's mask and entry_types fields.
fn insert_entry_in_place(&mut self,
local_key: usize,
new_entry: NodeEntryOwned<K, V, IS, H>) {