omextra 0.0.0.dev508__py3-none-any.whl → 0.0.0.dev510__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3621 +0,0 @@
1
- // @omlish-cext
2
- //
3
- // PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
4
- // --------------------------------------------
5
- //
6
- // 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization
7
- // ("Licensee") accessing and otherwise using this software ("Python") in source or binary form and its associated
8
- // documentation.
9
- //
10
- // 2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive,
11
- // royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative
12
- // works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License
13
- // Agreement and PSF's notice of copyright, i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
14
- // 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 Python Software Foundation; All Rights Reserved" are retained in
15
- // Python alone or in any derivative version prepared by Licensee.
16
- //
17
- // 3. In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and
18
- // wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in
19
- // any such work a brief summary of the changes made to Python.
20
- //
21
- // 4. PSF is making Python available to Licensee on an "AS IS" basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES,
22
- // EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY
23
- // OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY
24
- // RIGHTS.
25
- //
26
- // 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL
27
- // DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE THEREOF, EVEN IF
28
- // ADVISED OF THE POSSIBILITY THEREOF.
29
- //
30
- // 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions.
31
- //
32
- // 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint
33
- // venture between PSF and Licensee. This License Agreement does not grant permission to use PSF trademarks or trade
34
- // name in a trademark sense to endorse or promote products or services of Licensee, or any third party.
35
- //
36
- // 8. By copying, installing or otherwise using Python, Licensee agrees to be bound by the terms and conditions of this
37
- // License Agreement.
38
- //
39
- // https://github.com/python/cpython/commit/aa18fd55d575a04e3aa782fedcd08dced26676e0
40
- //
41
- #define PY_SSIZE_T_CLEAN
42
-
43
- #include "Python.h"
44
-
45
- #include <stddef.h> // offsetof()
46
-
47
- #if PY_VERSION_HEX < 0x030D0000
48
- # error "This extension requires CPython 3.13+"
49
- #endif
50
-
51
- ////
52
-
53
- /*
54
- HAMT tree is shaped by hashes of keys. Every group of 5 bits of a hash denotes
55
- the exact position of the key in one level of the tree. Since we're using
56
- 32 bit hashes, we can have at most 7 such levels. Although if there are
57
- two distinct keys with equal hashes, they will have to occupy the same
58
- cell in the 7th level of the tree -- so we'd put them in a "collision" node.
59
- Which brings the total possible tree depth to 8. Read more about the actual
60
- layout of the HAMT tree in `hamt.c`.
61
-
62
- This constant is used to define a datastucture for storing iteration state.
63
- */
64
- #define _Py_HAMT_MAX_TREE_DEPTH 8
65
-
66
-
67
- /* Abstract tree node. */
68
- typedef struct {
69
- PyObject_HEAD
70
- } HamtNode;
71
-
72
-
73
- /* An HAMT immutable mapping collection. */
74
- typedef struct {
75
- PyObject_HEAD
76
- HamtNode *h_root;
77
- PyObject *h_weakreflist;
78
- Py_ssize_t h_count;
79
- } HamtObject;
80
-
81
-
82
- typedef struct {
83
- PyObject_VAR_HEAD
84
- uint32_t b_bitmap;
85
- PyObject *b_array[1];
86
- } HamtNode_Bitmap;
87
-
88
-
89
- /* A struct to hold the state of depth-first traverse of the tree.
90
-
91
- HAMT is an immutable collection. Iterators will hold a strong reference
92
- to it, and every node in the HAMT has strong references to its children.
93
-
94
- So for iterators, we can implement zero allocations and zero reference
95
- inc/dec depth-first iteration.
96
-
97
- - i_nodes: an array of seven pointers to tree nodes
98
- - i_level: the current node in i_nodes
99
- - i_pos: an array of positions within nodes in i_nodes.
100
- */
101
- typedef struct {
102
- HamtNode *i_nodes[_Py_HAMT_MAX_TREE_DEPTH];
103
- Py_ssize_t i_pos[_Py_HAMT_MAX_TREE_DEPTH];
104
- int8_t i_level;
105
- } HamtIteratorState;
106
-
107
-
108
- /* Base iterator object.
109
-
110
- Contains the iteration state, a pointer to the HAMT tree,
111
- and a pointer to the 'yield function'. The latter is a simple
112
- function that returns a key/value tuple for the 'Items' iterator,
113
- just a key for the 'Keys' iterator, and a value for the 'Values'
114
- iterator.
115
- */
116
- typedef struct {
117
- PyObject_HEAD
118
- HamtObject *hi_obj;
119
- HamtIteratorState hi_iter;
120
- binaryfunc hi_yield;
121
- } HamtIterator;
122
-
123
-
124
- ////
125
-
126
- #define _MODULE_NAME "_hamt"
127
- #define _PACKAGE_NAME "omextra.collections.hamt"
128
- #define _MODULE_FULL_NAME _PACKAGE_NAME "." _MODULE_NAME
129
-
130
- //
131
-
132
- typedef struct hamt_module_state {
133
- /* Type objects */
134
- PyTypeObject *Hamt_Type;
135
- PyTypeObject *HamtItems_Type;
136
- PyTypeObject *HamtKeys_Type;
137
- PyTypeObject *HamtValues_Type;
138
- PyTypeObject *Hamt_ArrayNode_Type;
139
- PyTypeObject *Hamt_BitmapNode_Type;
140
- PyTypeObject *Hamt_CollisionNode_Type;
141
-
142
- /* Singleton objects */
143
- HamtObject *empty_hamt;
144
- HamtNode_Bitmap *empty_bitmap_node;
145
- } hamt_module_state;
146
-
147
- static inline hamt_module_state * get_hamt_module_state(PyObject *module)
148
- {
149
- void *state = PyModule_GetState(module);
150
- assert(state != NULL);
151
- return (hamt_module_state *)state;
152
- }
153
-
154
- static inline hamt_module_state * get_hamt_state_from_type(PyTypeObject *type)
155
- {
156
- PyObject *module = PyType_GetModule(type);
157
- assert(module != NULL);
158
- return get_hamt_module_state(module);
159
- }
160
-
161
- static inline hamt_module_state * get_hamt_state_from_obj(PyObject *obj)
162
- {
163
- PyTypeObject *type = Py_TYPE(obj);
164
- return get_hamt_state_from_type(type);
165
- }
166
-
167
- ////
168
-
169
- // Population count: count the number of 1's in 'x'
170
- // (number of bits set to 1), also known as the hamming weight.
171
- //
172
- // Implementation note. CPUID is not used, to test if x86 POPCNT instruction
173
- // can be used, to keep the implementation simple. For example, Visual Studio
174
- // __popcnt() is not used this reason. The clang and GCC builtin function can
175
- // use the x86 POPCNT instruction if the target architecture has SSE4a or
176
- // newer.
177
- static inline int
178
- _popcount32(uint32_t x)
179
- {
180
- #if (defined(__clang__) || defined(__GNUC__))
181
-
182
- #if SIZEOF_INT >= 4
183
- Py_BUILD_ASSERT(sizeof(x) <= sizeof(unsigned int));
184
- return __builtin_popcount(x);
185
- #else
186
- // The C standard guarantees that unsigned long will always be big enough
187
- // to hold a uint32_t value without losing information.
188
- Py_BUILD_ASSERT(sizeof(x) <= sizeof(unsigned long));
189
- return __builtin_popcountl(x);
190
- #endif
191
-
192
- #else
193
- // 32-bit SWAR (SIMD Within A Register) popcount
194
-
195
- // Binary: 0 1 0 1 ...
196
- const uint32_t M1 = 0x55555555;
197
- // Binary: 00 11 00 11. ..
198
- const uint32_t M2 = 0x33333333;
199
- // Binary: 0000 1111 0000 1111 ...
200
- const uint32_t M4 = 0x0F0F0F0F;
201
-
202
- // Put count of each 2 bits into those 2 bits
203
- x = x - ((x >> 1) & M1);
204
- // Put count of each 4 bits into those 4 bits
205
- x = (x & M2) + ((x >> 2) & M2);
206
- // Put count of each 8 bits into those 8 bits
207
- x = (x + (x >> 4)) & M4;
208
- // Sum of the 4 byte counts.
209
- // Take care when considering changes to the next line. Portability and
210
- // correctness are delicate here, thanks to C's "integer promotions" (C99
211
- // §6.3.1.1p2). On machines where the `int` type has width greater than 32
212
- // bits, `x` will be promoted to an `int`, and following C's "usual
213
- // arithmetic conversions" (C99 §6.3.1.8), the multiplication will be
214
- // performed as a multiplication of two `unsigned int` operands. In this
215
- // case it's critical that we cast back to `uint32_t` in order to keep only
216
- // the least significant 32 bits. On machines where the `int` type has
217
- // width no greater than 32, the multiplication is of two 32-bit unsigned
218
- // integer types, and the (uint32_t) cast is a no-op. In both cases, we
219
- // avoid the risk of undefined behaviour due to overflow of a
220
- // multiplication of signed integer types.
221
- return (uint32_t)(x * 0x01010101U) >> 24;
222
- #endif
223
- }
224
-
225
- ////
226
-
227
- /* Create a new HAMT immutable mapping. */
228
- HamtObject * _Hamt_New(hamt_module_state *state);
229
-
230
- /* Return a new collection based on "o", but with an additional
231
- key/val pair. */
232
- HamtObject * _Hamt_Assoc(HamtObject *o, PyObject *key, PyObject *val);
233
-
234
- /* Return a new collection based on "o", but without "key". */
235
- HamtObject * _Hamt_Without(HamtObject *o, PyObject *key);
236
-
237
- /* Find "key" in the "o" collection.
238
-
239
- Return:
240
- - -1: An error occurred.
241
- - 0: "key" wasn't found in "o".
242
- - 1: "key" is in "o"; "*val" is set to its value (a borrowed ref).
243
- */
244
- int _Hamt_Find(HamtObject *o, PyObject *key, PyObject **val);
245
-
246
- /* Check if "v" is equal to "w".
247
-
248
- Return:
249
- - 0: v != w
250
- - 1: v == w
251
- - -1: An error occurred.
252
- */
253
- int _Hamt_Eq(HamtObject *v, HamtObject *w);
254
-
255
- /* Return the size of "o"; equivalent of "len(o)". */
256
- Py_ssize_t _Hamt_Len(HamtObject *o);
257
-
258
- /* Return a Keys iterator over "o". */
259
- PyObject * _Hamt_NewIterKeys(HamtObject *o);
260
-
261
- /* Return a Values iterator over "o". */
262
- PyObject * _Hamt_NewIterValues(HamtObject *o);
263
-
264
- /* Return a Items iterator over "o". */
265
- PyObject * _Hamt_NewIterItems(HamtObject *o);
266
-
267
- ////
268
-
269
- /* Type check helper - checks if object is a HAMT by comparing against module state type */
270
- static inline int
271
- Hamt_Check(PyObject *o)
272
- {
273
- PyTypeObject *type = Py_TYPE(o);
274
- PyObject *mod = PyType_GetModule(type);
275
- if (mod == NULL) {
276
- // Not a heap type or not from a module, definitely not our HAMT
277
- PyErr_Clear();
278
- return 0;
279
- }
280
- hamt_module_state *state = get_hamt_module_state(mod);
281
- return Py_IS_TYPE(o, state->Hamt_Type);
282
- }
283
-
284
-
285
- /*
286
- This file provides an implementation of an immutable mapping using the
287
- Hash Array Mapped Trie (or HAMT) datastructure.
288
-
289
- This design allows to have:
290
-
291
- 1. Efficient copy: immutable mappings can be copied by reference,
292
- making it an O(1) operation.
293
-
294
- 2. Efficient mutations: due to structural sharing, only a portion of
295
- the trie needs to be copied when the collection is mutated. The
296
- cost of set/delete operations is O(log N).
297
-
298
- 3. Efficient lookups: O(log N).
299
-
300
- (where N is number of key/value items in the immutable mapping.)
301
-
302
-
303
- HAMT
304
- ====
305
-
306
- The core idea of HAMT is that the shape of the trie is encoded into the
307
- hashes of keys.
308
-
309
- Say we want to store a K/V pair in our mapping. First, we calculate the
310
- hash of K, let's say it's 19830128, or in binary:
311
-
312
- 0b1001011101001010101110000 = 19830128
313
-
314
- Now let's partition this bit representation of the hash into blocks of
315
- 5 bits each:
316
-
317
- 0b00_00000_10010_11101_00101_01011_10000 = 19830128
318
- (6) (5) (4) (3) (2) (1)
319
-
320
- Each block of 5 bits represents a number between 0 and 31. So if we have
321
- a tree that consists of nodes, each of which is an array of 32 pointers,
322
- those 5-bit blocks will encode a position on a single tree level.
323
-
324
- For example, storing the key K with hash 19830128, results in the following
325
- tree structure:
326
-
327
- (array of 32 pointers)
328
- +---+ -- +----+----+----+ -- +----+
329
- root node | 0 | .. | 15 | 16 | 17 | .. | 31 | 0b10000 = 16 (1)
330
- (level 1) +---+ -- +----+----+----+ -- +----+
331
- |
332
- +---+ -- +----+----+----+ -- +----+
333
- a 2nd level node | 0 | .. | 10 | 11 | 12 | .. | 31 | 0b01011 = 11 (2)
334
- +---+ -- +----+----+----+ -- +----+
335
- |
336
- +---+ -- +----+----+----+ -- +----+
337
- a 3rd level node | 0 | .. | 04 | 05 | 06 | .. | 31 | 0b00101 = 5 (3)
338
- +---+ -- +----+----+----+ -- +----+
339
- |
340
- +---+ -- +----+----+----+----+
341
- a 4th level node | 0 | .. | 04 | 29 | 30 | 31 | 0b11101 = 29 (4)
342
- +---+ -- +----+----+----+----+
343
- |
344
- +---+ -- +----+----+----+ -- +----+
345
- a 5th level node | 0 | .. | 17 | 18 | 19 | .. | 31 | 0b10010 = 18 (5)
346
- +---+ -- +----+----+----+ -- +----+
347
- |
348
- +--------------+
349
- |
350
- +---+ -- +----+----+----+ -- +----+
351
- a 6th level node | 0 | .. | 15 | 16 | 17 | .. | 31 | 0b00000 = 0 (6)
352
- +---+ -- +----+----+----+ -- +----+
353
- |
354
- V -- our value (or collision)
355
-
356
- To rehash: for a K/V pair, the hash of K encodes where in the tree V will
357
- be stored.
358
-
359
- To optimize memory footprint and handle hash collisions, our implementation
360
- uses three different types of nodes:
361
-
362
- * A Bitmap node;
363
- * An Array node;
364
- * A Collision node.
365
-
366
- Because we implement an immutable dictionary, our nodes are also
367
- immutable. Therefore, when we need to modify a node, we copy it, and
368
- do that modification to the copy.
369
-
370
-
371
- Array Nodes
372
- -----------
373
-
374
- These nodes are very simple. Essentially they are arrays of 32 pointers
375
- we used to illustrate the high-level idea in the previous section.
376
-
377
- We use Array nodes only when we need to store more than 16 pointers
378
- in a single node.
379
-
380
- Array nodes do not store key objects or value objects. They are used
381
- only as an indirection level - their pointers point to other nodes in
382
- the tree.
383
-
384
-
385
- Bitmap Node
386
- -----------
387
-
388
- Allocating a new 32-pointers array for every node of our tree would be
389
- very expensive. Unless we store millions of keys, most of tree nodes would
390
- be very sparse.
391
-
392
- When we have less than 16 elements in a node, we don't want to use the
393
- Array node, that would mean that we waste a lot of memory. Instead,
394
- we can use bitmap compression and can have just as many pointers
395
- as we need!
396
-
397
- Bitmap nodes consist of two fields:
398
-
399
- 1. An array of pointers. If a Bitmap node holds N elements, the
400
- array will be of N pointers.
401
-
402
- 2. A 32bit integer -- a bitmap field. If an N-th bit is set in the
403
- bitmap, it means that the node has an N-th element.
404
-
405
- For example, say we need to store a 3 elements sparse array:
406
-
407
- +---+ -- +---+ -- +----+ -- +----+
408
- | 0 | .. | 4 | .. | 11 | .. | 17 |
409
- +---+ -- +---+ -- +----+ -- +----+
410
- | | |
411
- o1 o2 o3
412
-
413
- We allocate a three-pointer Bitmap node. Its bitmap field will be
414
- then set to:
415
-
416
- 0b_00100_00010_00000_10000 == (1 << 17) | (1 << 11) | (1 << 4)
417
-
418
- To check if our Bitmap node has an I-th element we can do:
419
-
420
- bitmap & (1 << I)
421
-
422
-
423
- And here's a formula to calculate a position in our pointer array
424
- which would correspond to an I-th element:
425
-
426
- popcount(bitmap & ((1 << I) - 1))
427
-
428
-
429
- Let's break it down:
430
-
431
- * `popcount` is a function that returns a number of bits set to 1;
432
-
433
- * `((1 << I) - 1)` is a mask to filter the bitmask to contain bits
434
- set to the *right* of our bit.
435
-
436
-
437
- So for our 17, 11, and 4 indexes:
438
-
439
- * bitmap & ((1 << 17) - 1) == 0b100000010000 => 2 bits are set => index is 2.
440
-
441
- * bitmap & ((1 << 11) - 1) == 0b10000 => 1 bit is set => index is 1.
442
-
443
- * bitmap & ((1 << 4) - 1) == 0b0 => 0 bits are set => index is 0.
444
-
445
-
446
- To conclude: Bitmap nodes are just like Array nodes -- they can store
447
- a number of pointers, but use bitmap compression to eliminate unused
448
- pointers.
449
-
450
-
451
- Bitmap nodes have two pointers for each item:
452
-
453
- +----+----+----+----+ -- +----+----+
454
- | k1 | v1 | k2 | v2 | .. | kN | vN |
455
- +----+----+----+----+ -- +----+----+
456
-
457
- When kI == NULL, vI points to another tree level.
458
-
459
- When kI != NULL, the actual key object is stored in kI, and its
460
- value is stored in vI.
461
-
462
-
463
- Collision Nodes
464
- ---------------
465
-
466
- Collision nodes are simple arrays of pointers -- two pointers per
467
- key/value. When there's a hash collision, say for k1/v1 and k2/v2
468
- we have `hash(k1)==hash(k2)`. Then our collision node will be:
469
-
470
- +----+----+----+----+
471
- | k1 | v1 | k2 | v2 |
472
- +----+----+----+----+
473
-
474
-
475
- Tree Structure
476
- --------------
477
-
478
- All nodes are PyObjects.
479
-
480
- The `HamtObject` object has a pointer to the root node (h_root),
481
- and has a length field (h_count).
482
-
483
- High-level functions accept a HamtObject object and dispatch to
484
- lower-level functions depending on what kind of node h_root points to.
485
-
486
-
487
- Operations
488
- ==========
489
-
490
- There are three fundamental operations on an immutable dictionary:
491
-
492
- 1. "o.assoc(k, v)" will return a new immutable dictionary, that will be
493
- a copy of "o", but with the "k/v" item set.
494
-
495
- Functions in this file:
496
-
497
- hamt_node_assoc, hamt_node_bitmap_assoc,
498
- hamt_node_array_assoc, hamt_node_collision_assoc
499
-
500
- `hamt_node_assoc` function accepts a node object, and calls
501
- other functions depending on its actual type.
502
-
503
- 2. "o.find(k)" will lookup key "k" in "o".
504
-
505
- Functions:
506
-
507
- hamt_node_find, hamt_node_bitmap_find,
508
- hamt_node_array_find, hamt_node_collision_find
509
-
510
- 3. "o.without(k)" will return a new immutable dictionary, that will be
511
- a copy of "o", buth without the "k" key.
512
-
513
- Functions:
514
-
515
- hamt_node_without, hamt_node_bitmap_without,
516
- hamt_node_array_without, hamt_node_collision_without
517
-
518
-
519
- Further Reading
520
- ===============
521
-
522
- 1. http://blog.higher-order.net/2009/09/08/understanding-clojures-persistenthashmap-deftwice.html
523
-
524
- 2. http://blog.higher-order.net/2010/08/16/assoc-and-clojures-persistenthashmap-part-ii.html
525
-
526
- 3. Clojure's PersistentHashMap implementation:
527
- https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/PersistentHashMap.java
528
-
529
-
530
- Debug
531
- =====
532
-
533
- The HAMT datatype is accessible for testing purposes under the
534
- `_testinternalcapi` module:
535
-
536
- >>> from _testinternalcapi import hamt
537
- >>> h = hamt()
538
- >>> h2 = h.set('a', 2)
539
- >>> h3 = h2.set('b', 3)
540
- >>> list(h3)
541
- ['a', 'b']
542
-
543
- When CPython is built in debug mode, a '__dump__()' method is available
544
- to introspect the tree:
545
-
546
- >>> print(h3.__dump__())
547
- HAMT(len=2):
548
- BitmapNode(size=4 count=2 bitmap=0b110 id=0x10eb9d9e8):
549
- 'a': 2
550
- 'b': 3
551
- */
552
-
553
-
554
- static inline int
555
- IS_ARRAY_NODE(HamtNode *node)
556
- {
557
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)node);
558
- return Py_IS_TYPE(node, state->Hamt_ArrayNode_Type);
559
- }
560
-
561
- static inline int
562
- IS_BITMAP_NODE(HamtNode *node)
563
- {
564
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)node);
565
- return Py_IS_TYPE(node, state->Hamt_BitmapNode_Type);
566
- }
567
-
568
- static inline int
569
- IS_COLLISION_NODE(HamtNode *node)
570
- {
571
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)node);
572
- return Py_IS_TYPE(node, state->Hamt_CollisionNode_Type);
573
- }
574
-
575
-
576
- /* Return type for 'find' (lookup a key) functions.
577
-
578
- * F_ERROR - an error occurred;
579
- * F_NOT_FOUND - the key was not found;
580
- * F_FOUND - the key was found.
581
- */
582
- typedef enum {F_ERROR, F_NOT_FOUND, F_FOUND} hamt_find_t;
583
-
584
-
585
- /* Return type for 'without' (delete a key) functions.
586
-
587
- * W_ERROR - an error occurred;
588
- * W_NOT_FOUND - the key was not found: there's nothing to delete;
589
- * W_EMPTY - the key was found: the node/tree would be empty
590
- if the key is deleted;
591
- * W_NEWNODE - the key was found: a new node/tree is returned
592
- without that key.
593
- */
594
- typedef enum {W_ERROR, W_NOT_FOUND, W_EMPTY, W_NEWNODE} hamt_without_t;
595
-
596
-
597
- /* Low-level iterator protocol type.
598
-
599
- * I_ITEM - a new item has been yielded;
600
- * I_END - the whole tree was visited (similar to StopIteration).
601
- */
602
- typedef enum {I_ITEM, I_END} hamt_iter_t;
603
-
604
-
605
- #define HAMT_ARRAY_NODE_SIZE 32
606
-
607
-
608
- typedef struct {
609
- PyObject_HEAD
610
- HamtNode *a_array[HAMT_ARRAY_NODE_SIZE];
611
- Py_ssize_t a_count;
612
- } HamtNode_Array;
613
-
614
-
615
- typedef struct {
616
- PyObject_VAR_HEAD
617
- int32_t c_hash;
618
- PyObject *c_array[1];
619
- } HamtNode_Collision;
620
-
621
-
622
- static HamtObject *
623
- hamt_alloc(hamt_module_state *state);
624
-
625
- static HamtNode *
626
- hamt_node_assoc(HamtNode *node,
627
- uint32_t shift, int32_t hash,
628
- PyObject *key, PyObject *val, int* added_leaf);
629
-
630
- static hamt_without_t
631
- hamt_node_without(HamtNode *node,
632
- uint32_t shift, int32_t hash,
633
- PyObject *key,
634
- HamtNode **new_node);
635
-
636
- static hamt_find_t
637
- hamt_node_find(HamtNode *node,
638
- uint32_t shift, int32_t hash,
639
- PyObject *key, PyObject **val);
640
-
641
- #ifdef Py_DEBUG
642
- static int
643
- hamt_node_dump(HamtNode *node,
644
- _PyUnicodeWriter *writer, int level);
645
- #endif
646
-
647
- static HamtNode *
648
- hamt_node_array_new(hamt_module_state *state, Py_ssize_t);
649
-
650
- static HamtNode *
651
- hamt_node_collision_new(hamt_module_state *state, int32_t hash, Py_ssize_t size);
652
-
653
- static inline Py_ssize_t
654
- hamt_node_collision_count(HamtNode_Collision *node);
655
-
656
-
657
- #ifdef Py_DEBUG
658
- static void
659
- _hamt_node_array_validate(void *obj_raw)
660
- {
661
- PyObject *obj = _PyObject_CAST(obj_raw);
662
- assert(IS_ARRAY_NODE(obj));
663
- HamtNode_Array *node = (HamtNode_Array*)obj;
664
- Py_ssize_t i = 0, count = 0;
665
- for (; i < HAMT_ARRAY_NODE_SIZE; i++) {
666
- if (node->a_array[i] != NULL) {
667
- count++;
668
- }
669
- }
670
- assert(count == node->a_count);
671
- }
672
-
673
- #define VALIDATE_ARRAY_NODE(NODE) \
674
- do { _hamt_node_array_validate(NODE); } while (0);
675
- #else
676
- #define VALIDATE_ARRAY_NODE(NODE)
677
- #endif
678
-
679
-
680
- /* Returns -1 on error */
681
- static inline int32_t
682
- hamt_hash(PyObject *o)
683
- {
684
- Py_hash_t hash = PyObject_Hash(o);
685
-
686
- #if SIZEOF_PY_HASH_T <= 4
687
- return hash;
688
- #else
689
- if (hash == -1) {
690
- /* exception */
691
- return -1;
692
- }
693
-
694
- /* While it's somewhat suboptimal to reduce Python's 64 bit hash to
695
- 32 bits via XOR, it seems that the resulting hash function
696
- is good enough (this is also how Long type is hashed in Java.)
697
- Storing 10, 100, 1000 Python strings results in a relatively
698
- shallow and uniform tree structure.
699
-
700
- Also it's worth noting that it would be possible to adapt the tree
701
- structure to 64 bit hashes, but that would increase memory pressure
702
- and provide little to no performance benefits for collections with
703
- fewer than billions of key/value pairs.
704
-
705
- Important: do not change this hash reducing function. There are many
706
- tests that need an exact tree shape to cover all code paths and
707
- we do that by specifying concrete values for test data's `__hash__`.
708
- If this function is changed most of the regression tests would
709
- become useless.
710
- */
711
- int32_t xored = (int32_t)(hash & 0xffffffffl) ^ (int32_t)(hash >> 32);
712
- return xored == -1 ? -2 : xored;
713
- #endif
714
- }
715
-
716
- static inline uint32_t
717
- hamt_mask(int32_t hash, uint32_t shift)
718
- {
719
- return (((uint32_t)hash >> shift) & 0x01f);
720
- }
721
-
722
- static inline uint32_t
723
- hamt_bitpos(int32_t hash, uint32_t shift)
724
- {
725
- return (uint32_t)1 << hamt_mask(hash, shift);
726
- }
727
-
728
- static inline uint32_t
729
- hamt_bitindex(uint32_t bitmap, uint32_t bit)
730
- {
731
- return (uint32_t)_popcount32(bitmap & (bit - 1));
732
- }
733
-
734
-
735
- /////////////////////////////////// Dump Helpers
736
- #ifdef Py_DEBUG
737
-
738
- static int
739
- _hamt_dump_ident(_PyUnicodeWriter *writer, int level)
740
- {
741
- /* Write `' ' * level` to the `writer` */
742
- PyObject *str = NULL;
743
- PyObject *num = NULL;
744
- PyObject *res = NULL;
745
- int ret = -1;
746
-
747
- str = PyUnicode_FromString(" ");
748
- if (str == NULL) {
749
- goto error;
750
- }
751
-
752
- num = PyLong_FromLong((long)level);
753
- if (num == NULL) {
754
- goto error;
755
- }
756
-
757
- res = PyNumber_Multiply(str, num);
758
- if (res == NULL) {
759
- goto error;
760
- }
761
-
762
- ret = _PyUnicodeWriter_WriteStr(writer, res);
763
-
764
- error:
765
- Py_XDECREF(res);
766
- Py_XDECREF(str);
767
- Py_XDECREF(num);
768
- return ret;
769
- }
770
-
771
- static int
772
- _hamt_dump_format(_PyUnicodeWriter *writer, const char *format, ...)
773
- {
774
- /* A convenient helper combining _PyUnicodeWriter_WriteStr and
775
- PyUnicode_FromFormatV.
776
- */
777
- PyObject* msg;
778
- int ret;
779
-
780
- va_list vargs;
781
- va_start(vargs, format);
782
- msg = PyUnicode_FromFormatV(format, vargs);
783
- va_end(vargs);
784
-
785
- if (msg == NULL) {
786
- return -1;
787
- }
788
-
789
- ret = _PyUnicodeWriter_WriteStr(writer, msg);
790
- Py_DECREF(msg);
791
- return ret;
792
- }
793
-
794
- #endif /* Py_DEBUG */
795
- /////////////////////////////////// Bitmap Node
796
-
797
-
798
- static HamtNode *
799
- hamt_node_bitmap_new(hamt_module_state *state, Py_ssize_t size)
800
- {
801
- /* Create a new bitmap node of size 'size' */
802
-
803
- HamtNode_Bitmap *node;
804
- Py_ssize_t i;
805
-
806
- if (size == 0) {
807
- /* Since bitmap nodes are immutable, we can cache the instance
808
- for size=0 and reuse it whenever we need an empty bitmap node.
809
- */
810
- return (HamtNode *)Py_NewRef(state->empty_bitmap_node);
811
- }
812
-
813
- assert(size >= 0);
814
- assert(size % 2 == 0);
815
-
816
- /* No freelist; allocate a new bitmap node */
817
- node = PyObject_GC_NewVar(
818
- HamtNode_Bitmap, state->Hamt_BitmapNode_Type, size);
819
- if (node == NULL) {
820
- return NULL;
821
- }
822
-
823
- Py_SET_SIZE(node, size);
824
-
825
- for (i = 0; i < size; i++) {
826
- node->b_array[i] = NULL;
827
- }
828
-
829
- node->b_bitmap = 0;
830
-
831
- PyObject_GC_Track(node);
832
-
833
- return (HamtNode *)node;
834
- }
835
-
836
- static inline Py_ssize_t
837
- hamt_node_bitmap_count(HamtNode_Bitmap *node)
838
- {
839
- return Py_SIZE(node) / 2;
840
- }
841
-
842
- static HamtNode_Bitmap *
843
- hamt_node_bitmap_clone(HamtNode_Bitmap *node)
844
- {
845
- /* Clone a bitmap node; return a new one with the same child notes. */
846
-
847
- HamtNode_Bitmap *clone;
848
- Py_ssize_t i;
849
-
850
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)node);
851
- clone = (HamtNode_Bitmap *)hamt_node_bitmap_new(state, Py_SIZE(node));
852
- if (clone == NULL) {
853
- return NULL;
854
- }
855
-
856
- for (i = 0; i < Py_SIZE(node); i++) {
857
- clone->b_array[i] = Py_XNewRef(node->b_array[i]);
858
- }
859
-
860
- clone->b_bitmap = node->b_bitmap;
861
- return clone;
862
- }
863
-
864
- static HamtNode_Bitmap *
865
- hamt_node_bitmap_clone_without(HamtNode_Bitmap *o, uint32_t bit)
866
- {
867
- assert(bit & o->b_bitmap);
868
- assert(hamt_node_bitmap_count(o) > 1);
869
-
870
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)o);
871
- HamtNode_Bitmap *new = (HamtNode_Bitmap *)hamt_node_bitmap_new(
872
- state, Py_SIZE(o) - 2);
873
- if (new == NULL) {
874
- return NULL;
875
- }
876
-
877
- uint32_t idx = hamt_bitindex(o->b_bitmap, bit);
878
- uint32_t key_idx = 2 * idx;
879
- uint32_t val_idx = key_idx + 1;
880
- uint32_t i;
881
-
882
- for (i = 0; i < key_idx; i++) {
883
- new->b_array[i] = Py_XNewRef(o->b_array[i]);
884
- }
885
-
886
- assert(Py_SIZE(o) >= 0 && Py_SIZE(o) <= 32);
887
- for (i = val_idx + 1; i < (uint32_t)Py_SIZE(o); i++) {
888
- new->b_array[i - 2] = Py_XNewRef(o->b_array[i]);
889
- }
890
-
891
- new->b_bitmap = o->b_bitmap & ~bit;
892
- return new;
893
- }
894
-
895
- static HamtNode *
896
- hamt_node_new_bitmap_or_collision(
897
- hamt_module_state *state,
898
- uint32_t shift,
899
- PyObject *key1, PyObject *val1,
900
- int32_t key2_hash,
901
- PyObject *key2, PyObject *val2)
902
- {
903
- /* Helper method. Creates a new node for key1/val and key2/val2
904
- pairs.
905
-
906
- If key1 hash is equal to the hash of key2, a Collision node
907
- will be created. If they are not equal, a Bitmap node is
908
- created.
909
- */
910
-
911
- int32_t key1_hash = hamt_hash(key1);
912
- if (key1_hash == -1) {
913
- return NULL;
914
- }
915
-
916
- if (key1_hash == key2_hash) {
917
- HamtNode_Collision *n;
918
- n = (HamtNode_Collision *)hamt_node_collision_new(state, key1_hash, 4);
919
- if (n == NULL) {
920
- return NULL;
921
- }
922
-
923
- n->c_array[0] = Py_NewRef(key1);
924
- n->c_array[1] = Py_NewRef(val1);
925
-
926
- n->c_array[2] = Py_NewRef(key2);
927
- n->c_array[3] = Py_NewRef(val2);
928
-
929
- return (HamtNode *)n;
930
- }
931
- else {
932
- int added_leaf = 0;
933
- HamtNode *n = hamt_node_bitmap_new(state, 0);
934
- if (n == NULL) {
935
- return NULL;
936
- }
937
-
938
- HamtNode *n2 = hamt_node_assoc(
939
- n, shift, key1_hash, key1, val1, &added_leaf);
940
- Py_DECREF(n);
941
- if (n2 == NULL) {
942
- return NULL;
943
- }
944
-
945
- n = hamt_node_assoc(n2, shift, key2_hash, key2, val2, &added_leaf);
946
- Py_DECREF(n2);
947
- if (n == NULL) {
948
- return NULL;
949
- }
950
-
951
- return n;
952
- }
953
- }
954
-
955
- static HamtNode *
956
- hamt_node_bitmap_assoc(HamtNode_Bitmap *self,
957
- uint32_t shift, int32_t hash,
958
- PyObject *key, PyObject *val, int* added_leaf)
959
- {
960
- /* assoc operation for bitmap nodes.
961
-
962
- Return: a new node, or self if key/val already is in the
963
- collection.
964
-
965
- 'added_leaf' is later used in '_Hamt_Assoc' to determine if
966
- `hamt.set(key, val)` increased the size of the collection.
967
- */
968
-
969
- uint32_t bit = hamt_bitpos(hash, shift);
970
- uint32_t idx = hamt_bitindex(self->b_bitmap, bit);
971
-
972
- /* Bitmap node layout:
973
-
974
- +------+------+------+------+ --- +------+------+
975
- | key1 | val1 | key2 | val2 | ... | keyN | valN |
976
- +------+------+------+------+ --- +------+------+
977
- where `N < Py_SIZE(node)`.
978
-
979
- The `node->b_bitmap` field is a bitmap. For a given
980
- `(shift, hash)` pair we can determine:
981
-
982
- - If this node has the corresponding key/val slots.
983
- - The index of key/val slots.
984
- */
985
-
986
- if (self->b_bitmap & bit) {
987
- /* The key is set in this node */
988
-
989
- uint32_t key_idx = 2 * idx;
990
- uint32_t val_idx = key_idx + 1;
991
-
992
- assert(val_idx < (size_t)Py_SIZE(self));
993
-
994
- PyObject *key_or_null = self->b_array[key_idx];
995
- PyObject *val_or_node = self->b_array[val_idx];
996
-
997
- if (key_or_null == NULL) {
998
- /* key is NULL. This means that we have a few keys
999
- that have the same (hash, shift) pair. */
1000
-
1001
- assert(val_or_node != NULL);
1002
-
1003
- HamtNode *sub_node = hamt_node_assoc(
1004
- (HamtNode *)val_or_node,
1005
- shift + 5, hash, key, val, added_leaf);
1006
- if (sub_node == NULL) {
1007
- return NULL;
1008
- }
1009
-
1010
- if (val_or_node == (PyObject *)sub_node) {
1011
- Py_DECREF(sub_node);
1012
- return (HamtNode *)Py_NewRef(self);
1013
- }
1014
-
1015
- HamtNode_Bitmap *ret = hamt_node_bitmap_clone(self);
1016
- if (ret == NULL) {
1017
- return NULL;
1018
- }
1019
- Py_SETREF(ret->b_array[val_idx], (PyObject*)sub_node);
1020
- return (HamtNode *)ret;
1021
- }
1022
-
1023
- assert(key != NULL);
1024
- /* key is not NULL. This means that we have only one other
1025
- key in this collection that matches our hash for this shift. */
1026
-
1027
- int comp_err = PyObject_RichCompareBool(key, key_or_null, Py_EQ);
1028
- if (comp_err < 0) { /* exception in __eq__ */
1029
- return NULL;
1030
- }
1031
- if (comp_err == 1) { /* key == key_or_null */
1032
- if (val == val_or_node) {
1033
- /* we already have the same key/val pair; return self. */
1034
- return (HamtNode *)Py_NewRef(self);
1035
- }
1036
-
1037
- /* We're setting a new value for the key we had before.
1038
- Make a new bitmap node with a replaced value, and return it. */
1039
- HamtNode_Bitmap *ret = hamt_node_bitmap_clone(self);
1040
- if (ret == NULL) {
1041
- return NULL;
1042
- }
1043
- Py_SETREF(ret->b_array[val_idx], Py_NewRef(val));
1044
- return (HamtNode *)ret;
1045
- }
1046
-
1047
- /* It's a new key, and it has the same index as *one* another key.
1048
- We have a collision. We need to create a new node which will
1049
- combine the existing key and the key we're adding.
1050
-
1051
- `hamt_node_new_bitmap_or_collision` will either create a new
1052
- Collision node if the keys have identical hashes, or
1053
- a new Bitmap node.
1054
- */
1055
- HamtNode *sub_node = hamt_node_new_bitmap_or_collision(
1056
- get_hamt_state_from_obj((PyObject*)self),
1057
- shift + 5,
1058
- key_or_null, val_or_node, /* existing key/val */
1059
- hash,
1060
- key, val /* new key/val */
1061
- );
1062
- if (sub_node == NULL) {
1063
- return NULL;
1064
- }
1065
-
1066
- HamtNode_Bitmap *ret = hamt_node_bitmap_clone(self);
1067
- if (ret == NULL) {
1068
- Py_DECREF(sub_node);
1069
- return NULL;
1070
- }
1071
- Py_SETREF(ret->b_array[key_idx], NULL);
1072
- Py_SETREF(ret->b_array[val_idx], (PyObject *)sub_node);
1073
-
1074
- *added_leaf = 1;
1075
- return (HamtNode *)ret;
1076
- }
1077
- else {
1078
- /* There was no key before with the same (shift,hash). */
1079
-
1080
- uint32_t n = (uint32_t)_popcount32(self->b_bitmap);
1081
-
1082
- if (n >= 16) {
1083
- /* When we have a situation where we want to store more
1084
- than 16 nodes at one level of the tree, we no longer
1085
- want to use the Bitmap node with bitmap encoding.
1086
-
1087
- Instead we start using an Array node, which has
1088
- simpler (faster) implementation at the expense of
1089
- having preallocated 32 pointers for its keys/values
1090
- pairs.
1091
-
1092
- Small hamt objects (<30 keys) usually don't have any
1093
- Array nodes at all. Between ~30 and ~400 keys hamt
1094
- objects usually have one Array node, and usually it's
1095
- a root node.
1096
- */
1097
-
1098
- uint32_t jdx = hamt_mask(hash, shift);
1099
- /* 'jdx' is the index of where the new key should be added
1100
- in the new Array node we're about to create. */
1101
-
1102
- HamtNode *empty = NULL;
1103
- HamtNode_Array *new_node = NULL;
1104
- HamtNode *res = NULL;
1105
-
1106
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)self);
1107
-
1108
- /* Create a new Array node. */
1109
- new_node = (HamtNode_Array *)hamt_node_array_new(state, n + 1);
1110
- if (new_node == NULL) {
1111
- goto fin;
1112
- }
1113
-
1114
- /* Create an empty bitmap node for the next
1115
- hamt_node_assoc call. */
1116
- empty = hamt_node_bitmap_new(state, 0);
1117
- if (empty == NULL) {
1118
- goto fin;
1119
- }
1120
-
1121
- /* Make a new bitmap node for the key/val we're adding.
1122
- Set that bitmap node to new-array-node[jdx]. */
1123
- new_node->a_array[jdx] = hamt_node_assoc(
1124
- empty, shift + 5, hash, key, val, added_leaf);
1125
- if (new_node->a_array[jdx] == NULL) {
1126
- goto fin;
1127
- }
1128
-
1129
- /* Copy existing key/value pairs from the current Bitmap
1130
- node to the new Array node we've just created. */
1131
- Py_ssize_t i, j;
1132
- for (i = 0, j = 0; i < HAMT_ARRAY_NODE_SIZE; i++) {
1133
- if (((self->b_bitmap >> i) & 1) != 0) {
1134
- /* Ensure we don't accidentally override `jdx` element
1135
- we set few lines above.
1136
- */
1137
- assert(new_node->a_array[i] == NULL);
1138
-
1139
- if (self->b_array[j] == NULL) {
1140
- new_node->a_array[i] =
1141
- (HamtNode *)Py_NewRef(self->b_array[j + 1]);
1142
- }
1143
- else {
1144
- int32_t rehash = hamt_hash(self->b_array[j]);
1145
- if (rehash == -1) {
1146
- goto fin;
1147
- }
1148
-
1149
- new_node->a_array[i] = hamt_node_assoc(
1150
- empty, shift + 5,
1151
- rehash,
1152
- self->b_array[j],
1153
- self->b_array[j + 1],
1154
- added_leaf);
1155
-
1156
- if (new_node->a_array[i] == NULL) {
1157
- goto fin;
1158
- }
1159
- }
1160
- j += 2;
1161
- }
1162
- }
1163
-
1164
- VALIDATE_ARRAY_NODE(new_node)
1165
-
1166
- /* That's it! */
1167
- res = (HamtNode *)new_node;
1168
-
1169
- fin:
1170
- Py_XDECREF(empty);
1171
- if (res == NULL) {
1172
- Py_XDECREF(new_node);
1173
- }
1174
- return res;
1175
- }
1176
- else {
1177
- /* We have less than 16 keys at this level; let's just
1178
- create a new bitmap node out of this node with the
1179
- new key/val pair added. */
1180
-
1181
- uint32_t key_idx = 2 * idx;
1182
- uint32_t val_idx = key_idx + 1;
1183
- uint32_t i;
1184
-
1185
- *added_leaf = 1;
1186
-
1187
- /* Allocate new Bitmap node which can have one more key/val
1188
- pair in addition to what we have already. */
1189
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)self);
1190
- HamtNode_Bitmap *new_node =
1191
- (HamtNode_Bitmap *)hamt_node_bitmap_new(state, 2 * (n + 1));
1192
- if (new_node == NULL) {
1193
- return NULL;
1194
- }
1195
-
1196
- /* Copy all keys/values that will be before the new key/value
1197
- we are adding. */
1198
- for (i = 0; i < key_idx; i++) {
1199
- new_node->b_array[i] = Py_XNewRef(self->b_array[i]);
1200
- }
1201
-
1202
- /* Set the new key/value to the new Bitmap node. */
1203
- new_node->b_array[key_idx] = Py_NewRef(key);
1204
- new_node->b_array[val_idx] = Py_NewRef(val);
1205
-
1206
- /* Copy all keys/values that will be after the new key/value
1207
- we are adding. */
1208
- assert(Py_SIZE(self) >= 0 && Py_SIZE(self) <= 32);
1209
- for (i = key_idx; i < (uint32_t)Py_SIZE(self); i++) {
1210
- new_node->b_array[i + 2] = Py_XNewRef(self->b_array[i]);
1211
- }
1212
-
1213
- new_node->b_bitmap = self->b_bitmap | bit;
1214
- return (HamtNode *)new_node;
1215
- }
1216
- }
1217
- }
1218
-
1219
- static hamt_without_t
1220
- hamt_node_bitmap_without(HamtNode_Bitmap *self,
1221
- uint32_t shift, int32_t hash,
1222
- PyObject *key,
1223
- HamtNode **new_node)
1224
- {
1225
- uint32_t bit = hamt_bitpos(hash, shift);
1226
- if ((self->b_bitmap & bit) == 0) {
1227
- return W_NOT_FOUND;
1228
- }
1229
-
1230
- uint32_t idx = hamt_bitindex(self->b_bitmap, bit);
1231
-
1232
- uint32_t key_idx = 2 * idx;
1233
- uint32_t val_idx = key_idx + 1;
1234
-
1235
- PyObject *key_or_null = self->b_array[key_idx];
1236
- PyObject *val_or_node = self->b_array[val_idx];
1237
-
1238
- if (key_or_null == NULL) {
1239
- /* key == NULL means that 'value' is another tree node. */
1240
-
1241
- HamtNode *sub_node = NULL;
1242
-
1243
- hamt_without_t res = hamt_node_without(
1244
- (HamtNode *)val_or_node,
1245
- shift + 5, hash, key, &sub_node);
1246
-
1247
- switch (res) {
1248
- case W_EMPTY:
1249
- /* It's impossible for us to receive a W_EMPTY here:
1250
-
1251
- - Array nodes are converted to Bitmap nodes when
1252
- we delete 16th item from them;
1253
-
1254
- - Collision nodes are converted to Bitmap when
1255
- there is one item in them;
1256
-
1257
- - Bitmap node's without() inlines single-item
1258
- sub-nodes.
1259
-
1260
- So in no situation we can have a single-item
1261
- Bitmap child of another Bitmap node.
1262
- */
1263
- Py_UNREACHABLE();
1264
-
1265
- case W_NEWNODE: {
1266
- assert(sub_node != NULL);
1267
-
1268
- if (IS_BITMAP_NODE(sub_node)) {
1269
- HamtNode_Bitmap *sub_tree = (HamtNode_Bitmap *)sub_node;
1270
- if (hamt_node_bitmap_count(sub_tree) == 1 &&
1271
- sub_tree->b_array[0] != NULL)
1272
- {
1273
- /* A bitmap node with one key/value pair. Just
1274
- merge it into this node.
1275
-
1276
- Note that we don't inline Bitmap nodes that
1277
- have a NULL key -- those nodes point to another
1278
- tree level, and we cannot simply move tree levels
1279
- up or down.
1280
- */
1281
-
1282
- HamtNode_Bitmap *clone = hamt_node_bitmap_clone(self);
1283
- if (clone == NULL) {
1284
- Py_DECREF(sub_node);
1285
- return W_ERROR;
1286
- }
1287
-
1288
- PyObject *key = sub_tree->b_array[0];
1289
- PyObject *val = sub_tree->b_array[1];
1290
-
1291
- Py_XSETREF(clone->b_array[key_idx], Py_NewRef(key));
1292
- Py_SETREF(clone->b_array[val_idx], Py_NewRef(val));
1293
-
1294
- Py_DECREF(sub_tree);
1295
-
1296
- *new_node = (HamtNode *)clone;
1297
- return W_NEWNODE;
1298
- }
1299
- }
1300
-
1301
- #ifdef Py_DEBUG
1302
- /* Ensure that Collision.without implementation
1303
- converts to Bitmap nodes itself.
1304
- */
1305
- if (IS_COLLISION_NODE(sub_node)) {
1306
- assert(hamt_node_collision_count(
1307
- (HamtNode_Collision*)sub_node) > 1);
1308
- }
1309
- #endif
1310
-
1311
- HamtNode_Bitmap *clone = hamt_node_bitmap_clone(self);
1312
- if (clone == NULL) {
1313
- return W_ERROR;
1314
- }
1315
-
1316
- Py_SETREF(clone->b_array[val_idx],
1317
- (PyObject *)sub_node); /* borrow */
1318
-
1319
- *new_node = (HamtNode *)clone;
1320
- return W_NEWNODE;
1321
- }
1322
-
1323
- case W_ERROR:
1324
- case W_NOT_FOUND:
1325
- assert(sub_node == NULL);
1326
- return res;
1327
-
1328
- default:
1329
- Py_UNREACHABLE();
1330
- }
1331
- }
1332
- else {
1333
- /* We have a regular key/value pair */
1334
-
1335
- int cmp = PyObject_RichCompareBool(key_or_null, key, Py_EQ);
1336
- if (cmp < 0) {
1337
- return W_ERROR;
1338
- }
1339
- if (cmp == 0) {
1340
- return W_NOT_FOUND;
1341
- }
1342
-
1343
- if (hamt_node_bitmap_count(self) == 1) {
1344
- return W_EMPTY;
1345
- }
1346
-
1347
- *new_node = (HamtNode *)
1348
- hamt_node_bitmap_clone_without(self, bit);
1349
- if (*new_node == NULL) {
1350
- return W_ERROR;
1351
- }
1352
-
1353
- return W_NEWNODE;
1354
- }
1355
- }
1356
-
1357
- static hamt_find_t
1358
- hamt_node_bitmap_find(HamtNode_Bitmap *self,
1359
- uint32_t shift, int32_t hash,
1360
- PyObject *key, PyObject **val)
1361
- {
1362
- /* Lookup a key in a Bitmap node. */
1363
-
1364
- uint32_t bit = hamt_bitpos(hash, shift);
1365
- uint32_t idx;
1366
- uint32_t key_idx;
1367
- uint32_t val_idx;
1368
- PyObject *key_or_null;
1369
- PyObject *val_or_node;
1370
- int comp_err;
1371
-
1372
- if ((self->b_bitmap & bit) == 0) {
1373
- return F_NOT_FOUND;
1374
- }
1375
-
1376
- idx = hamt_bitindex(self->b_bitmap, bit);
1377
- key_idx = idx * 2;
1378
- val_idx = key_idx + 1;
1379
-
1380
- assert(val_idx < (size_t)Py_SIZE(self));
1381
-
1382
- key_or_null = self->b_array[key_idx];
1383
- val_or_node = self->b_array[val_idx];
1384
-
1385
- if (key_or_null == NULL) {
1386
- /* There are a few keys that have the same hash at the current shift
1387
- that match our key. Dispatch the lookup further down the tree. */
1388
- assert(val_or_node != NULL);
1389
- return hamt_node_find((HamtNode *)val_or_node,
1390
- shift + 5, hash, key, val);
1391
- }
1392
-
1393
- /* We have only one key -- a potential match. Let's compare if the
1394
- key we are looking at is equal to the key we are looking for. */
1395
- assert(key != NULL);
1396
- comp_err = PyObject_RichCompareBool(key, key_or_null, Py_EQ);
1397
- if (comp_err < 0) { /* exception in __eq__ */
1398
- return F_ERROR;
1399
- }
1400
- if (comp_err == 1) { /* key == key_or_null */
1401
- *val = val_or_node;
1402
- return F_FOUND;
1403
- }
1404
-
1405
- return F_NOT_FOUND;
1406
- }
1407
-
1408
- static int
1409
- hamt_node_bitmap_traverse(HamtNode_Bitmap *self, visitproc visit, void *arg)
1410
- {
1411
- /* Bitmap's tp_traverse */
1412
-
1413
- Py_ssize_t i;
1414
-
1415
- for (i = Py_SIZE(self); --i >= 0; ) {
1416
- Py_VISIT(self->b_array[i]);
1417
- }
1418
-
1419
- return 0;
1420
- }
1421
-
1422
- static void
1423
- hamt_node_bitmap_dealloc(HamtNode_Bitmap *self)
1424
- {
1425
- /* Bitmap's tp_dealloc */
1426
-
1427
- Py_ssize_t len = Py_SIZE(self);
1428
- Py_ssize_t i;
1429
-
1430
- if (Py_SIZE(self) == 0) {
1431
- /* The empty node is managed by the module state. */
1432
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)self);
1433
- assert(self == state->empty_bitmap_node);
1434
- #ifdef Py_DEBUG
1435
- _Py_FatalRefcountError("deallocating the empty hamt node bitmap singleton");
1436
- #else
1437
- return;
1438
- #endif
1439
- }
1440
-
1441
- PyObject_GC_UnTrack(self);
1442
- Py_TRASHCAN_BEGIN(self, hamt_node_bitmap_dealloc)
1443
-
1444
- if (len > 0) {
1445
- i = len;
1446
- while (--i >= 0) {
1447
- Py_XDECREF(self->b_array[i]);
1448
- }
1449
- }
1450
-
1451
- Py_TYPE(self)->tp_free((PyObject *)self);
1452
- Py_TRASHCAN_END
1453
- }
1454
-
1455
- #ifdef Py_DEBUG
1456
- static int
1457
- hamt_node_bitmap_dump(HamtNode_Bitmap *node,
1458
- _PyUnicodeWriter *writer, int level)
1459
- {
1460
- /* Debug build: __dump__() method implementation for Bitmap nodes. */
1461
-
1462
- Py_ssize_t i;
1463
- PyObject *tmp1;
1464
- PyObject *tmp2;
1465
-
1466
- if (_hamt_dump_ident(writer, level + 1)) {
1467
- goto error;
1468
- }
1469
-
1470
- if (_hamt_dump_format(writer, "BitmapNode(size=%zd count=%zd ",
1471
- Py_SIZE(node), Py_SIZE(node) / 2))
1472
- {
1473
- goto error;
1474
- }
1475
-
1476
- tmp1 = PyLong_FromUnsignedLong(node->b_bitmap);
1477
- if (tmp1 == NULL) {
1478
- goto error;
1479
- }
1480
- // Format as binary using format spec 'b' (like f"{num:b}" in Python)
1481
- PyObject *format_spec = PyUnicode_FromString("b");
1482
- if (format_spec == NULL) {
1483
- Py_DECREF(tmp1);
1484
- goto error;
1485
- }
1486
- tmp2 = PyObject_Format(tmp1, format_spec);
1487
- Py_DECREF(format_spec);
1488
- Py_DECREF(tmp1);
1489
- if (tmp2 == NULL) {
1490
- goto error;
1491
- }
1492
- if (_hamt_dump_format(writer, "bitmap=%S id=%p):\n", tmp2, node)) {
1493
- Py_DECREF(tmp2);
1494
- goto error;
1495
- }
1496
- Py_DECREF(tmp2);
1497
-
1498
- for (i = 0; i < Py_SIZE(node); i += 2) {
1499
- PyObject *key_or_null = node->b_array[i];
1500
- PyObject *val_or_node = node->b_array[i + 1];
1501
-
1502
- if (_hamt_dump_ident(writer, level + 2)) {
1503
- goto error;
1504
- }
1505
-
1506
- if (key_or_null == NULL) {
1507
- if (_hamt_dump_format(writer, "NULL:\n")) {
1508
- goto error;
1509
- }
1510
-
1511
- if (hamt_node_dump((HamtNode *)val_or_node,
1512
- writer, level + 2))
1513
- {
1514
- goto error;
1515
- }
1516
- }
1517
- else {
1518
- if (_hamt_dump_format(writer, "%R: %R", key_or_null,
1519
- val_or_node))
1520
- {
1521
- goto error;
1522
- }
1523
- }
1524
-
1525
- if (_hamt_dump_format(writer, "\n")) {
1526
- goto error;
1527
- }
1528
- }
1529
-
1530
- return 0;
1531
- error:
1532
- return -1;
1533
- }
1534
- #endif /* Py_DEBUG */
1535
-
1536
-
1537
- /////////////////////////////////// Collision Node
1538
-
1539
-
1540
- static HamtNode *
1541
- hamt_node_collision_new(hamt_module_state *state, int32_t hash, Py_ssize_t size)
1542
- {
1543
- /* Create a new Collision node. */
1544
-
1545
- HamtNode_Collision *node;
1546
- Py_ssize_t i;
1547
-
1548
- assert(size >= 4);
1549
- assert(size % 2 == 0);
1550
-
1551
- node = PyObject_GC_NewVar(
1552
- HamtNode_Collision, state->Hamt_CollisionNode_Type, size);
1553
- if (node == NULL) {
1554
- return NULL;
1555
- }
1556
-
1557
- for (i = 0; i < size; i++) {
1558
- node->c_array[i] = NULL;
1559
- }
1560
-
1561
- Py_SET_SIZE(node, size);
1562
- node->c_hash = hash;
1563
-
1564
- PyObject_GC_Track(node);
1565
-
1566
- return (HamtNode *)node;
1567
- }
1568
-
1569
- static hamt_find_t
1570
- hamt_node_collision_find_index(HamtNode_Collision *self, PyObject *key,
1571
- Py_ssize_t *idx)
1572
- {
1573
- /* Lookup `key` in the Collision node `self`. Set the index of the
1574
- found key to 'idx'. */
1575
-
1576
- Py_ssize_t i;
1577
- PyObject *el;
1578
-
1579
- for (i = 0; i < Py_SIZE(self); i += 2) {
1580
- el = self->c_array[i];
1581
-
1582
- assert(el != NULL);
1583
- int cmp = PyObject_RichCompareBool(key, el, Py_EQ);
1584
- if (cmp < 0) {
1585
- return F_ERROR;
1586
- }
1587
- if (cmp == 1) {
1588
- *idx = i;
1589
- return F_FOUND;
1590
- }
1591
- }
1592
-
1593
- return F_NOT_FOUND;
1594
- }
1595
-
1596
- static HamtNode *
1597
- hamt_node_collision_assoc(HamtNode_Collision *self,
1598
- uint32_t shift, int32_t hash,
1599
- PyObject *key, PyObject *val, int* added_leaf)
1600
- {
1601
- /* Set a new key to this level (currently a Collision node)
1602
- of the tree. */
1603
-
1604
- if (hash == self->c_hash) {
1605
- /* The hash of the 'key' we are adding matches the hash of
1606
- other keys in this Collision node. */
1607
-
1608
- Py_ssize_t key_idx = -1;
1609
- hamt_find_t found;
1610
- HamtNode_Collision *new_node;
1611
- Py_ssize_t i;
1612
- hamt_module_state *state;
1613
-
1614
- /* Let's try to lookup the new 'key', maybe we already have it. */
1615
- found = hamt_node_collision_find_index(self, key, &key_idx);
1616
- switch (found) {
1617
- case F_ERROR:
1618
- /* Exception. */
1619
- return NULL;
1620
-
1621
- case F_NOT_FOUND:
1622
- /* This is a totally new key. Clone the current node,
1623
- add a new key/value to the cloned node. */
1624
-
1625
- state = get_hamt_state_from_obj((PyObject*)self);
1626
- new_node = (HamtNode_Collision *)hamt_node_collision_new(
1627
- state, self->c_hash, Py_SIZE(self) + 2);
1628
- if (new_node == NULL) {
1629
- return NULL;
1630
- }
1631
-
1632
- for (i = 0; i < Py_SIZE(self); i++) {
1633
- new_node->c_array[i] = Py_NewRef(self->c_array[i]);
1634
- }
1635
-
1636
- new_node->c_array[i] = Py_NewRef(key);
1637
- new_node->c_array[i + 1] = Py_NewRef(val);
1638
-
1639
- *added_leaf = 1;
1640
- return (HamtNode *)new_node;
1641
-
1642
- case F_FOUND:
1643
- /* There's a key which is equal to the key we are adding. */
1644
-
1645
- assert(key_idx >= 0);
1646
- assert(key_idx < Py_SIZE(self));
1647
- Py_ssize_t val_idx = key_idx + 1;
1648
-
1649
- if (self->c_array[val_idx] == val) {
1650
- /* We're setting a key/value pair that's already set. */
1651
- return (HamtNode *)Py_NewRef(self);
1652
- }
1653
-
1654
- /* We need to replace old value for the key
1655
- with a new value. Create a new Collision node.*/
1656
- hamt_module_state *state2 = get_hamt_state_from_obj((PyObject*)self);
1657
- new_node = (HamtNode_Collision *)hamt_node_collision_new(
1658
- state2, self->c_hash, Py_SIZE(self));
1659
- if (new_node == NULL) {
1660
- return NULL;
1661
- }
1662
-
1663
- /* Copy all elements of the old node to the new one. */
1664
- for (i = 0; i < Py_SIZE(self); i++) {
1665
- new_node->c_array[i] = Py_NewRef(self->c_array[i]);
1666
- }
1667
-
1668
- /* Replace the old value with the new value for the our key. */
1669
- Py_SETREF(new_node->c_array[val_idx], Py_NewRef(val));
1670
-
1671
- return (HamtNode *)new_node;
1672
-
1673
- default:
1674
- Py_UNREACHABLE();
1675
- }
1676
- }
1677
- else {
1678
- /* The hash of the new key is different from the hash that
1679
- all keys of this Collision node have.
1680
-
1681
- Create a Bitmap node inplace with two children:
1682
- key/value pair that we're adding, and the Collision node
1683
- we're replacing on this tree level.
1684
- */
1685
-
1686
- HamtNode_Bitmap *new_node;
1687
- HamtNode *assoc_res;
1688
-
1689
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)self);
1690
- new_node = (HamtNode_Bitmap *)hamt_node_bitmap_new(state, 2);
1691
- if (new_node == NULL) {
1692
- return NULL;
1693
- }
1694
- new_node->b_bitmap = hamt_bitpos(self->c_hash, shift);
1695
- new_node->b_array[1] = Py_NewRef(self);
1696
-
1697
- assoc_res = hamt_node_bitmap_assoc(
1698
- new_node, shift, hash, key, val, added_leaf);
1699
- Py_DECREF(new_node);
1700
- return assoc_res;
1701
- }
1702
- }
1703
-
1704
- static inline Py_ssize_t
1705
- hamt_node_collision_count(HamtNode_Collision *node)
1706
- {
1707
- return Py_SIZE(node) / 2;
1708
- }
1709
-
1710
- static hamt_without_t
1711
- hamt_node_collision_without(HamtNode_Collision *self,
1712
- uint32_t shift, int32_t hash,
1713
- PyObject *key,
1714
- HamtNode **new_node)
1715
- {
1716
- if (hash != self->c_hash) {
1717
- return W_NOT_FOUND;
1718
- }
1719
-
1720
- Py_ssize_t key_idx = -1;
1721
- hamt_find_t found = hamt_node_collision_find_index(self, key, &key_idx);
1722
-
1723
- switch (found) {
1724
- case F_ERROR:
1725
- return W_ERROR;
1726
-
1727
- case F_NOT_FOUND:
1728
- return W_NOT_FOUND;
1729
-
1730
- case F_FOUND:
1731
- assert(key_idx >= 0);
1732
- assert(key_idx < Py_SIZE(self));
1733
-
1734
- Py_ssize_t new_count = hamt_node_collision_count(self) - 1;
1735
-
1736
- if (new_count == 0) {
1737
- /* The node has only one key/value pair and it's for the
1738
- key we're trying to delete. So a new node will be empty
1739
- after the removal.
1740
- */
1741
- return W_EMPTY;
1742
- }
1743
-
1744
- if (new_count == 1) {
1745
- /* The node has two keys, and after deletion the
1746
- new Collision node would have one. Collision nodes
1747
- with one key shouldn't exist, so convert it to a
1748
- Bitmap node.
1749
- */
1750
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)self);
1751
- HamtNode_Bitmap *node = (HamtNode_Bitmap *)
1752
- hamt_node_bitmap_new(state, 2);
1753
- if (node == NULL) {
1754
- return W_ERROR;
1755
- }
1756
-
1757
- if (key_idx == 0) {
1758
- node->b_array[0] = Py_NewRef(self->c_array[2]);
1759
- node->b_array[1] = Py_NewRef(self->c_array[3]);
1760
- }
1761
- else {
1762
- assert(key_idx == 2);
1763
- node->b_array[0] = Py_NewRef(self->c_array[0]);
1764
- node->b_array[1] = Py_NewRef(self->c_array[1]);
1765
- }
1766
-
1767
- node->b_bitmap = hamt_bitpos(hash, shift);
1768
-
1769
- *new_node = (HamtNode *)node;
1770
- return W_NEWNODE;
1771
- }
1772
-
1773
- /* Allocate a new Collision node with capacity for one
1774
- less key/value pair */
1775
- hamt_module_state *state3 = get_hamt_state_from_obj((PyObject*)self);
1776
- HamtNode_Collision *new = (HamtNode_Collision *)
1777
- hamt_node_collision_new(
1778
- state3, self->c_hash, Py_SIZE(self) - 2);
1779
- if (new == NULL) {
1780
- return W_ERROR;
1781
- }
1782
-
1783
- /* Copy all other keys from `self` to `new` */
1784
- Py_ssize_t i;
1785
- for (i = 0; i < key_idx; i++) {
1786
- new->c_array[i] = Py_NewRef(self->c_array[i]);
1787
- }
1788
- for (i = key_idx + 2; i < Py_SIZE(self); i++) {
1789
- new->c_array[i - 2] = Py_NewRef(self->c_array[i]);
1790
- }
1791
-
1792
- *new_node = (HamtNode*)new;
1793
- return W_NEWNODE;
1794
-
1795
- default:
1796
- Py_UNREACHABLE();
1797
- }
1798
- }
1799
-
1800
- static hamt_find_t
1801
- hamt_node_collision_find(HamtNode_Collision *self,
1802
- uint32_t shift, int32_t hash,
1803
- PyObject *key, PyObject **val)
1804
- {
1805
- /* Lookup `key` in the Collision node `self`. Set the value
1806
- for the found key to 'val'. */
1807
-
1808
- Py_ssize_t idx = -1;
1809
- hamt_find_t res;
1810
-
1811
- res = hamt_node_collision_find_index(self, key, &idx);
1812
- if (res == F_ERROR || res == F_NOT_FOUND) {
1813
- return res;
1814
- }
1815
-
1816
- assert(idx >= 0);
1817
- assert(idx + 1 < Py_SIZE(self));
1818
-
1819
- *val = self->c_array[idx + 1];
1820
- assert(*val != NULL);
1821
-
1822
- return F_FOUND;
1823
- }
1824
-
1825
-
1826
- static int
1827
- hamt_node_collision_traverse(HamtNode_Collision *self,
1828
- visitproc visit, void *arg)
1829
- {
1830
- /* Collision's tp_traverse */
1831
-
1832
- Py_ssize_t i;
1833
-
1834
- for (i = Py_SIZE(self); --i >= 0; ) {
1835
- Py_VISIT(self->c_array[i]);
1836
- }
1837
-
1838
- return 0;
1839
- }
1840
-
1841
- static void
1842
- hamt_node_collision_dealloc(HamtNode_Collision *self)
1843
- {
1844
- /* Collision's tp_dealloc */
1845
-
1846
- Py_ssize_t len = Py_SIZE(self);
1847
-
1848
- PyObject_GC_UnTrack(self);
1849
- Py_TRASHCAN_BEGIN(self, hamt_node_collision_dealloc)
1850
-
1851
- if (len > 0) {
1852
-
1853
- while (--len >= 0) {
1854
- Py_XDECREF(self->c_array[len]);
1855
- }
1856
- }
1857
-
1858
- Py_TYPE(self)->tp_free((PyObject *)self);
1859
- Py_TRASHCAN_END
1860
- }
1861
-
1862
- #ifdef Py_DEBUG
1863
- static int
1864
- hamt_node_collision_dump(HamtNode_Collision *node,
1865
- _PyUnicodeWriter *writer, int level)
1866
- {
1867
- /* Debug build: __dump__() method implementation for Collision nodes. */
1868
-
1869
- Py_ssize_t i;
1870
-
1871
- if (_hamt_dump_ident(writer, level + 1)) {
1872
- goto error;
1873
- }
1874
-
1875
- if (_hamt_dump_format(writer, "CollisionNode(size=%zd id=%p):\n",
1876
- Py_SIZE(node), node))
1877
- {
1878
- goto error;
1879
- }
1880
-
1881
- for (i = 0; i < Py_SIZE(node); i += 2) {
1882
- PyObject *key = node->c_array[i];
1883
- PyObject *val = node->c_array[i + 1];
1884
-
1885
- if (_hamt_dump_ident(writer, level + 2)) {
1886
- goto error;
1887
- }
1888
-
1889
- if (_hamt_dump_format(writer, "%R: %R\n", key, val)) {
1890
- goto error;
1891
- }
1892
- }
1893
-
1894
- return 0;
1895
- error:
1896
- return -1;
1897
- }
1898
- #endif /* Py_DEBUG */
1899
-
1900
-
1901
- /////////////////////////////////// Array Node
1902
-
1903
-
1904
- static HamtNode *
1905
- hamt_node_array_new(hamt_module_state *state, Py_ssize_t count)
1906
- {
1907
- Py_ssize_t i;
1908
-
1909
- HamtNode_Array *node = PyObject_GC_New(
1910
- HamtNode_Array, state->Hamt_ArrayNode_Type);
1911
- if (node == NULL) {
1912
- return NULL;
1913
- }
1914
-
1915
- for (i = 0; i < HAMT_ARRAY_NODE_SIZE; i++) {
1916
- node->a_array[i] = NULL;
1917
- }
1918
-
1919
- node->a_count = count;
1920
-
1921
- PyObject_GC_Track(node);
1922
- return (HamtNode *)node;
1923
- }
1924
-
1925
- static HamtNode_Array *
1926
- hamt_node_array_clone(HamtNode_Array *node)
1927
- {
1928
- HamtNode_Array *clone;
1929
- Py_ssize_t i;
1930
-
1931
- VALIDATE_ARRAY_NODE(node)
1932
-
1933
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)node);
1934
-
1935
- /* Create a new Array node. */
1936
- clone = (HamtNode_Array *)hamt_node_array_new(state, node->a_count);
1937
- if (clone == NULL) {
1938
- return NULL;
1939
- }
1940
-
1941
- /* Copy all elements from the current Array node to the new one. */
1942
- for (i = 0; i < HAMT_ARRAY_NODE_SIZE; i++) {
1943
- clone->a_array[i] = (HamtNode*)Py_XNewRef(node->a_array[i]);
1944
- }
1945
-
1946
- VALIDATE_ARRAY_NODE(clone)
1947
- return clone;
1948
- }
1949
-
1950
- static HamtNode *
1951
- hamt_node_array_assoc(HamtNode_Array *self,
1952
- uint32_t shift, int32_t hash,
1953
- PyObject *key, PyObject *val, int* added_leaf)
1954
- {
1955
- /* Set a new key to this level (currently a Collision node)
1956
- of the tree.
1957
-
1958
- Array nodes don't store values, they can only point to
1959
- other nodes. They are simple arrays of 32 BaseNode pointers/
1960
- */
1961
-
1962
- uint32_t idx = hamt_mask(hash, shift);
1963
- HamtNode *node = self->a_array[idx];
1964
- HamtNode *child_node;
1965
- HamtNode_Array *new_node;
1966
- Py_ssize_t i;
1967
-
1968
- if (node == NULL) {
1969
- /* There's no child node for the given hash. Create a new
1970
- Bitmap node for this key. */
1971
-
1972
- HamtNode_Bitmap *empty = NULL;
1973
-
1974
- /* Get an empty Bitmap node to work with. */
1975
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)self);
1976
- empty = (HamtNode_Bitmap *)hamt_node_bitmap_new(state, 0);
1977
- if (empty == NULL) {
1978
- return NULL;
1979
- }
1980
-
1981
- /* Set key/val to the newly created empty Bitmap, thus
1982
- creating a new Bitmap node with our key/value pair. */
1983
- child_node = hamt_node_bitmap_assoc(
1984
- empty,
1985
- shift + 5, hash, key, val, added_leaf);
1986
- Py_DECREF(empty);
1987
- if (child_node == NULL) {
1988
- return NULL;
1989
- }
1990
-
1991
- /* Create a new Array node. */
1992
- new_node = (HamtNode_Array *)hamt_node_array_new(state, self->a_count + 1);
1993
- if (new_node == NULL) {
1994
- Py_DECREF(child_node);
1995
- return NULL;
1996
- }
1997
-
1998
- /* Copy all elements from the current Array node to the
1999
- new one. */
2000
- for (i = 0; i < HAMT_ARRAY_NODE_SIZE; i++) {
2001
- new_node->a_array[i] = (HamtNode*)Py_XNewRef(self->a_array[i]);
2002
- }
2003
-
2004
- assert(new_node->a_array[idx] == NULL);
2005
- new_node->a_array[idx] = child_node; /* borrow */
2006
- VALIDATE_ARRAY_NODE(new_node)
2007
- }
2008
- else {
2009
- /* There's a child node for the given hash.
2010
- Set the key to it./ */
2011
- child_node = hamt_node_assoc(
2012
- node, shift + 5, hash, key, val, added_leaf);
2013
- if (child_node == NULL) {
2014
- return NULL;
2015
- }
2016
- else if (child_node == (HamtNode *)self) {
2017
- Py_DECREF(child_node);
2018
- return (HamtNode *)self;
2019
- }
2020
-
2021
- new_node = hamt_node_array_clone(self);
2022
- if (new_node == NULL) {
2023
- Py_DECREF(child_node);
2024
- return NULL;
2025
- }
2026
-
2027
- Py_SETREF(new_node->a_array[idx], child_node); /* borrow */
2028
- VALIDATE_ARRAY_NODE(new_node)
2029
- }
2030
-
2031
- return (HamtNode *)new_node;
2032
- }
2033
-
2034
- static hamt_without_t
2035
- hamt_node_array_without(HamtNode_Array *self,
2036
- uint32_t shift, int32_t hash,
2037
- PyObject *key,
2038
- HamtNode **new_node)
2039
- {
2040
- uint32_t idx = hamt_mask(hash, shift);
2041
- HamtNode *node = self->a_array[idx];
2042
-
2043
- if (node == NULL) {
2044
- return W_NOT_FOUND;
2045
- }
2046
-
2047
- HamtNode *sub_node = NULL;
2048
- hamt_without_t res = hamt_node_without(
2049
- (HamtNode *)node,
2050
- shift + 5, hash, key, &sub_node);
2051
-
2052
- switch (res) {
2053
- case W_NOT_FOUND:
2054
- case W_ERROR:
2055
- assert(sub_node == NULL);
2056
- return res;
2057
-
2058
- case W_NEWNODE: {
2059
- /* We need to replace a node at the `idx` index.
2060
- Clone this node and replace.
2061
- */
2062
- assert(sub_node != NULL);
2063
-
2064
- HamtNode_Array *clone = hamt_node_array_clone(self);
2065
- if (clone == NULL) {
2066
- Py_DECREF(sub_node);
2067
- return W_ERROR;
2068
- }
2069
-
2070
- Py_SETREF(clone->a_array[idx], sub_node); /* borrow */
2071
- *new_node = (HamtNode*)clone; /* borrow */
2072
- return W_NEWNODE;
2073
- }
2074
-
2075
- case W_EMPTY: {
2076
- assert(sub_node == NULL);
2077
- /* We need to remove a node at the `idx` index.
2078
- Calculate the size of the replacement Array node.
2079
- */
2080
- Py_ssize_t new_count = self->a_count - 1;
2081
-
2082
- if (new_count == 0) {
2083
- return W_EMPTY;
2084
- }
2085
-
2086
- if (new_count >= 16) {
2087
- /* We convert Bitmap nodes to Array nodes, when a
2088
- Bitmap node needs to store more than 15 key/value
2089
- pairs. So we will create a new Array node if we
2090
- the number of key/values after deletion is still
2091
- greater than 15.
2092
- */
2093
-
2094
- HamtNode_Array *new = hamt_node_array_clone(self);
2095
- if (new == NULL) {
2096
- return W_ERROR;
2097
- }
2098
- new->a_count = new_count;
2099
- Py_CLEAR(new->a_array[idx]);
2100
-
2101
- *new_node = (HamtNode*)new; /* borrow */
2102
- return W_NEWNODE;
2103
- }
2104
-
2105
- /* New Array node would have less than 16 key/value
2106
- pairs. We need to create a replacement Bitmap node. */
2107
-
2108
- Py_ssize_t bitmap_size = new_count * 2;
2109
- uint32_t bitmap = 0;
2110
-
2111
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)self);
2112
- HamtNode_Bitmap *new = (HamtNode_Bitmap *)
2113
- hamt_node_bitmap_new(state, bitmap_size);
2114
- if (new == NULL) {
2115
- return W_ERROR;
2116
- }
2117
-
2118
- Py_ssize_t new_i = 0;
2119
- for (uint32_t i = 0; i < HAMT_ARRAY_NODE_SIZE; i++) {
2120
- if (i == idx) {
2121
- /* Skip the node we are deleting. */
2122
- continue;
2123
- }
2124
-
2125
- HamtNode *node = self->a_array[i];
2126
- if (node == NULL) {
2127
- /* Skip any missing nodes. */
2128
- continue;
2129
- }
2130
-
2131
- bitmap |= 1U << i;
2132
-
2133
- if (IS_BITMAP_NODE(node)) {
2134
- HamtNode_Bitmap *child = (HamtNode_Bitmap *)node;
2135
-
2136
- if (hamt_node_bitmap_count(child) == 1 &&
2137
- child->b_array[0] != NULL)
2138
- {
2139
- /* node is a Bitmap with one key/value pair, just
2140
- merge it into the new Bitmap node we're building.
2141
-
2142
- Note that we don't inline Bitmap nodes that
2143
- have a NULL key -- those nodes point to another
2144
- tree level, and we cannot simply move tree levels
2145
- up or down.
2146
- */
2147
- PyObject *key = child->b_array[0];
2148
- PyObject *val = child->b_array[1];
2149
-
2150
- new->b_array[new_i] = Py_NewRef(key);
2151
- new->b_array[new_i + 1] = Py_NewRef(val);
2152
- }
2153
- else {
2154
- new->b_array[new_i] = NULL;
2155
- new->b_array[new_i + 1] = Py_NewRef(node);
2156
- }
2157
- }
2158
- else {
2159
-
2160
- #ifdef Py_DEBUG
2161
- if (IS_COLLISION_NODE(node)) {
2162
- Py_ssize_t child_count = hamt_node_collision_count(
2163
- (HamtNode_Collision*)node);
2164
- assert(child_count > 1);
2165
- }
2166
- else if (IS_ARRAY_NODE(node)) {
2167
- assert(((HamtNode_Array*)node)->a_count >= 16);
2168
- }
2169
- #endif
2170
-
2171
- /* Just copy the node into our new Bitmap */
2172
- new->b_array[new_i] = NULL;
2173
- new->b_array[new_i + 1] = Py_NewRef(node);
2174
- }
2175
-
2176
- new_i += 2;
2177
- }
2178
-
2179
- new->b_bitmap = bitmap;
2180
- *new_node = (HamtNode*)new; /* borrow */
2181
- return W_NEWNODE;
2182
- }
2183
-
2184
- default:
2185
- Py_UNREACHABLE();
2186
- }
2187
- }
2188
-
2189
- static hamt_find_t
2190
- hamt_node_array_find(HamtNode_Array *self,
2191
- uint32_t shift, int32_t hash,
2192
- PyObject *key, PyObject **val)
2193
- {
2194
- /* Lookup `key` in the Array node `self`. Set the value
2195
- for the found key to 'val'. */
2196
-
2197
- uint32_t idx = hamt_mask(hash, shift);
2198
- HamtNode *node;
2199
-
2200
- node = self->a_array[idx];
2201
- if (node == NULL) {
2202
- return F_NOT_FOUND;
2203
- }
2204
-
2205
- /* Dispatch to the generic hamt_node_find */
2206
- return hamt_node_find(node, shift + 5, hash, key, val);
2207
- }
2208
-
2209
- static int
2210
- hamt_node_array_traverse(HamtNode_Array *self,
2211
- visitproc visit, void *arg)
2212
- {
2213
- /* Array's tp_traverse */
2214
-
2215
- Py_ssize_t i;
2216
-
2217
- for (i = 0; i < HAMT_ARRAY_NODE_SIZE; i++) {
2218
- Py_VISIT(self->a_array[i]);
2219
- }
2220
-
2221
- return 0;
2222
- }
2223
-
2224
- static void
2225
- hamt_node_array_dealloc(HamtNode_Array *self)
2226
- {
2227
- /* Array's tp_dealloc */
2228
-
2229
- Py_ssize_t i;
2230
-
2231
- PyObject_GC_UnTrack(self);
2232
- Py_TRASHCAN_BEGIN(self, hamt_node_array_dealloc)
2233
-
2234
- for (i = 0; i < HAMT_ARRAY_NODE_SIZE; i++) {
2235
- Py_XDECREF(self->a_array[i]);
2236
- }
2237
-
2238
- Py_TYPE(self)->tp_free((PyObject *)self);
2239
- Py_TRASHCAN_END
2240
- }
2241
-
2242
- #ifdef Py_DEBUG
2243
- static int
2244
- hamt_node_array_dump(HamtNode_Array *node,
2245
- _PyUnicodeWriter *writer, int level)
2246
- {
2247
- /* Debug build: __dump__() method implementation for Array nodes. */
2248
-
2249
- Py_ssize_t i;
2250
-
2251
- if (_hamt_dump_ident(writer, level + 1)) {
2252
- goto error;
2253
- }
2254
-
2255
- if (_hamt_dump_format(writer, "ArrayNode(id=%p):\n", node)) {
2256
- goto error;
2257
- }
2258
-
2259
- for (i = 0; i < HAMT_ARRAY_NODE_SIZE; i++) {
2260
- if (node->a_array[i] == NULL) {
2261
- continue;
2262
- }
2263
-
2264
- if (_hamt_dump_ident(writer, level + 2)) {
2265
- goto error;
2266
- }
2267
-
2268
- if (_hamt_dump_format(writer, "%zd::\n", i)) {
2269
- goto error;
2270
- }
2271
-
2272
- if (hamt_node_dump(node->a_array[i], writer, level + 1)) {
2273
- goto error;
2274
- }
2275
-
2276
- if (_hamt_dump_format(writer, "\n")) {
2277
- goto error;
2278
- }
2279
- }
2280
-
2281
- return 0;
2282
- error:
2283
- return -1;
2284
- }
2285
- #endif /* Py_DEBUG */
2286
-
2287
-
2288
- /////////////////////////////////// Node Dispatch
2289
-
2290
-
2291
- static HamtNode *
2292
- hamt_node_assoc(HamtNode *node,
2293
- uint32_t shift, int32_t hash,
2294
- PyObject *key, PyObject *val, int* added_leaf)
2295
- {
2296
- /* Set key/value to the 'node' starting with the given shift/hash.
2297
- Return a new node, or the same node if key/value already
2298
- set.
2299
-
2300
- added_leaf will be set to 1 if key/value wasn't in the
2301
- tree before.
2302
-
2303
- This method automatically dispatches to the suitable
2304
- hamt_node_{nodetype}_assoc method.
2305
- */
2306
-
2307
- if (IS_BITMAP_NODE(node)) {
2308
- return hamt_node_bitmap_assoc(
2309
- (HamtNode_Bitmap *)node,
2310
- shift, hash, key, val, added_leaf);
2311
- }
2312
- else if (IS_ARRAY_NODE(node)) {
2313
- return hamt_node_array_assoc(
2314
- (HamtNode_Array *)node,
2315
- shift, hash, key, val, added_leaf);
2316
- }
2317
- else {
2318
- assert(IS_COLLISION_NODE(node));
2319
- return hamt_node_collision_assoc(
2320
- (HamtNode_Collision *)node,
2321
- shift, hash, key, val, added_leaf);
2322
- }
2323
- }
2324
-
2325
- static hamt_without_t
2326
- hamt_node_without(HamtNode *node,
2327
- uint32_t shift, int32_t hash,
2328
- PyObject *key,
2329
- HamtNode **new_node)
2330
- {
2331
- if (IS_BITMAP_NODE(node)) {
2332
- return hamt_node_bitmap_without(
2333
- (HamtNode_Bitmap *)node,
2334
- shift, hash, key,
2335
- new_node);
2336
- }
2337
- else if (IS_ARRAY_NODE(node)) {
2338
- return hamt_node_array_without(
2339
- (HamtNode_Array *)node,
2340
- shift, hash, key,
2341
- new_node);
2342
- }
2343
- else {
2344
- assert(IS_COLLISION_NODE(node));
2345
- return hamt_node_collision_without(
2346
- (HamtNode_Collision *)node,
2347
- shift, hash, key,
2348
- new_node);
2349
- }
2350
- }
2351
-
2352
- static hamt_find_t
2353
- hamt_node_find(HamtNode *node,
2354
- uint32_t shift, int32_t hash,
2355
- PyObject *key, PyObject **val)
2356
- {
2357
- /* Find the key in the node starting with the given shift/hash.
2358
-
2359
- If a value is found, the result will be set to F_FOUND, and
2360
- *val will point to the found value object.
2361
-
2362
- If a value wasn't found, the result will be set to F_NOT_FOUND.
2363
-
2364
- If an exception occurs during the call, the result will be F_ERROR.
2365
-
2366
- This method automatically dispatches to the suitable
2367
- hamt_node_{nodetype}_find method.
2368
- */
2369
-
2370
- if (IS_BITMAP_NODE(node)) {
2371
- return hamt_node_bitmap_find(
2372
- (HamtNode_Bitmap *)node,
2373
- shift, hash, key, val);
2374
-
2375
- }
2376
- else if (IS_ARRAY_NODE(node)) {
2377
- return hamt_node_array_find(
2378
- (HamtNode_Array *)node,
2379
- shift, hash, key, val);
2380
- }
2381
- else {
2382
- assert(IS_COLLISION_NODE(node));
2383
- return hamt_node_collision_find(
2384
- (HamtNode_Collision *)node,
2385
- shift, hash, key, val);
2386
- }
2387
- }
2388
-
2389
- #ifdef Py_DEBUG
2390
- static int
2391
- hamt_node_dump(HamtNode *node,
2392
- _PyUnicodeWriter *writer, int level)
2393
- {
2394
- /* Debug build: __dump__() method implementation for a node.
2395
-
2396
- This method automatically dispatches to the suitable
2397
- hamt_node_{nodetype})_dump method.
2398
- */
2399
-
2400
- if (IS_BITMAP_NODE(node)) {
2401
- return hamt_node_bitmap_dump(
2402
- (HamtNode_Bitmap *)node, writer, level);
2403
- }
2404
- else if (IS_ARRAY_NODE(node)) {
2405
- return hamt_node_array_dump(
2406
- (HamtNode_Array *)node, writer, level);
2407
- }
2408
- else {
2409
- assert(IS_COLLISION_NODE(node));
2410
- return hamt_node_collision_dump(
2411
- (HamtNode_Collision *)node, writer, level);
2412
- }
2413
- }
2414
- #endif /* Py_DEBUG */
2415
-
2416
-
2417
- /////////////////////////////////// Iterators: Machinery
2418
-
2419
-
2420
- static hamt_iter_t
2421
- hamt_iterator_next(HamtIteratorState *iter, PyObject **key, PyObject **val);
2422
-
2423
-
2424
- static void
2425
- hamt_iterator_init(HamtIteratorState *iter, HamtNode *root)
2426
- {
2427
- for (uint32_t i = 0; i < _Py_HAMT_MAX_TREE_DEPTH; i++) {
2428
- iter->i_nodes[i] = NULL;
2429
- iter->i_pos[i] = 0;
2430
- }
2431
-
2432
- iter->i_level = 0;
2433
-
2434
- /* Note: we don't incref/decref nodes in i_nodes. */
2435
- iter->i_nodes[0] = root;
2436
- }
2437
-
2438
- static hamt_iter_t
2439
- hamt_iterator_bitmap_next(HamtIteratorState *iter,
2440
- PyObject **key, PyObject **val)
2441
- {
2442
- int8_t level = iter->i_level;
2443
-
2444
- HamtNode_Bitmap *node = (HamtNode_Bitmap *)(iter->i_nodes[level]);
2445
- Py_ssize_t pos = iter->i_pos[level];
2446
-
2447
- if (pos + 1 >= Py_SIZE(node)) {
2448
- #ifdef Py_DEBUG
2449
- assert(iter->i_level >= 0);
2450
- iter->i_nodes[iter->i_level] = NULL;
2451
- #endif
2452
- iter->i_level--;
2453
- return hamt_iterator_next(iter, key, val);
2454
- }
2455
-
2456
- if (node->b_array[pos] == NULL) {
2457
- iter->i_pos[level] = pos + 2;
2458
-
2459
- int8_t next_level = level + 1;
2460
- assert(next_level < _Py_HAMT_MAX_TREE_DEPTH);
2461
- iter->i_level = next_level;
2462
- iter->i_pos[next_level] = 0;
2463
- iter->i_nodes[next_level] = (HamtNode *)
2464
- node->b_array[pos + 1];
2465
-
2466
- return hamt_iterator_next(iter, key, val);
2467
- }
2468
-
2469
- *key = node->b_array[pos];
2470
- *val = node->b_array[pos + 1];
2471
- iter->i_pos[level] = pos + 2;
2472
- return I_ITEM;
2473
- }
2474
-
2475
- static hamt_iter_t
2476
- hamt_iterator_collision_next(HamtIteratorState *iter,
2477
- PyObject **key, PyObject **val)
2478
- {
2479
- int8_t level = iter->i_level;
2480
-
2481
- HamtNode_Collision *node = (HamtNode_Collision *)(iter->i_nodes[level]);
2482
- Py_ssize_t pos = iter->i_pos[level];
2483
-
2484
- if (pos + 1 >= Py_SIZE(node)) {
2485
- #ifdef Py_DEBUG
2486
- assert(iter->i_level >= 0);
2487
- iter->i_nodes[iter->i_level] = NULL;
2488
- #endif
2489
- iter->i_level--;
2490
- return hamt_iterator_next(iter, key, val);
2491
- }
2492
-
2493
- *key = node->c_array[pos];
2494
- *val = node->c_array[pos + 1];
2495
- iter->i_pos[level] = pos + 2;
2496
- return I_ITEM;
2497
- }
2498
-
2499
- static hamt_iter_t
2500
- hamt_iterator_array_next(HamtIteratorState *iter,
2501
- PyObject **key, PyObject **val)
2502
- {
2503
- int8_t level = iter->i_level;
2504
-
2505
- HamtNode_Array *node = (HamtNode_Array *)(iter->i_nodes[level]);
2506
- Py_ssize_t pos = iter->i_pos[level];
2507
-
2508
- if (pos >= HAMT_ARRAY_NODE_SIZE) {
2509
- #ifdef Py_DEBUG
2510
- assert(iter->i_level >= 0);
2511
- iter->i_nodes[iter->i_level] = NULL;
2512
- #endif
2513
- iter->i_level--;
2514
- return hamt_iterator_next(iter, key, val);
2515
- }
2516
-
2517
- for (Py_ssize_t i = pos; i < HAMT_ARRAY_NODE_SIZE; i++) {
2518
- if (node->a_array[i] != NULL) {
2519
- iter->i_pos[level] = i + 1;
2520
-
2521
- int8_t next_level = level + 1;
2522
- assert(next_level < _Py_HAMT_MAX_TREE_DEPTH);
2523
- iter->i_pos[next_level] = 0;
2524
- iter->i_nodes[next_level] = node->a_array[i];
2525
- iter->i_level = next_level;
2526
-
2527
- return hamt_iterator_next(iter, key, val);
2528
- }
2529
- }
2530
-
2531
- #ifdef Py_DEBUG
2532
- assert(iter->i_level >= 0);
2533
- iter->i_nodes[iter->i_level] = NULL;
2534
- #endif
2535
-
2536
- iter->i_level--;
2537
- return hamt_iterator_next(iter, key, val);
2538
- }
2539
-
2540
- static hamt_iter_t
2541
- hamt_iterator_next(HamtIteratorState *iter, PyObject **key, PyObject **val)
2542
- {
2543
- if (iter->i_level < 0) {
2544
- return I_END;
2545
- }
2546
-
2547
- assert(iter->i_level < _Py_HAMT_MAX_TREE_DEPTH);
2548
-
2549
- HamtNode *current = iter->i_nodes[iter->i_level];
2550
-
2551
- if (IS_BITMAP_NODE(current)) {
2552
- return hamt_iterator_bitmap_next(iter, key, val);
2553
- }
2554
- else if (IS_ARRAY_NODE(current)) {
2555
- return hamt_iterator_array_next(iter, key, val);
2556
- }
2557
- else {
2558
- assert(IS_COLLISION_NODE(current));
2559
- return hamt_iterator_collision_next(iter, key, val);
2560
- }
2561
- }
2562
-
2563
-
2564
- /////////////////////////////////// HAMT high-level functions
2565
-
2566
-
2567
- HamtObject *
2568
- _Hamt_Assoc(HamtObject *o, PyObject *key, PyObject *val)
2569
- {
2570
- int32_t key_hash;
2571
- int added_leaf = 0;
2572
- HamtNode *new_root;
2573
- HamtObject *new_o;
2574
-
2575
- key_hash = hamt_hash(key);
2576
- if (key_hash == -1) {
2577
- return NULL;
2578
- }
2579
-
2580
- new_root = hamt_node_assoc(
2581
- (HamtNode *)(o->h_root),
2582
- 0, key_hash, key, val, &added_leaf);
2583
- if (new_root == NULL) {
2584
- return NULL;
2585
- }
2586
-
2587
- if (new_root == o->h_root) {
2588
- Py_DECREF(new_root);
2589
- return (HamtObject*)Py_NewRef(o);
2590
- }
2591
-
2592
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)o);
2593
- new_o = hamt_alloc(state);
2594
- if (new_o == NULL) {
2595
- Py_DECREF(new_root);
2596
- return NULL;
2597
- }
2598
-
2599
- new_o->h_root = new_root; /* borrow */
2600
- new_o->h_count = added_leaf ? o->h_count + 1 : o->h_count;
2601
-
2602
- return new_o;
2603
- }
2604
-
2605
- HamtObject *
2606
- _Hamt_Without(HamtObject *o, PyObject *key)
2607
- {
2608
- int32_t key_hash = hamt_hash(key);
2609
- if (key_hash == -1) {
2610
- return NULL;
2611
- }
2612
-
2613
- HamtNode *new_root = NULL;
2614
-
2615
- hamt_without_t res = hamt_node_without(
2616
- (HamtNode *)(o->h_root),
2617
- 0, key_hash, key,
2618
- &new_root);
2619
-
2620
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)o);
2621
-
2622
- switch (res) {
2623
- case W_ERROR:
2624
- return NULL;
2625
- case W_EMPTY: {
2626
- return _Hamt_New(state);
2627
- }
2628
- case W_NOT_FOUND:
2629
- return (HamtObject*)Py_NewRef(o);
2630
- case W_NEWNODE: {
2631
- assert(new_root != NULL);
2632
-
2633
- HamtObject *new_o = hamt_alloc(state);
2634
- if (new_o == NULL) {
2635
- Py_DECREF(new_root);
2636
- return NULL;
2637
- }
2638
-
2639
- new_o->h_root = new_root; /* borrow */
2640
- new_o->h_count = o->h_count - 1;
2641
- assert(new_o->h_count >= 0);
2642
- return new_o;
2643
- }
2644
- default:
2645
- Py_UNREACHABLE();
2646
- }
2647
- }
2648
-
2649
- static hamt_find_t
2650
- hamt_find(HamtObject *o, PyObject *key, PyObject **val)
2651
- {
2652
- if (o->h_count == 0) {
2653
- return F_NOT_FOUND;
2654
- }
2655
-
2656
- int32_t key_hash = hamt_hash(key);
2657
- if (key_hash == -1) {
2658
- return F_ERROR;
2659
- }
2660
-
2661
- return hamt_node_find(o->h_root, 0, key_hash, key, val);
2662
- }
2663
-
2664
-
2665
- int
2666
- _Hamt_Find(HamtObject *o, PyObject *key, PyObject **val)
2667
- {
2668
- hamt_find_t res = hamt_find(o, key, val);
2669
- switch (res) {
2670
- case F_ERROR:
2671
- return -1;
2672
- case F_NOT_FOUND:
2673
- return 0;
2674
- case F_FOUND:
2675
- return 1;
2676
- default:
2677
- Py_UNREACHABLE();
2678
- }
2679
- }
2680
-
2681
-
2682
- int
2683
- _Hamt_Eq(HamtObject *v, HamtObject *w)
2684
- {
2685
- if (v == w) {
2686
- return 1;
2687
- }
2688
-
2689
- if (v->h_count != w->h_count) {
2690
- return 0;
2691
- }
2692
-
2693
- HamtIteratorState iter;
2694
- hamt_iter_t iter_res;
2695
- hamt_find_t find_res;
2696
- PyObject *v_key;
2697
- PyObject *v_val;
2698
- PyObject *w_val;
2699
-
2700
- hamt_iterator_init(&iter, v->h_root);
2701
-
2702
- do {
2703
- iter_res = hamt_iterator_next(&iter, &v_key, &v_val);
2704
- if (iter_res == I_ITEM) {
2705
- find_res = hamt_find(w, v_key, &w_val);
2706
- switch (find_res) {
2707
- case F_ERROR:
2708
- return -1;
2709
-
2710
- case F_NOT_FOUND:
2711
- return 0;
2712
-
2713
- case F_FOUND: {
2714
- int cmp = PyObject_RichCompareBool(v_val, w_val, Py_EQ);
2715
- if (cmp < 0) {
2716
- return -1;
2717
- }
2718
- if (cmp == 0) {
2719
- return 0;
2720
- }
2721
- }
2722
- }
2723
- }
2724
- } while (iter_res != I_END);
2725
-
2726
- return 1;
2727
- }
2728
-
2729
- Py_ssize_t
2730
- _Hamt_Len(HamtObject *o)
2731
- {
2732
- return o->h_count;
2733
- }
2734
-
2735
- static HamtObject *
2736
- hamt_alloc(hamt_module_state *state)
2737
- {
2738
- HamtObject *o;
2739
- o = PyObject_GC_New(HamtObject, state->Hamt_Type);
2740
- if (o == NULL) {
2741
- return NULL;
2742
- }
2743
- o->h_count = 0;
2744
- o->h_root = NULL;
2745
- o->h_weakreflist = NULL;
2746
- PyObject_GC_Track(o);
2747
- return o;
2748
- }
2749
-
2750
- HamtObject *
2751
- _Hamt_New(hamt_module_state *state)
2752
- {
2753
- /* HAMT is an immutable object so we can easily cache an
2754
- empty instance. */
2755
- return (HamtObject*)Py_NewRef(state->empty_hamt);
2756
- }
2757
-
2758
- #ifdef Py_DEBUG
2759
- static PyObject *
2760
- hamt_dump(HamtObject *self)
2761
- {
2762
- _PyUnicodeWriter writer;
2763
-
2764
- _PyUnicodeWriter_Init(&writer);
2765
-
2766
- if (_hamt_dump_format(&writer, "HAMT(len=%zd):\n", self->h_count)) {
2767
- goto error;
2768
- }
2769
-
2770
- if (hamt_node_dump(self->h_root, &writer, 0)) {
2771
- goto error;
2772
- }
2773
-
2774
- return _PyUnicodeWriter_Finish(&writer);
2775
-
2776
- error:
2777
- _PyUnicodeWriter_Dealloc(&writer);
2778
- return NULL;
2779
- }
2780
- #endif /* Py_DEBUG */
2781
-
2782
-
2783
- /////////////////////////////////// Iterators: Shared Iterator Implementation
2784
-
2785
-
2786
- static int
2787
- hamt_baseiter_tp_clear(HamtIterator *it)
2788
- {
2789
- Py_CLEAR(it->hi_obj);
2790
- return 0;
2791
- }
2792
-
2793
- static void
2794
- hamt_baseiter_tp_dealloc(HamtIterator *it)
2795
- {
2796
- PyObject_GC_UnTrack(it);
2797
- (void)hamt_baseiter_tp_clear(it);
2798
- PyObject_GC_Del(it);
2799
- }
2800
-
2801
- static int
2802
- hamt_baseiter_tp_traverse(HamtIterator *it, visitproc visit, void *arg)
2803
- {
2804
- Py_VISIT(it->hi_obj);
2805
- return 0;
2806
- }
2807
-
2808
- static PyObject *
2809
- hamt_baseiter_tp_iternext(HamtIterator *it)
2810
- {
2811
- PyObject *key;
2812
- PyObject *val;
2813
- hamt_iter_t res = hamt_iterator_next(&it->hi_iter, &key, &val);
2814
-
2815
- switch (res) {
2816
- case I_END:
2817
- PyErr_SetNone(PyExc_StopIteration);
2818
- return NULL;
2819
-
2820
- case I_ITEM: {
2821
- return (*(it->hi_yield))(key, val);
2822
- }
2823
-
2824
- default: {
2825
- Py_UNREACHABLE();
2826
- }
2827
- }
2828
- }
2829
-
2830
- static Py_ssize_t
2831
- hamt_baseiter_tp_len(HamtIterator *it)
2832
- {
2833
- return it->hi_obj->h_count;
2834
- }
2835
-
2836
- static PyObject *
2837
- hamt_baseiter_new(PyTypeObject *type, binaryfunc yield, HamtObject *o)
2838
- {
2839
- HamtIterator *it = PyObject_GC_New(HamtIterator, type);
2840
- if (it == NULL) {
2841
- return NULL;
2842
- }
2843
-
2844
- it->hi_obj = (HamtObject*)Py_NewRef(o);
2845
- it->hi_yield = yield;
2846
-
2847
- hamt_iterator_init(&it->hi_iter, o->h_root);
2848
-
2849
- return (PyObject*)it;
2850
- }
2851
-
2852
- #define ITERATOR_TYPE_SHARED_SLOTS \
2853
- .tp_basicsize = sizeof(HamtIterator), \
2854
- .tp_itemsize = 0, \
2855
- .tp_as_mapping = &HamtIterator_as_mapping, \
2856
- .tp_dealloc = (destructor)hamt_baseiter_tp_dealloc, \
2857
- .tp_getattro = PyObject_GenericGetAttr, \
2858
- .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, \
2859
- .tp_traverse = (traverseproc)hamt_baseiter_tp_traverse, \
2860
- .tp_clear = (inquiry)hamt_baseiter_tp_clear, \
2861
- .tp_iter = PyObject_SelfIter, \
2862
- .tp_iternext = (iternextfunc)hamt_baseiter_tp_iternext,
2863
-
2864
-
2865
- /////////////////////////////////// _HamtItems_Type
2866
-
2867
-
2868
- static PyType_Slot HamtItems_Type_slots[] = {
2869
- {Py_tp_dealloc, hamt_baseiter_tp_dealloc},
2870
- {Py_tp_getattro, PyObject_GenericGetAttr},
2871
- {Py_tp_traverse, hamt_baseiter_tp_traverse},
2872
- {Py_tp_clear, hamt_baseiter_tp_clear},
2873
- {Py_tp_iter, PyObject_SelfIter},
2874
- {Py_tp_iternext, hamt_baseiter_tp_iternext},
2875
- {Py_mp_length, hamt_baseiter_tp_len},
2876
- {0, NULL},
2877
- };
2878
-
2879
- static PyType_Spec HamtItems_Type_spec = {
2880
- .name = "hamt.items",
2881
- .basicsize = sizeof(HamtIterator),
2882
- .itemsize = 0,
2883
- .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
2884
- .slots = HamtItems_Type_slots,
2885
- };
2886
-
2887
- static PyObject *
2888
- hamt_iter_yield_items(PyObject *key, PyObject *val)
2889
- {
2890
- return PyTuple_Pack(2, key, val);
2891
- }
2892
-
2893
- PyObject *
2894
- _Hamt_NewIterItems(HamtObject *o)
2895
- {
2896
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)o);
2897
- return hamt_baseiter_new(
2898
- state->HamtItems_Type, hamt_iter_yield_items, o);
2899
- }
2900
-
2901
-
2902
- /////////////////////////////////// _HamtKeys_Type
2903
-
2904
-
2905
- static PyType_Slot HamtKeys_Type_slots[] = {
2906
- {Py_tp_dealloc, hamt_baseiter_tp_dealloc},
2907
- {Py_tp_getattro, PyObject_GenericGetAttr},
2908
- {Py_tp_traverse, hamt_baseiter_tp_traverse},
2909
- {Py_tp_clear, hamt_baseiter_tp_clear},
2910
- {Py_tp_iter, PyObject_SelfIter},
2911
- {Py_tp_iternext, hamt_baseiter_tp_iternext},
2912
- {Py_mp_length, hamt_baseiter_tp_len},
2913
- {0, NULL},
2914
- };
2915
-
2916
- static PyType_Spec HamtKeys_Type_spec = {
2917
- .name = "hamt.keys",
2918
- .basicsize = sizeof(HamtIterator),
2919
- .itemsize = 0,
2920
- .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
2921
- .slots = HamtKeys_Type_slots,
2922
- };
2923
-
2924
- static PyObject *
2925
- hamt_iter_yield_keys(PyObject *key, PyObject *val)
2926
- {
2927
- return Py_NewRef(key);
2928
- }
2929
-
2930
- PyObject *
2931
- _Hamt_NewIterKeys(HamtObject *o)
2932
- {
2933
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)o);
2934
- return hamt_baseiter_new(
2935
- state->HamtKeys_Type, hamt_iter_yield_keys, o);
2936
- }
2937
-
2938
-
2939
- /////////////////////////////////// _HamtValues_Type
2940
-
2941
-
2942
- static PyType_Slot HamtValues_Type_slots[] = {
2943
- {Py_tp_dealloc, hamt_baseiter_tp_dealloc},
2944
- {Py_tp_getattro, PyObject_GenericGetAttr},
2945
- {Py_tp_traverse, hamt_baseiter_tp_traverse},
2946
- {Py_tp_clear, hamt_baseiter_tp_clear},
2947
- {Py_tp_iter, PyObject_SelfIter},
2948
- {Py_tp_iternext, hamt_baseiter_tp_iternext},
2949
- {Py_mp_length, hamt_baseiter_tp_len},
2950
- {0, NULL},
2951
- };
2952
-
2953
- static PyType_Spec HamtValues_Type_spec = {
2954
- .name = "hamt.values",
2955
- .basicsize = sizeof(HamtIterator),
2956
- .itemsize = 0,
2957
- .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
2958
- .slots = HamtValues_Type_slots,
2959
- };
2960
-
2961
- static PyObject *
2962
- hamt_iter_yield_values(PyObject *key, PyObject *val)
2963
- {
2964
- return Py_NewRef(val);
2965
- }
2966
-
2967
- PyObject *
2968
- _Hamt_NewIterValues(HamtObject *o)
2969
- {
2970
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)o);
2971
- return hamt_baseiter_new(
2972
- state->HamtValues_Type, hamt_iter_yield_values, o);
2973
- }
2974
-
2975
-
2976
- /////////////////////////////////// _Hamt_Type
2977
-
2978
-
2979
- #ifdef Py_DEBUG
2980
- static PyObject *
2981
- hamt_dump(HamtObject *self);
2982
- #endif
2983
-
2984
-
2985
- static PyObject *
2986
- hamt_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2987
- {
2988
- hamt_module_state *state = get_hamt_state_from_type(type);
2989
- return (PyObject*)_Hamt_New(state);
2990
- }
2991
-
2992
- static int
2993
- hamt_tp_clear(HamtObject *self)
2994
- {
2995
- Py_CLEAR(self->h_root);
2996
- return 0;
2997
- }
2998
-
2999
-
3000
- static int
3001
- hamt_tp_traverse(HamtObject *self, visitproc visit, void *arg)
3002
- {
3003
- Py_VISIT(self->h_root);
3004
- return 0;
3005
- }
3006
-
3007
- static void
3008
- hamt_tp_dealloc(HamtObject *self)
3009
- {
3010
- hamt_module_state *state = get_hamt_state_from_obj((PyObject*)self);
3011
- if (self == state->empty_hamt) {
3012
- /* The empty one is managed by the module state. */
3013
- #ifdef Py_DEBUG
3014
- _Py_FatalRefcountError("deallocating the empty hamt singleton");
3015
- #else
3016
- return;
3017
- #endif
3018
- }
3019
-
3020
- PyObject_GC_UnTrack(self);
3021
- if (self->h_weakreflist != NULL) {
3022
- PyObject_ClearWeakRefs((PyObject*)self);
3023
- }
3024
- (void)hamt_tp_clear(self);
3025
- Py_TYPE(self)->tp_free(self);
3026
- }
3027
-
3028
-
3029
- static PyObject *
3030
- hamt_tp_richcompare(PyObject *v, PyObject *w, int op)
3031
- {
3032
- if (!Hamt_Check(v) || !Hamt_Check(w) || (op != Py_EQ && op != Py_NE)) {
3033
- Py_RETURN_NOTIMPLEMENTED;
3034
- }
3035
-
3036
- int res = _Hamt_Eq((HamtObject *)v, (HamtObject *)w);
3037
- if (res < 0) {
3038
- return NULL;
3039
- }
3040
-
3041
- if (op == Py_NE) {
3042
- res = !res;
3043
- }
3044
-
3045
- if (res) {
3046
- Py_RETURN_TRUE;
3047
- }
3048
- else {
3049
- Py_RETURN_FALSE;
3050
- }
3051
- }
3052
-
3053
- static int
3054
- hamt_tp_contains(HamtObject *self, PyObject *key)
3055
- {
3056
- PyObject *val;
3057
- return _Hamt_Find(self, key, &val);
3058
- }
3059
-
3060
- static PyObject *
3061
- hamt_tp_subscript(HamtObject *self, PyObject *key)
3062
- {
3063
- PyObject *val;
3064
- hamt_find_t res = hamt_find(self, key, &val);
3065
- switch (res) {
3066
- case F_ERROR:
3067
- return NULL;
3068
- case F_FOUND:
3069
- return Py_NewRef(val);
3070
- case F_NOT_FOUND:
3071
- PyErr_SetObject(PyExc_KeyError, key);
3072
- return NULL;
3073
- default:
3074
- Py_UNREACHABLE();
3075
- }
3076
- }
3077
-
3078
- static Py_ssize_t
3079
- hamt_tp_len(HamtObject *self)
3080
- {
3081
- return _Hamt_Len(self);
3082
- }
3083
-
3084
- static PyObject *
3085
- hamt_tp_iter(HamtObject *self)
3086
- {
3087
- return _Hamt_NewIterKeys(self);
3088
- }
3089
-
3090
- static PyObject *
3091
- hamt_py_set(HamtObject *self, PyObject *args)
3092
- {
3093
- PyObject *key;
3094
- PyObject *val;
3095
-
3096
- if (!PyArg_UnpackTuple(args, "set", 2, 2, &key, &val)) {
3097
- return NULL;
3098
- }
3099
-
3100
- return (PyObject *)_Hamt_Assoc(self, key, val);
3101
- }
3102
-
3103
- static PyObject *
3104
- hamt_py_get(HamtObject *self, PyObject *args)
3105
- {
3106
- PyObject *key;
3107
- PyObject *def = NULL;
3108
-
3109
- if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &def)) {
3110
- return NULL;
3111
- }
3112
-
3113
- PyObject *val = NULL;
3114
- hamt_find_t res = hamt_find(self, key, &val);
3115
- switch (res) {
3116
- case F_ERROR:
3117
- return NULL;
3118
- case F_FOUND:
3119
- return Py_NewRef(val);
3120
- case F_NOT_FOUND:
3121
- if (def == NULL) {
3122
- Py_RETURN_NONE;
3123
- }
3124
- return Py_NewRef(def);
3125
- default:
3126
- Py_UNREACHABLE();
3127
- }
3128
- }
3129
-
3130
- static PyObject *
3131
- hamt_py_delete(HamtObject *self, PyObject *key)
3132
- {
3133
- return (PyObject *)_Hamt_Without(self, key);
3134
- }
3135
-
3136
- static PyObject *
3137
- hamt_py_items(HamtObject *self, PyObject *args)
3138
- {
3139
- return _Hamt_NewIterItems(self);
3140
- }
3141
-
3142
- static PyObject *
3143
- hamt_py_values(HamtObject *self, PyObject *args)
3144
- {
3145
- return _Hamt_NewIterValues(self);
3146
- }
3147
-
3148
- static PyObject *
3149
- hamt_py_keys(HamtObject *self, PyObject *Py_UNUSED(args))
3150
- {
3151
- return _Hamt_NewIterKeys(self);
3152
- }
3153
-
3154
- #ifdef Py_DEBUG
3155
- static PyObject *
3156
- hamt_py_dump(HamtObject *self, PyObject *Py_UNUSED(args))
3157
- {
3158
- return hamt_dump(self);
3159
- }
3160
- #endif
3161
-
3162
-
3163
- static PyMethodDef Hamt_methods[] = {
3164
- {"set", _PyCFunction_CAST(hamt_py_set), METH_VARARGS, NULL},
3165
- {"get", _PyCFunction_CAST(hamt_py_get), METH_VARARGS, NULL},
3166
- {"delete", _PyCFunction_CAST(hamt_py_delete), METH_O, NULL},
3167
- {"items", _PyCFunction_CAST(hamt_py_items), METH_NOARGS, NULL},
3168
- {"keys", _PyCFunction_CAST(hamt_py_keys), METH_NOARGS, NULL},
3169
- {"values", _PyCFunction_CAST(hamt_py_values), METH_NOARGS, NULL},
3170
- #ifdef Py_DEBUG
3171
- {"__dump__", _PyCFunction_CAST(hamt_py_dump), METH_NOARGS, NULL},
3172
- #endif
3173
- {NULL, NULL}
3174
- };
3175
-
3176
- static PyType_Slot Hamt_Type_slots[] = {
3177
- {Py_tp_dealloc, hamt_tp_dealloc},
3178
- {Py_tp_getattro, PyObject_GenericGetAttr},
3179
- {Py_tp_traverse, hamt_tp_traverse},
3180
- {Py_tp_clear, hamt_tp_clear},
3181
- {Py_tp_new, hamt_tp_new},
3182
- {Py_tp_iter, hamt_tp_iter},
3183
- {Py_tp_richcompare, hamt_tp_richcompare},
3184
- {Py_tp_hash, PyObject_HashNotImplemented},
3185
- {Py_tp_methods, Hamt_methods},
3186
- {Py_mp_length, hamt_tp_len},
3187
- {Py_mp_subscript, hamt_tp_subscript},
3188
- {Py_sq_contains, hamt_tp_contains},
3189
- {0, NULL},
3190
- };
3191
-
3192
- static PyType_Spec Hamt_Type_spec = {
3193
- .name = "hamt.hamt",
3194
- .basicsize = sizeof(HamtObject),
3195
- .itemsize = 0,
3196
- .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3197
- .slots = Hamt_Type_slots,
3198
- };
3199
-
3200
-
3201
- /////////////////////////////////// Tree Node Types
3202
-
3203
-
3204
- static PyType_Slot Hamt_ArrayNode_Type_slots[] = {
3205
- {Py_tp_dealloc, hamt_node_array_dealloc},
3206
- {Py_tp_getattro, PyObject_GenericGetAttr},
3207
- {Py_tp_traverse, hamt_node_array_traverse},
3208
- {Py_tp_free, PyObject_GC_Del},
3209
- {Py_tp_hash, PyObject_HashNotImplemented},
3210
- {0, NULL},
3211
- };
3212
-
3213
- static PyType_Spec Hamt_ArrayNode_Type_spec = {
3214
- .name = "hamt.hamt_array_node",
3215
- .basicsize = sizeof(HamtNode_Array),
3216
- .itemsize = 0,
3217
- .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3218
- .slots = Hamt_ArrayNode_Type_slots,
3219
- };
3220
-
3221
- static PyType_Slot Hamt_BitmapNode_Type_slots[] = {
3222
- {Py_tp_dealloc, hamt_node_bitmap_dealloc},
3223
- {Py_tp_getattro, PyObject_GenericGetAttr},
3224
- {Py_tp_traverse, hamt_node_bitmap_traverse},
3225
- {Py_tp_free, PyObject_GC_Del},
3226
- {Py_tp_hash, PyObject_HashNotImplemented},
3227
- {0, NULL},
3228
- };
3229
-
3230
- static PyType_Spec Hamt_BitmapNode_Type_spec = {
3231
- .name = "hamt.hamt_bitmap_node",
3232
- .basicsize = sizeof(HamtNode_Bitmap) - sizeof(PyObject *),
3233
- .itemsize = sizeof(PyObject *),
3234
- .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3235
- .slots = Hamt_BitmapNode_Type_slots,
3236
- };
3237
-
3238
- static PyType_Slot Hamt_CollisionNode_Type_slots[] = {
3239
- {Py_tp_dealloc, hamt_node_collision_dealloc},
3240
- {Py_tp_getattro, PyObject_GenericGetAttr},
3241
- {Py_tp_traverse, hamt_node_collision_traverse},
3242
- {Py_tp_free, PyObject_GC_Del},
3243
- {Py_tp_hash, PyObject_HashNotImplemented},
3244
- {0, NULL},
3245
- };
3246
-
3247
- static PyType_Spec Hamt_CollisionNode_Type_spec = {
3248
- .name = "hamt.hamt_collision_node",
3249
- .basicsize = sizeof(HamtNode_Collision) - sizeof(PyObject *),
3250
- .itemsize = sizeof(PyObject *),
3251
- .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3252
- .slots = Hamt_CollisionNode_Type_slots,
3253
- };
3254
-
3255
- ////
3256
-
3257
- static PyObject *
3258
- py_hamt_new(PyObject *self, PyObject *args)
3259
- {
3260
- if (!PyArg_ParseTuple(args, "")) {
3261
- return NULL;
3262
- }
3263
-
3264
- hamt_module_state *state = get_hamt_module_state(self);
3265
- HamtObject *hamt = _Hamt_New(state);
3266
- if (!hamt) {
3267
- return NULL;
3268
- }
3269
-
3270
- return (PyObject *)hamt;
3271
- }
3272
-
3273
- static PyObject *
3274
- py_hamt_assoc(PyObject *self, PyObject *args)
3275
- {
3276
- PyObject *hamt_obj;
3277
- PyObject *key;
3278
- PyObject *val;
3279
-
3280
- if (!PyArg_ParseTuple(args, "OOO", &hamt_obj, &key, &val)) {
3281
- return NULL;
3282
- }
3283
-
3284
- if (!Hamt_Check(hamt_obj)) {
3285
- PyErr_SetString(PyExc_TypeError, "first argument must be a HAMT object");
3286
- return NULL;
3287
- }
3288
-
3289
- HamtObject *result = _Hamt_Assoc((HamtObject *)hamt_obj, key, val);
3290
- if (!result) {
3291
- return NULL;
3292
- }
3293
-
3294
- return (PyObject *)result;
3295
- }
3296
-
3297
- static PyObject *
3298
- py_hamt_without(PyObject *self, PyObject *args)
3299
- {
3300
- PyObject *hamt_obj;
3301
- PyObject *key;
3302
-
3303
- if (!PyArg_ParseTuple(args, "OO", &hamt_obj, &key)) {
3304
- return NULL;
3305
- }
3306
-
3307
- if (!Hamt_Check(hamt_obj)) {
3308
- PyErr_SetString(PyExc_TypeError, "first argument must be a HAMT object");
3309
- return NULL;
3310
- }
3311
-
3312
- HamtObject *result = _Hamt_Without((HamtObject *)hamt_obj, key);
3313
- if (!result) {
3314
- return NULL;
3315
- }
3316
-
3317
- return (PyObject *)result;
3318
- }
3319
-
3320
- static PyObject *
3321
- py_hamt_find(PyObject *self, PyObject *args)
3322
- {
3323
- PyObject *hamt_obj;
3324
- PyObject *key;
3325
-
3326
- if (!PyArg_ParseTuple(args, "OO", &hamt_obj, &key)) {
3327
- return NULL;
3328
- }
3329
-
3330
- if (!Hamt_Check(hamt_obj)) {
3331
- PyErr_SetString(PyExc_TypeError, "first argument must be a HAMT object");
3332
- return NULL;
3333
- }
3334
-
3335
- PyObject *val = NULL;
3336
- int result = _Hamt_Find((HamtObject *)hamt_obj, key, &val);
3337
-
3338
- if (result == -1) {
3339
- return NULL;
3340
- }
3341
-
3342
- if (result == 0) {
3343
- Py_RETURN_NONE;
3344
- }
3345
-
3346
- // result == 1, key found, val is a borrowed reference
3347
- Py_INCREF(val);
3348
- return val;
3349
- }
3350
-
3351
- static PyObject *
3352
- py_hamt_eq(PyObject *self, PyObject *args)
3353
- {
3354
- PyObject *v_obj;
3355
- PyObject *w_obj;
3356
-
3357
- if (!PyArg_ParseTuple(args, "OO", &v_obj, &w_obj)) {
3358
- return NULL;
3359
- }
3360
-
3361
- if (!Hamt_Check(v_obj)) {
3362
- PyErr_SetString(PyExc_TypeError, "first argument must be a HAMT object");
3363
- return NULL;
3364
- }
3365
-
3366
- if (!Hamt_Check(w_obj)) {
3367
- PyErr_SetString(PyExc_TypeError, "second argument must be a HAMT object");
3368
- return NULL;
3369
- }
3370
-
3371
- int result = _Hamt_Eq((HamtObject *)v_obj, (HamtObject *)w_obj);
3372
-
3373
- if (result == -1) {
3374
- return NULL;
3375
- }
3376
-
3377
- if (result == 0) {
3378
- Py_RETURN_FALSE;
3379
- }
3380
-
3381
- Py_RETURN_TRUE;
3382
- }
3383
-
3384
- static PyObject *
3385
- py_hamt_len(PyObject *self, PyObject *args)
3386
- {
3387
- PyObject *hamt_obj;
3388
-
3389
- if (!PyArg_ParseTuple(args, "O", &hamt_obj)) {
3390
- return NULL;
3391
- }
3392
-
3393
- if (!Hamt_Check(hamt_obj)) {
3394
- PyErr_SetString(PyExc_TypeError, "argument must be a HAMT object");
3395
- return NULL;
3396
- }
3397
-
3398
- Py_ssize_t len = _Hamt_Len((HamtObject *)hamt_obj);
3399
- return PyLong_FromSsize_t(len);
3400
- }
3401
-
3402
- static PyObject *
3403
- py_hamt_iter_keys(PyObject *self, PyObject *args)
3404
- {
3405
- PyObject *hamt_obj;
3406
-
3407
- if (!PyArg_ParseTuple(args, "O", &hamt_obj)) {
3408
- return NULL;
3409
- }
3410
-
3411
- if (!Hamt_Check(hamt_obj)) {
3412
- PyErr_SetString(PyExc_TypeError, "argument must be a HAMT object");
3413
- return NULL;
3414
- }
3415
-
3416
- PyObject *iter = _Hamt_NewIterKeys((HamtObject *)hamt_obj);
3417
- if (!iter) {
3418
- return NULL;
3419
- }
3420
-
3421
- return iter;
3422
- }
3423
-
3424
- static PyObject *
3425
- py_hamt_iter_values(PyObject *self, PyObject *args)
3426
- {
3427
- PyObject *hamt_obj;
3428
-
3429
- if (!PyArg_ParseTuple(args, "O", &hamt_obj)) {
3430
- return NULL;
3431
- }
3432
-
3433
- if (!Hamt_Check(hamt_obj)) {
3434
- PyErr_SetString(PyExc_TypeError, "argument must be a HAMT object");
3435
- return NULL;
3436
- }
3437
-
3438
- PyObject *iter = _Hamt_NewIterValues((HamtObject *)hamt_obj);
3439
- if (!iter) {
3440
- return NULL;
3441
- }
3442
-
3443
- return iter;
3444
- }
3445
-
3446
- static PyObject *
3447
- py_hamt_iter_items(PyObject *self, PyObject *args)
3448
- {
3449
- PyObject *hamt_obj;
3450
-
3451
- if (!PyArg_ParseTuple(args, "O", &hamt_obj)) {
3452
- return NULL;
3453
- }
3454
-
3455
- if (!Hamt_Check(hamt_obj)) {
3456
- PyErr_SetString(PyExc_TypeError, "argument must be a HAMT object");
3457
- return NULL;
3458
- }
3459
-
3460
- PyObject *iter = _Hamt_NewIterItems((HamtObject *)hamt_obj);
3461
- if (!iter) {
3462
- return NULL;
3463
- }
3464
-
3465
- return iter;
3466
- }
3467
-
3468
- //
3469
-
3470
- static int _hamt_module_exec(PyObject *module)
3471
- {
3472
- hamt_module_state *state = get_hamt_module_state(module);
3473
-
3474
- /* Initialize type objects */
3475
- state->Hamt_Type = (PyTypeObject *)PyType_FromModuleAndSpec(module, &Hamt_Type_spec, NULL);
3476
- if (state->Hamt_Type == NULL) {
3477
- return -1;
3478
- }
3479
- if (PyModule_AddType(module, state->Hamt_Type) < 0) {
3480
- return -1;
3481
- }
3482
-
3483
- state->HamtItems_Type = (PyTypeObject *)PyType_FromModuleAndSpec(module, &HamtItems_Type_spec, NULL);
3484
- if (state->HamtItems_Type == NULL) {
3485
- return -1;
3486
- }
3487
-
3488
- state->HamtKeys_Type = (PyTypeObject *)PyType_FromModuleAndSpec(module, &HamtKeys_Type_spec, NULL);
3489
- if (state->HamtKeys_Type == NULL) {
3490
- return -1;
3491
- }
3492
-
3493
- state->HamtValues_Type = (PyTypeObject *)PyType_FromModuleAndSpec(module, &HamtValues_Type_spec, NULL);
3494
- if (state->HamtValues_Type == NULL) {
3495
- return -1;
3496
- }
3497
-
3498
- state->Hamt_ArrayNode_Type = (PyTypeObject *)PyType_FromModuleAndSpec(module, &Hamt_ArrayNode_Type_spec, NULL);
3499
- if (state->Hamt_ArrayNode_Type == NULL) {
3500
- return -1;
3501
- }
3502
-
3503
- state->Hamt_BitmapNode_Type = (PyTypeObject *)PyType_FromModuleAndSpec(module, &Hamt_BitmapNode_Type_spec, NULL);
3504
- if (state->Hamt_BitmapNode_Type == NULL) {
3505
- return -1;
3506
- }
3507
-
3508
- state->Hamt_CollisionNode_Type = (PyTypeObject *)PyType_FromModuleAndSpec(module, &Hamt_CollisionNode_Type_spec, NULL);
3509
- if (state->Hamt_CollisionNode_Type == NULL) {
3510
- return -1;
3511
- }
3512
-
3513
- /* Initialize singleton objects */
3514
-
3515
- /* Create empty bitmap node */
3516
- state->empty_bitmap_node = PyObject_GC_New(HamtNode_Bitmap, state->Hamt_BitmapNode_Type);
3517
- if (state->empty_bitmap_node == NULL) {
3518
- return -1;
3519
- }
3520
- Py_SET_SIZE(state->empty_bitmap_node, 0);
3521
- state->empty_bitmap_node->b_bitmap = 0;
3522
- PyObject_GC_Track(state->empty_bitmap_node);
3523
-
3524
- /* Create empty HAMT object */
3525
- state->empty_hamt = PyObject_GC_New(HamtObject, state->Hamt_Type);
3526
- if (state->empty_hamt == NULL) {
3527
- return -1;
3528
- }
3529
- state->empty_hamt->h_root = (HamtNode *)Py_NewRef(state->empty_bitmap_node);
3530
- state->empty_hamt->h_weakreflist = NULL;
3531
- state->empty_hamt->h_count = 0;
3532
- PyObject_GC_Track(state->empty_hamt);
3533
-
3534
- return 0;
3535
- }
3536
-
3537
- static int _hamt_module_traverse(PyObject *module, visitproc visit, void *arg)
3538
- {
3539
- hamt_module_state *state = get_hamt_module_state(module);
3540
-
3541
- /* Visit type objects */
3542
- Py_VISIT(state->Hamt_Type);
3543
- Py_VISIT(state->HamtItems_Type);
3544
- Py_VISIT(state->HamtKeys_Type);
3545
- Py_VISIT(state->HamtValues_Type);
3546
- Py_VISIT(state->Hamt_ArrayNode_Type);
3547
- Py_VISIT(state->Hamt_BitmapNode_Type);
3548
- Py_VISIT(state->Hamt_CollisionNode_Type);
3549
-
3550
- /* Visit singleton objects */
3551
- Py_VISIT(state->empty_hamt);
3552
- Py_VISIT(state->empty_bitmap_node);
3553
-
3554
- return 0;
3555
- }
3556
-
3557
- static int _hamt_module_clear(PyObject *module)
3558
- {
3559
- hamt_module_state *state = get_hamt_module_state(module);
3560
-
3561
- /* Clear type objects */
3562
- Py_CLEAR(state->Hamt_Type);
3563
- Py_CLEAR(state->HamtItems_Type);
3564
- Py_CLEAR(state->HamtKeys_Type);
3565
- Py_CLEAR(state->HamtValues_Type);
3566
- Py_CLEAR(state->Hamt_ArrayNode_Type);
3567
- Py_CLEAR(state->Hamt_BitmapNode_Type);
3568
- Py_CLEAR(state->Hamt_CollisionNode_Type);
3569
-
3570
- /* Clear singleton objects */
3571
- Py_CLEAR(state->empty_hamt);
3572
- Py_CLEAR(state->empty_bitmap_node);
3573
-
3574
- return 0;
3575
- }
3576
-
3577
- static void _hamt_module_free(void *module)
3578
- {
3579
- _hamt_module_clear((PyObject *)module);
3580
- }
3581
-
3582
- //
3583
-
3584
- PyDoc_STRVAR(hamt_doc, _MODULE_NAME);
3585
-
3586
- static PyMethodDef hamt_methods[] = {
3587
- {"new", py_hamt_new, METH_VARARGS, "Create a new HAMT immutable mapping"},
3588
- {"assoc", py_hamt_assoc, METH_VARARGS, "Return a new HAMT with an additional key/value pair"},
3589
- {"without", py_hamt_without, METH_VARARGS, "Return a new HAMT without the specified key"},
3590
- {"find", py_hamt_find, METH_VARARGS, "Find a key in the HAMT, return value or None"},
3591
- {"eq", py_hamt_eq, METH_VARARGS, "Check if two HAMTs are equal"},
3592
- {"len", py_hamt_len, METH_VARARGS, "Return the number of items in the HAMT"},
3593
- {"iter_keys", py_hamt_iter_keys, METH_VARARGS, "Return a keys iterator over the HAMT"},
3594
- {"iter_values", py_hamt_iter_values, METH_VARARGS, "Return a values iterator over the HAMT"},
3595
- {"iter_items", py_hamt_iter_items, METH_VARARGS, "Return an items iterator over the HAMT"},
3596
- {NULL, NULL, 0, NULL}
3597
- };
3598
-
3599
- static struct PyModuleDef_Slot hamt_slots[] = {
3600
- {Py_mod_exec, (void *) _hamt_module_exec},
3601
- {Py_mod_gil, Py_MOD_GIL_NOT_USED},
3602
- {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
3603
- {0, NULL}
3604
- };
3605
-
3606
- static struct PyModuleDef hamt_module = {
3607
- .m_base = PyModuleDef_HEAD_INIT,
3608
- .m_name = _MODULE_NAME,
3609
- .m_doc = hamt_doc,
3610
- .m_size = sizeof(hamt_module_state),
3611
- .m_methods = hamt_methods,
3612
- .m_slots = hamt_slots,
3613
- .m_traverse = _hamt_module_traverse,
3614
- .m_clear = _hamt_module_clear,
3615
- .m_free = _hamt_module_free,
3616
- };
3617
-
3618
- PyMODINIT_FUNC PyInit__hamt(void)
3619
- {
3620
- return PyModuleDef_Init(&hamt_module);
3621
- }