forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hamt.c
2895 lines (2293 loc) · 77.2 KB
/
hamt.c
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
#include "Python.h"
#include "pycore_bitutils.h" // _Py_popcount32()
#include "pycore_hamt.h"
#include "pycore_initconfig.h" // _PyStatus_OK()
#include "pycore_long.h" // _PyLong_Format()
#include "pycore_object.h" // _PyObject_GC_TRACK()
#include <stddef.h> // offsetof()
/*
This file provides an implementation of an immutable mapping using the
Hash Array Mapped Trie (or HAMT) datastructure.
This design allows to have:
1. Efficient copy: immutable mappings can be copied by reference,
making it an O(1) operation.
2. Efficient mutations: due to structural sharing, only a portion of
the trie needs to be copied when the collection is mutated. The
cost of set/delete operations is O(log N).
3. Efficient lookups: O(log N).
(where N is number of key/value items in the immutable mapping.)
HAMT
====
The core idea of HAMT is that the shape of the trie is encoded into the
hashes of keys.
Say we want to store a K/V pair in our mapping. First, we calculate the
hash of K, let's say it's 19830128, or in binary:
0b1001011101001010101110000 = 19830128
Now let's partition this bit representation of the hash into blocks of
5 bits each:
0b00_00000_10010_11101_00101_01011_10000 = 19830128
(6) (5) (4) (3) (2) (1)
Each block of 5 bits represents a number between 0 and 31. So if we have
a tree that consists of nodes, each of which is an array of 32 pointers,
those 5-bit blocks will encode a position on a single tree level.
For example, storing the key K with hash 19830128, results in the following
tree structure:
(array of 32 pointers)
+---+ -- +----+----+----+ -- +----+
root node | 0 | .. | 15 | 16 | 17 | .. | 31 | 0b10000 = 16 (1)
(level 1) +---+ -- +----+----+----+ -- +----+
|
+---+ -- +----+----+----+ -- +----+
a 2nd level node | 0 | .. | 10 | 11 | 12 | .. | 31 | 0b01011 = 11 (2)
+---+ -- +----+----+----+ -- +----+
|
+---+ -- +----+----+----+ -- +----+
a 3rd level node | 0 | .. | 04 | 05 | 06 | .. | 31 | 0b00101 = 5 (3)
+---+ -- +----+----+----+ -- +----+
|
+---+ -- +----+----+----+----+
a 4th level node | 0 | .. | 04 | 29 | 30 | 31 | 0b11101 = 29 (4)
+---+ -- +----+----+----+----+
|
+---+ -- +----+----+----+ -- +----+
a 5th level node | 0 | .. | 17 | 18 | 19 | .. | 31 | 0b10010 = 18 (5)
+---+ -- +----+----+----+ -- +----+
|
+--------------+
|
+---+ -- +----+----+----+ -- +----+
a 6th level node | 0 | .. | 15 | 16 | 17 | .. | 31 | 0b00000 = 0 (6)
+---+ -- +----+----+----+ -- +----+
|
V -- our value (or collision)
To rehash: for a K/V pair, the hash of K encodes where in the tree V will
be stored.
To optimize memory footprint and handle hash collisions, our implementation
uses three different types of nodes:
* A Bitmap node;
* An Array node;
* A Collision node.
Because we implement an immutable dictionary, our nodes are also
immutable. Therefore, when we need to modify a node, we copy it, and
do that modification to the copy.
Array Nodes
-----------
These nodes are very simple. Essentially they are arrays of 32 pointers
we used to illustrate the high-level idea in the previous section.
We use Array nodes only when we need to store more than 16 pointers
in a single node.
Array nodes do not store key objects or value objects. They are used
only as an indirection level - their pointers point to other nodes in
the tree.
Bitmap Node
-----------
Allocating a new 32-pointers array for every node of our tree would be
very expensive. Unless we store millions of keys, most of tree nodes would
be very sparse.
When we have less than 16 elements in a node, we don't want to use the
Array node, that would mean that we waste a lot of memory. Instead,
we can use bitmap compression and can have just as many pointers
as we need!
Bitmap nodes consist of two fields:
1. An array of pointers. If a Bitmap node holds N elements, the
array will be of N pointers.
2. A 32bit integer -- a bitmap field. If an N-th bit is set in the
bitmap, it means that the node has an N-th element.
For example, say we need to store a 3 elements sparse array:
+---+ -- +---+ -- +----+ -- +----+
| 0 | .. | 4 | .. | 11 | .. | 17 |
+---+ -- +---+ -- +----+ -- +----+
| | |
o1 o2 o3
We allocate a three-pointer Bitmap node. Its bitmap field will be
then set to:
0b_00100_00010_00000_10000 == (1 << 17) | (1 << 11) | (1 << 4)
To check if our Bitmap node has an I-th element we can do:
bitmap & (1 << I)
And here's a formula to calculate a position in our pointer array
which would correspond to an I-th element:
popcount(bitmap & ((1 << I) - 1))
Let's break it down:
* `popcount` is a function that returns a number of bits set to 1;
* `((1 << I) - 1)` is a mask to filter the bitmask to contain bits
set to the *right* of our bit.
So for our 17, 11, and 4 indexes:
* bitmap & ((1 << 17) - 1) == 0b100000010000 => 2 bits are set => index is 2.
* bitmap & ((1 << 11) - 1) == 0b10000 => 1 bit is set => index is 1.
* bitmap & ((1 << 4) - 1) == 0b0 => 0 bits are set => index is 0.
To conclude: Bitmap nodes are just like Array nodes -- they can store
a number of pointers, but use bitmap compression to eliminate unused
pointers.
Bitmap nodes have two pointers for each item:
+----+----+----+----+ -- +----+----+
| k1 | v1 | k2 | v2 | .. | kN | vN |
+----+----+----+----+ -- +----+----+
When kI == NULL, vI points to another tree level.
When kI != NULL, the actual key object is stored in kI, and its
value is stored in vI.
Collision Nodes
---------------
Collision nodes are simple arrays of pointers -- two pointers per
key/value. When there's a hash collision, say for k1/v1 and k2/v2
we have `hash(k1)==hash(k2)`. Then our collision node will be:
+----+----+----+----+
| k1 | v1 | k2 | v2 |
+----+----+----+----+
Tree Structure
--------------
All nodes are PyObjects.
The `PyHamtObject` object has a pointer to the root node (h_root),
and has a length field (h_count).
High-level functions accept a PyHamtObject object and dispatch to
lower-level functions depending on what kind of node h_root points to.
Operations
==========
There are three fundamental operations on an immutable dictionary:
1. "o.assoc(k, v)" will return a new immutable dictionary, that will be
a copy of "o", but with the "k/v" item set.
Functions in this file:
hamt_node_assoc, hamt_node_bitmap_assoc,
hamt_node_array_assoc, hamt_node_collision_assoc
`hamt_node_assoc` function accepts a node object, and calls
other functions depending on its actual type.
2. "o.find(k)" will lookup key "k" in "o".
Functions:
hamt_node_find, hamt_node_bitmap_find,
hamt_node_array_find, hamt_node_collision_find
3. "o.without(k)" will return a new immutable dictionary, that will be
a copy of "o", buth without the "k" key.
Functions:
hamt_node_without, hamt_node_bitmap_without,
hamt_node_array_without, hamt_node_collision_without
Further Reading
===============
1. http://blog.higher-order.net/2009/09/08/understanding-clojures-persistenthashmap-deftwice.html
2. http://blog.higher-order.net/2010/08/16/assoc-and-clojures-persistenthashmap-part-ii.html
3. Clojure's PersistentHashMap implementation:
https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/PersistentHashMap.java
Debug
=====
The HAMT datatype is accessible for testing purposes under the
`_testcapi` module:
>>> from _testcapi import hamt
>>> h = hamt()
>>> h2 = h.set('a', 2)
>>> h3 = h2.set('b', 3)
>>> list(h3)
['a', 'b']
When CPython is built in debug mode, a '__dump__()' method is available
to introspect the tree:
>>> print(h3.__dump__())
HAMT(len=2):
BitmapNode(size=4 count=2 bitmap=0b110 id=0x10eb9d9e8):
'a': 2
'b': 3
*/
#define IS_ARRAY_NODE(node) Py_IS_TYPE(node, &_PyHamt_ArrayNode_Type)
#define IS_BITMAP_NODE(node) Py_IS_TYPE(node, &_PyHamt_BitmapNode_Type)
#define IS_COLLISION_NODE(node) Py_IS_TYPE(node, &_PyHamt_CollisionNode_Type)
/* Return type for 'find' (lookup a key) functions.
* F_ERROR - an error occurred;
* F_NOT_FOUND - the key was not found;
* F_FOUND - the key was found.
*/
typedef enum {F_ERROR, F_NOT_FOUND, F_FOUND} hamt_find_t;
/* Return type for 'without' (delete a key) functions.
* W_ERROR - an error occurred;
* W_NOT_FOUND - the key was not found: there's nothing to delete;
* W_EMPTY - the key was found: the node/tree would be empty
if the key is deleted;
* W_NEWNODE - the key was found: a new node/tree is returned
without that key.
*/
typedef enum {W_ERROR, W_NOT_FOUND, W_EMPTY, W_NEWNODE} hamt_without_t;
/* Low-level iterator protocol type.
* I_ITEM - a new item has been yielded;
* I_END - the whole tree was visited (similar to StopIteration).
*/
typedef enum {I_ITEM, I_END} hamt_iter_t;
#define HAMT_ARRAY_NODE_SIZE 32
typedef struct {
PyObject_HEAD
PyHamtNode *a_array[HAMT_ARRAY_NODE_SIZE];
Py_ssize_t a_count;
} PyHamtNode_Array;
typedef struct {
PyObject_VAR_HEAD
int32_t c_hash;
PyObject *c_array[1];
} PyHamtNode_Collision;
static PyHamtObject *
hamt_alloc(void);
static PyHamtNode *
hamt_node_assoc(PyHamtNode *node,
uint32_t shift, int32_t hash,
PyObject *key, PyObject *val, int* added_leaf);
static hamt_without_t
hamt_node_without(PyHamtNode *node,
uint32_t shift, int32_t hash,
PyObject *key,
PyHamtNode **new_node);
static hamt_find_t
hamt_node_find(PyHamtNode *node,
uint32_t shift, int32_t hash,
PyObject *key, PyObject **val);
#ifdef Py_DEBUG
static int
hamt_node_dump(PyHamtNode *node,
_PyUnicodeWriter *writer, int level);
#endif
static PyHamtNode *
hamt_node_array_new(Py_ssize_t);
static PyHamtNode *
hamt_node_collision_new(int32_t hash, Py_ssize_t size);
static inline Py_ssize_t
hamt_node_collision_count(PyHamtNode_Collision *node);
#ifdef Py_DEBUG
static void
_hamt_node_array_validate(void *obj_raw)
{
PyObject *obj = _PyObject_CAST(obj_raw);
assert(IS_ARRAY_NODE(obj));
PyHamtNode_Array *node = (PyHamtNode_Array*)obj;
Py_ssize_t i = 0, count = 0;
for (; i < HAMT_ARRAY_NODE_SIZE; i++) {
if (node->a_array[i] != NULL) {
count++;
}
}
assert(count == node->a_count);
}
#define VALIDATE_ARRAY_NODE(NODE) \
do { _hamt_node_array_validate(NODE); } while (0);
#else
#define VALIDATE_ARRAY_NODE(NODE)
#endif
/* Returns -1 on error */
static inline int32_t
hamt_hash(PyObject *o)
{
Py_hash_t hash = PyObject_Hash(o);
#if SIZEOF_PY_HASH_T <= 4
return hash;
#else
if (hash == -1) {
/* exception */
return -1;
}
/* While it's somewhat suboptimal to reduce Python's 64 bit hash to
32 bits via XOR, it seems that the resulting hash function
is good enough (this is also how Long type is hashed in Java.)
Storing 10, 100, 1000 Python strings results in a relatively
shallow and uniform tree structure.
Also it's worth noting that it would be possible to adapt the tree
structure to 64 bit hashes, but that would increase memory pressure
and provide little to no performance benefits for collections with
fewer than billions of key/value pairs.
Important: do not change this hash reducing function. There are many
tests that need an exact tree shape to cover all code paths and
we do that by specifying concrete values for test data's `__hash__`.
If this function is changed most of the regression tests would
become useless.
*/
int32_t xored = (int32_t)(hash & 0xffffffffl) ^ (int32_t)(hash >> 32);
return xored == -1 ? -2 : xored;
#endif
}
static inline uint32_t
hamt_mask(int32_t hash, uint32_t shift)
{
return (((uint32_t)hash >> shift) & 0x01f);
}
static inline uint32_t
hamt_bitpos(int32_t hash, uint32_t shift)
{
return (uint32_t)1 << hamt_mask(hash, shift);
}
static inline uint32_t
hamt_bitindex(uint32_t bitmap, uint32_t bit)
{
return (uint32_t)_Py_popcount32(bitmap & (bit - 1));
}
/////////////////////////////////// Dump Helpers
#ifdef Py_DEBUG
static int
_hamt_dump_ident(_PyUnicodeWriter *writer, int level)
{
/* Write `' ' * level` to the `writer` */
PyObject *str = NULL;
PyObject *num = NULL;
PyObject *res = NULL;
int ret = -1;
str = PyUnicode_FromString(" ");
if (str == NULL) {
goto error;
}
num = PyLong_FromLong((long)level);
if (num == NULL) {
goto error;
}
res = PyNumber_Multiply(str, num);
if (res == NULL) {
goto error;
}
ret = _PyUnicodeWriter_WriteStr(writer, res);
error:
Py_XDECREF(res);
Py_XDECREF(str);
Py_XDECREF(num);
return ret;
}
static int
_hamt_dump_format(_PyUnicodeWriter *writer, const char *format, ...)
{
/* A convenient helper combining _PyUnicodeWriter_WriteStr and
PyUnicode_FromFormatV.
*/
PyObject* msg;
int ret;
va_list vargs;
va_start(vargs, format);
msg = PyUnicode_FromFormatV(format, vargs);
va_end(vargs);
if (msg == NULL) {
return -1;
}
ret = _PyUnicodeWriter_WriteStr(writer, msg);
Py_DECREF(msg);
return ret;
}
#endif /* Py_DEBUG */
/////////////////////////////////// Bitmap Node
static PyHamtNode *
hamt_node_bitmap_new(Py_ssize_t size)
{
/* Create a new bitmap node of size 'size' */
PyHamtNode_Bitmap *node;
Py_ssize_t i;
if (size == 0) {
/* Since bitmap nodes are immutable, we can cache the instance
for size=0 and reuse it whenever we need an empty bitmap node.
*/
return (PyHamtNode *)&_Py_SINGLETON(hamt_bitmap_node_empty);
}
assert(size >= 0);
assert(size % 2 == 0);
/* No freelist; allocate a new bitmap node */
node = PyObject_GC_NewVar(
PyHamtNode_Bitmap, &_PyHamt_BitmapNode_Type, size);
if (node == NULL) {
return NULL;
}
Py_SET_SIZE(node, size);
for (i = 0; i < size; i++) {
node->b_array[i] = NULL;
}
node->b_bitmap = 0;
_PyObject_GC_TRACK(node);
return (PyHamtNode *)node;
}
static inline Py_ssize_t
hamt_node_bitmap_count(PyHamtNode_Bitmap *node)
{
return Py_SIZE(node) / 2;
}
static PyHamtNode_Bitmap *
hamt_node_bitmap_clone(PyHamtNode_Bitmap *node)
{
/* Clone a bitmap node; return a new one with the same child notes. */
PyHamtNode_Bitmap *clone;
Py_ssize_t i;
clone = (PyHamtNode_Bitmap *)hamt_node_bitmap_new(Py_SIZE(node));
if (clone == NULL) {
return NULL;
}
for (i = 0; i < Py_SIZE(node); i++) {
clone->b_array[i] = Py_XNewRef(node->b_array[i]);
}
clone->b_bitmap = node->b_bitmap;
return clone;
}
static PyHamtNode_Bitmap *
hamt_node_bitmap_clone_without(PyHamtNode_Bitmap *o, uint32_t bit)
{
assert(bit & o->b_bitmap);
assert(hamt_node_bitmap_count(o) > 1);
PyHamtNode_Bitmap *new = (PyHamtNode_Bitmap *)hamt_node_bitmap_new(
Py_SIZE(o) - 2);
if (new == NULL) {
return NULL;
}
uint32_t idx = hamt_bitindex(o->b_bitmap, bit);
uint32_t key_idx = 2 * idx;
uint32_t val_idx = key_idx + 1;
uint32_t i;
for (i = 0; i < key_idx; i++) {
new->b_array[i] = Py_XNewRef(o->b_array[i]);
}
assert(Py_SIZE(o) >= 0 && Py_SIZE(o) <= 32);
for (i = val_idx + 1; i < (uint32_t)Py_SIZE(o); i++) {
new->b_array[i - 2] = Py_XNewRef(o->b_array[i]);
}
new->b_bitmap = o->b_bitmap & ~bit;
return new;
}
static PyHamtNode *
hamt_node_new_bitmap_or_collision(uint32_t shift,
PyObject *key1, PyObject *val1,
int32_t key2_hash,
PyObject *key2, PyObject *val2)
{
/* Helper method. Creates a new node for key1/val and key2/val2
pairs.
If key1 hash is equal to the hash of key2, a Collision node
will be created. If they are not equal, a Bitmap node is
created.
*/
int32_t key1_hash = hamt_hash(key1);
if (key1_hash == -1) {
return NULL;
}
if (key1_hash == key2_hash) {
PyHamtNode_Collision *n;
n = (PyHamtNode_Collision *)hamt_node_collision_new(key1_hash, 4);
if (n == NULL) {
return NULL;
}
n->c_array[0] = Py_NewRef(key1);
n->c_array[1] = Py_NewRef(val1);
n->c_array[2] = Py_NewRef(key2);
n->c_array[3] = Py_NewRef(val2);
return (PyHamtNode *)n;
}
else {
int added_leaf = 0;
PyHamtNode *n = hamt_node_bitmap_new(0);
if (n == NULL) {
return NULL;
}
PyHamtNode *n2 = hamt_node_assoc(
n, shift, key1_hash, key1, val1, &added_leaf);
Py_DECREF(n);
if (n2 == NULL) {
return NULL;
}
n = hamt_node_assoc(n2, shift, key2_hash, key2, val2, &added_leaf);
Py_DECREF(n2);
if (n == NULL) {
return NULL;
}
return n;
}
}
static PyHamtNode *
hamt_node_bitmap_assoc(PyHamtNode_Bitmap *self,
uint32_t shift, int32_t hash,
PyObject *key, PyObject *val, int* added_leaf)
{
/* assoc operation for bitmap nodes.
Return: a new node, or self if key/val already is in the
collection.
'added_leaf' is later used in '_PyHamt_Assoc' to determine if
`hamt.set(key, val)` increased the size of the collection.
*/
uint32_t bit = hamt_bitpos(hash, shift);
uint32_t idx = hamt_bitindex(self->b_bitmap, bit);
/* Bitmap node layout:
+------+------+------+------+ --- +------+------+
| key1 | val1 | key2 | val2 | ... | keyN | valN |
+------+------+------+------+ --- +------+------+
where `N < Py_SIZE(node)`.
The `node->b_bitmap` field is a bitmap. For a given
`(shift, hash)` pair we can determine:
- If this node has the corresponding key/val slots.
- The index of key/val slots.
*/
if (self->b_bitmap & bit) {
/* The key is set in this node */
uint32_t key_idx = 2 * idx;
uint32_t val_idx = key_idx + 1;
assert(val_idx < (size_t)Py_SIZE(self));
PyObject *key_or_null = self->b_array[key_idx];
PyObject *val_or_node = self->b_array[val_idx];
if (key_or_null == NULL) {
/* key is NULL. This means that we have a few keys
that have the same (hash, shift) pair. */
assert(val_or_node != NULL);
PyHamtNode *sub_node = hamt_node_assoc(
(PyHamtNode *)val_or_node,
shift + 5, hash, key, val, added_leaf);
if (sub_node == NULL) {
return NULL;
}
if (val_or_node == (PyObject *)sub_node) {
Py_DECREF(sub_node);
return (PyHamtNode *)Py_NewRef(self);
}
PyHamtNode_Bitmap *ret = hamt_node_bitmap_clone(self);
if (ret == NULL) {
return NULL;
}
Py_SETREF(ret->b_array[val_idx], (PyObject*)sub_node);
return (PyHamtNode *)ret;
}
assert(key != NULL);
/* key is not NULL. This means that we have only one other
key in this collection that matches our hash for this shift. */
int comp_err = PyObject_RichCompareBool(key, key_or_null, Py_EQ);
if (comp_err < 0) { /* exception in __eq__ */
return NULL;
}
if (comp_err == 1) { /* key == key_or_null */
if (val == val_or_node) {
/* we already have the same key/val pair; return self. */
return (PyHamtNode *)Py_NewRef(self);
}
/* We're setting a new value for the key we had before.
Make a new bitmap node with a replaced value, and return it. */
PyHamtNode_Bitmap *ret = hamt_node_bitmap_clone(self);
if (ret == NULL) {
return NULL;
}
Py_SETREF(ret->b_array[val_idx], Py_NewRef(val));
return (PyHamtNode *)ret;
}
/* It's a new key, and it has the same index as *one* another key.
We have a collision. We need to create a new node which will
combine the existing key and the key we're adding.
`hamt_node_new_bitmap_or_collision` will either create a new
Collision node if the keys have identical hashes, or
a new Bitmap node.
*/
PyHamtNode *sub_node = hamt_node_new_bitmap_or_collision(
shift + 5,
key_or_null, val_or_node, /* existing key/val */
hash,
key, val /* new key/val */
);
if (sub_node == NULL) {
return NULL;
}
PyHamtNode_Bitmap *ret = hamt_node_bitmap_clone(self);
if (ret == NULL) {
Py_DECREF(sub_node);
return NULL;
}
Py_SETREF(ret->b_array[key_idx], NULL);
Py_SETREF(ret->b_array[val_idx], (PyObject *)sub_node);
*added_leaf = 1;
return (PyHamtNode *)ret;
}
else {
/* There was no key before with the same (shift,hash). */
uint32_t n = (uint32_t)_Py_popcount32(self->b_bitmap);
if (n >= 16) {
/* When we have a situation where we want to store more
than 16 nodes at one level of the tree, we no longer
want to use the Bitmap node with bitmap encoding.
Instead we start using an Array node, which has
simpler (faster) implementation at the expense of
having preallocated 32 pointers for its keys/values
pairs.
Small hamt objects (<30 keys) usually don't have any
Array nodes at all. Between ~30 and ~400 keys hamt
objects usually have one Array node, and usually it's
a root node.
*/
uint32_t jdx = hamt_mask(hash, shift);
/* 'jdx' is the index of where the new key should be added
in the new Array node we're about to create. */
PyHamtNode *empty = NULL;
PyHamtNode_Array *new_node = NULL;
PyHamtNode *res = NULL;
/* Create a new Array node. */
new_node = (PyHamtNode_Array *)hamt_node_array_new(n + 1);
if (new_node == NULL) {
goto fin;
}
/* Create an empty bitmap node for the next
hamt_node_assoc call. */
empty = hamt_node_bitmap_new(0);
if (empty == NULL) {
goto fin;
}
/* Make a new bitmap node for the key/val we're adding.
Set that bitmap node to new-array-node[jdx]. */
new_node->a_array[jdx] = hamt_node_assoc(
empty, shift + 5, hash, key, val, added_leaf);
if (new_node->a_array[jdx] == NULL) {
goto fin;
}
/* Copy existing key/value pairs from the current Bitmap
node to the new Array node we've just created. */
Py_ssize_t i, j;
for (i = 0, j = 0; i < HAMT_ARRAY_NODE_SIZE; i++) {
if (((self->b_bitmap >> i) & 1) != 0) {
/* Ensure we don't accidentally override `jdx` element
we set few lines above.
*/
assert(new_node->a_array[i] == NULL);
if (self->b_array[j] == NULL) {
new_node->a_array[i] =
(PyHamtNode *)Py_NewRef(self->b_array[j + 1]);
}
else {
int32_t rehash = hamt_hash(self->b_array[j]);
if (rehash == -1) {
goto fin;
}
new_node->a_array[i] = hamt_node_assoc(
empty, shift + 5,
rehash,
self->b_array[j],
self->b_array[j + 1],
added_leaf);
if (new_node->a_array[i] == NULL) {
goto fin;
}
}
j += 2;
}
}
VALIDATE_ARRAY_NODE(new_node)
/* That's it! */
res = (PyHamtNode *)new_node;
fin:
Py_XDECREF(empty);
if (res == NULL) {
Py_XDECREF(new_node);
}
return res;
}
else {
/* We have less than 16 keys at this level; let's just
create a new bitmap node out of this node with the
new key/val pair added. */
uint32_t key_idx = 2 * idx;
uint32_t val_idx = key_idx + 1;
uint32_t i;
*added_leaf = 1;
/* Allocate new Bitmap node which can have one more key/val
pair in addition to what we have already. */
PyHamtNode_Bitmap *new_node =
(PyHamtNode_Bitmap *)hamt_node_bitmap_new(2 * (n + 1));
if (new_node == NULL) {
return NULL;
}
/* Copy all keys/values that will be before the new key/value
we are adding. */
for (i = 0; i < key_idx; i++) {
new_node->b_array[i] = Py_XNewRef(self->b_array[i]);
}
/* Set the new key/value to the new Bitmap node. */
new_node->b_array[key_idx] = Py_NewRef(key);
new_node->b_array[val_idx] = Py_NewRef(val);
/* Copy all keys/values that will be after the new key/value
we are adding. */
assert(Py_SIZE(self) >= 0 && Py_SIZE(self) <= 32);
for (i = key_idx; i < (uint32_t)Py_SIZE(self); i++) {
new_node->b_array[i + 2] = Py_XNewRef(self->b_array[i]);
}
new_node->b_bitmap = self->b_bitmap | bit;
return (PyHamtNode *)new_node;
}
}
}
static hamt_without_t
hamt_node_bitmap_without(PyHamtNode_Bitmap *self,
uint32_t shift, int32_t hash,
PyObject *key,
PyHamtNode **new_node)
{
uint32_t bit = hamt_bitpos(hash, shift);
if ((self->b_bitmap & bit) == 0) {
return W_NOT_FOUND;
}
uint32_t idx = hamt_bitindex(self->b_bitmap, bit);
uint32_t key_idx = 2 * idx;
uint32_t val_idx = key_idx + 1;
PyObject *key_or_null = self->b_array[key_idx];
PyObject *val_or_node = self->b_array[val_idx];
if (key_or_null == NULL) {
/* key == NULL means that 'value' is another tree node. */
PyHamtNode *sub_node = NULL;
hamt_without_t res = hamt_node_without(
(PyHamtNode *)val_or_node,
shift + 5, hash, key, &sub_node);
switch (res) {
case W_EMPTY:
/* It's impossible for us to receive a W_EMPTY here:
- Array nodes are converted to Bitmap nodes when
we delete 16th item from them;
- Collision nodes are converted to Bitmap when
there is one item in them;
- Bitmap node's without() inlines single-item
sub-nodes.
So in no situation we can have a single-item
Bitmap child of another Bitmap node.
*/
Py_UNREACHABLE();
case W_NEWNODE: {
assert(sub_node != NULL);
if (IS_BITMAP_NODE(sub_node)) {
PyHamtNode_Bitmap *sub_tree = (PyHamtNode_Bitmap *)sub_node;
if (hamt_node_bitmap_count(sub_tree) == 1 &&
sub_tree->b_array[0] != NULL)
{
/* A bitmap node with one key/value pair. Just
merge it into this node.
Note that we don't inline Bitmap nodes that
have a NULL key -- those nodes point to another
tree level, and we cannot simply move tree levels
up or down.
*/
PyHamtNode_Bitmap *clone = hamt_node_bitmap_clone(self);
if (clone == NULL) {
Py_DECREF(sub_node);
return W_ERROR;
}
PyObject *key = sub_tree->b_array[0];
PyObject *val = sub_tree->b_array[1];
Py_XSETREF(clone->b_array[key_idx], Py_NewRef(key));
Py_SETREF(clone->b_array[val_idx], Py_NewRef(val));
Py_DECREF(sub_tree);
*new_node = (PyHamtNode *)clone;
return W_NEWNODE;
}
}