You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2997 lines
79 KiB

  1. #include "Python.h"
  2. #include "pycore_hamt.h"
  3. #include "pycore_object.h"
  4. #include "pycore_pystate.h"
  5. #include "structmember.h"
  6. /*
  7. This file provides an implementation of an immutable mapping using the
  8. Hash Array Mapped Trie (or HAMT) datastructure.
  9. This design allows to have:
  10. 1. Efficient copy: immutable mappings can be copied by reference,
  11. making it an O(1) operation.
  12. 2. Efficient mutations: due to structural sharing, only a portion of
  13. the trie needs to be copied when the collection is mutated. The
  14. cost of set/delete operations is O(log N).
  15. 3. Efficient lookups: O(log N).
  16. (where N is number of key/value items in the immutable mapping.)
  17. HAMT
  18. ====
  19. The core idea of HAMT is that the shape of the trie is encoded into the
  20. hashes of keys.
  21. Say we want to store a K/V pair in our mapping. First, we calculate the
  22. hash of K, let's say it's 19830128, or in binary:
  23. 0b1001011101001010101110000 = 19830128
  24. Now let's partition this bit representation of the hash into blocks of
  25. 5 bits each:
  26. 0b00_00000_10010_11101_00101_01011_10000 = 19830128
  27. (6) (5) (4) (3) (2) (1)
  28. Each block of 5 bits represents a number between 0 and 31. So if we have
  29. a tree that consists of nodes, each of which is an array of 32 pointers,
  30. those 5-bit blocks will encode a position on a single tree level.
  31. For example, storing the key K with hash 19830128, results in the following
  32. tree structure:
  33. (array of 32 pointers)
  34. +---+ -- +----+----+----+ -- +----+
  35. root node | 0 | .. | 15 | 16 | 17 | .. | 31 | 0b10000 = 16 (1)
  36. (level 1) +---+ -- +----+----+----+ -- +----+
  37. |
  38. +---+ -- +----+----+----+ -- +----+
  39. a 2nd level node | 0 | .. | 10 | 11 | 12 | .. | 31 | 0b01011 = 11 (2)
  40. +---+ -- +----+----+----+ -- +----+
  41. |
  42. +---+ -- +----+----+----+ -- +----+
  43. a 3rd level node | 0 | .. | 04 | 05 | 06 | .. | 31 | 0b00101 = 5 (3)
  44. +---+ -- +----+----+----+ -- +----+
  45. |
  46. +---+ -- +----+----+----+----+
  47. a 4th level node | 0 | .. | 04 | 29 | 30 | 31 | 0b11101 = 29 (4)
  48. +---+ -- +----+----+----+----+
  49. |
  50. +---+ -- +----+----+----+ -- +----+
  51. a 5th level node | 0 | .. | 17 | 18 | 19 | .. | 31 | 0b10010 = 18 (5)
  52. +---+ -- +----+----+----+ -- +----+
  53. |
  54. +--------------+
  55. |
  56. +---+ -- +----+----+----+ -- +----+
  57. a 6th level node | 0 | .. | 15 | 16 | 17 | .. | 31 | 0b00000 = 0 (6)
  58. +---+ -- +----+----+----+ -- +----+
  59. |
  60. V -- our value (or collision)
  61. To rehash: for a K/V pair, the hash of K encodes where in the tree V will
  62. be stored.
  63. To optimize memory footprint and handle hash collisions, our implementation
  64. uses three different types of nodes:
  65. * A Bitmap node;
  66. * An Array node;
  67. * A Collision node.
  68. Because we implement an immutable dictionary, our nodes are also
  69. immutable. Therefore, when we need to modify a node, we copy it, and
  70. do that modification to the copy.
  71. Array Nodes
  72. -----------
  73. These nodes are very simple. Essentially they are arrays of 32 pointers
  74. we used to illustrate the high-level idea in the previous section.
  75. We use Array nodes only when we need to store more than 16 pointers
  76. in a single node.
  77. Array nodes do not store key objects or value objects. They are used
  78. only as an indirection level - their pointers point to other nodes in
  79. the tree.
  80. Bitmap Node
  81. -----------
  82. Allocating a new 32-pointers array for every node of our tree would be
  83. very expensive. Unless we store millions of keys, most of tree nodes would
  84. be very sparse.
  85. When we have less than 16 elements in a node, we don't want to use the
  86. Array node, that would mean that we waste a lot of memory. Instead,
  87. we can use bitmap compression and can have just as many pointers
  88. as we need!
  89. Bitmap nodes consist of two fields:
  90. 1. An array of pointers. If a Bitmap node holds N elements, the
  91. array will be of N pointers.
  92. 2. A 32bit integer -- a bitmap field. If an N-th bit is set in the
  93. bitmap, it means that the node has an N-th element.
  94. For example, say we need to store a 3 elements sparse array:
  95. +---+ -- +---+ -- +----+ -- +----+
  96. | 0 | .. | 4 | .. | 11 | .. | 17 |
  97. +---+ -- +---+ -- +----+ -- +----+
  98. | | |
  99. o1 o2 o3
  100. We allocate a three-pointer Bitmap node. Its bitmap field will be
  101. then set to:
  102. 0b_00100_00010_00000_10000 == (1 << 17) | (1 << 11) | (1 << 4)
  103. To check if our Bitmap node has an I-th element we can do:
  104. bitmap & (1 << I)
  105. And here's a formula to calculate a position in our pointer array
  106. which would correspond to an I-th element:
  107. popcount(bitmap & ((1 << I) - 1))
  108. Let's break it down:
  109. * `popcount` is a function that returns a number of bits set to 1;
  110. * `((1 << I) - 1)` is a mask to filter the bitmask to contain bits
  111. set to the *right* of our bit.
  112. So for our 17, 11, and 4 indexes:
  113. * bitmap & ((1 << 17) - 1) == 0b100000010000 => 2 bits are set => index is 2.
  114. * bitmap & ((1 << 11) - 1) == 0b10000 => 1 bit is set => index is 1.
  115. * bitmap & ((1 << 4) - 1) == 0b0 => 0 bits are set => index is 0.
  116. To conclude: Bitmap nodes are just like Array nodes -- they can store
  117. a number of pointers, but use bitmap compression to eliminate unused
  118. pointers.
  119. Bitmap nodes have two pointers for each item:
  120. +----+----+----+----+ -- +----+----+
  121. | k1 | v1 | k2 | v2 | .. | kN | vN |
  122. +----+----+----+----+ -- +----+----+
  123. When kI == NULL, vI points to another tree level.
  124. When kI != NULL, the actual key object is stored in kI, and its
  125. value is stored in vI.
  126. Collision Nodes
  127. ---------------
  128. Collision nodes are simple arrays of pointers -- two pointers per
  129. key/value. When there's a hash collision, say for k1/v1 and k2/v2
  130. we have `hash(k1)==hash(k2)`. Then our collision node will be:
  131. +----+----+----+----+
  132. | k1 | v1 | k2 | v2 |
  133. +----+----+----+----+
  134. Tree Structure
  135. --------------
  136. All nodes are PyObjects.
  137. The `PyHamtObject` object has a pointer to the root node (h_root),
  138. and has a length field (h_count).
  139. High-level functions accept a PyHamtObject object and dispatch to
  140. lower-level functions depending on what kind of node h_root points to.
  141. Operations
  142. ==========
  143. There are three fundamental operations on an immutable dictionary:
  144. 1. "o.assoc(k, v)" will return a new immutable dictionary, that will be
  145. a copy of "o", but with the "k/v" item set.
  146. Functions in this file:
  147. hamt_node_assoc, hamt_node_bitmap_assoc,
  148. hamt_node_array_assoc, hamt_node_collision_assoc
  149. `hamt_node_assoc` function accepts a node object, and calls
  150. other functions depending on its actual type.
  151. 2. "o.find(k)" will lookup key "k" in "o".
  152. Functions:
  153. hamt_node_find, hamt_node_bitmap_find,
  154. hamt_node_array_find, hamt_node_collision_find
  155. 3. "o.without(k)" will return a new immutable dictionary, that will be
  156. a copy of "o", buth without the "k" key.
  157. Functions:
  158. hamt_node_without, hamt_node_bitmap_without,
  159. hamt_node_array_without, hamt_node_collision_without
  160. Further Reading
  161. ===============
  162. 1. http://blog.higher-order.net/2009/09/08/understanding-clojures-persistenthashmap-deftwice.html
  163. 2. http://blog.higher-order.net/2010/08/16/assoc-and-clojures-persistenthashmap-part-ii.html
  164. 3. Clojure's PersistentHashMap implementation:
  165. https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/PersistentHashMap.java
  166. Debug
  167. =====
  168. The HAMT datatype is accessible for testing purposes under the
  169. `_testcapi` module:
  170. >>> from _testcapi import hamt
  171. >>> h = hamt()
  172. >>> h2 = h.set('a', 2)
  173. >>> h3 = h2.set('b', 3)
  174. >>> list(h3)
  175. ['a', 'b']
  176. When CPython is built in debug mode, a '__dump__()' method is available
  177. to introspect the tree:
  178. >>> print(h3.__dump__())
  179. HAMT(len=2):
  180. BitmapNode(size=4 count=2 bitmap=0b110 id=0x10eb9d9e8):
  181. 'a': 2
  182. 'b': 3
  183. */
  184. #define IS_ARRAY_NODE(node) (Py_TYPE(node) == &_PyHamt_ArrayNode_Type)
  185. #define IS_BITMAP_NODE(node) (Py_TYPE(node) == &_PyHamt_BitmapNode_Type)
  186. #define IS_COLLISION_NODE(node) (Py_TYPE(node) == &_PyHamt_CollisionNode_Type)
  187. /* Return type for 'find' (lookup a key) functions.
  188. * F_ERROR - an error occurred;
  189. * F_NOT_FOUND - the key was not found;
  190. * F_FOUND - the key was found.
  191. */
  192. typedef enum {F_ERROR, F_NOT_FOUND, F_FOUND} hamt_find_t;
  193. /* Return type for 'without' (delete a key) functions.
  194. * W_ERROR - an error occurred;
  195. * W_NOT_FOUND - the key was not found: there's nothing to delete;
  196. * W_EMPTY - the key was found: the node/tree would be empty
  197. if the key is deleted;
  198. * W_NEWNODE - the key was found: a new node/tree is returned
  199. without that key.
  200. */
  201. typedef enum {W_ERROR, W_NOT_FOUND, W_EMPTY, W_NEWNODE} hamt_without_t;
  202. /* Low-level iterator protocol type.
  203. * I_ITEM - a new item has been yielded;
  204. * I_END - the whole tree was visited (similar to StopIteration).
  205. */
  206. typedef enum {I_ITEM, I_END} hamt_iter_t;
  207. #define HAMT_ARRAY_NODE_SIZE 32
  208. typedef struct {
  209. PyObject_HEAD
  210. PyHamtNode *a_array[HAMT_ARRAY_NODE_SIZE];
  211. Py_ssize_t a_count;
  212. } PyHamtNode_Array;
  213. typedef struct {
  214. PyObject_VAR_HEAD
  215. uint32_t b_bitmap;
  216. PyObject *b_array[1];
  217. } PyHamtNode_Bitmap;
  218. typedef struct {
  219. PyObject_VAR_HEAD
  220. int32_t c_hash;
  221. PyObject *c_array[1];
  222. } PyHamtNode_Collision;
  223. static PyHamtNode_Bitmap *_empty_bitmap_node;
  224. static PyHamtObject *_empty_hamt;
  225. static PyHamtObject *
  226. hamt_alloc(void);
  227. static PyHamtNode *
  228. hamt_node_assoc(PyHamtNode *node,
  229. uint32_t shift, int32_t hash,
  230. PyObject *key, PyObject *val, int* added_leaf);
  231. static hamt_without_t
  232. hamt_node_without(PyHamtNode *node,
  233. uint32_t shift, int32_t hash,
  234. PyObject *key,
  235. PyHamtNode **new_node);
  236. static hamt_find_t
  237. hamt_node_find(PyHamtNode *node,
  238. uint32_t shift, int32_t hash,
  239. PyObject *key, PyObject **val);
  240. #ifdef Py_DEBUG
  241. static int
  242. hamt_node_dump(PyHamtNode *node,
  243. _PyUnicodeWriter *writer, int level);
  244. #endif
  245. static PyHamtNode *
  246. hamt_node_array_new(Py_ssize_t);
  247. static PyHamtNode *
  248. hamt_node_collision_new(int32_t hash, Py_ssize_t size);
  249. static inline Py_ssize_t
  250. hamt_node_collision_count(PyHamtNode_Collision *node);
  251. #ifdef Py_DEBUG
  252. static void
  253. _hamt_node_array_validate(void *obj_raw)
  254. {
  255. PyObject *obj = _PyObject_CAST(obj_raw);
  256. assert(IS_ARRAY_NODE(obj));
  257. PyHamtNode_Array *node = (PyHamtNode_Array*)obj;
  258. Py_ssize_t i = 0, count = 0;
  259. for (; i < HAMT_ARRAY_NODE_SIZE; i++) {
  260. if (node->a_array[i] != NULL) {
  261. count++;
  262. }
  263. }
  264. assert(count == node->a_count);
  265. }
  266. #define VALIDATE_ARRAY_NODE(NODE) \
  267. do { _hamt_node_array_validate(NODE); } while (0);
  268. #else
  269. #define VALIDATE_ARRAY_NODE(NODE)
  270. #endif
  271. /* Returns -1 on error */
  272. static inline int32_t
  273. hamt_hash(PyObject *o)
  274. {
  275. Py_hash_t hash = PyObject_Hash(o);
  276. #if SIZEOF_PY_HASH_T <= 4
  277. return hash;
  278. #else
  279. if (hash == -1) {
  280. /* exception */
  281. return -1;
  282. }
  283. /* While it's suboptimal to reduce Python's 64 bit hash to
  284. 32 bits via XOR, it seems that the resulting hash function
  285. is good enough (this is also how Long type is hashed in Java.)
  286. Storing 10, 100, 1000 Python strings results in a relatively
  287. shallow and uniform tree structure.
  288. Please don't change this hashing algorithm, as there are many
  289. tests that test some exact tree shape to cover all code paths.
  290. */
  291. int32_t xored = (int32_t)(hash & 0xffffffffl) ^ (int32_t)(hash >> 32);
  292. return xored == -1 ? -2 : xored;
  293. #endif
  294. }
  295. static inline uint32_t
  296. hamt_mask(int32_t hash, uint32_t shift)
  297. {
  298. return (((uint32_t)hash >> shift) & 0x01f);
  299. }
  300. static inline uint32_t
  301. hamt_bitpos(int32_t hash, uint32_t shift)
  302. {
  303. return (uint32_t)1 << hamt_mask(hash, shift);
  304. }
  305. static inline uint32_t
  306. hamt_bitcount(uint32_t i)
  307. {
  308. /* We could use native popcount instruction but that would
  309. require to either add configure flags to enable SSE4.2
  310. support or to detect it dynamically. Otherwise, we have
  311. a risk of CPython not working properly on older hardware.
  312. In practice, there's no observable difference in
  313. performance between using a popcount instruction or the
  314. following fallback code.
  315. The algorithm is copied from:
  316. https://graphics.stanford.edu/~seander/bithacks.html
  317. */
  318. i = i - ((i >> 1) & 0x55555555);
  319. i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
  320. return (((i + (i >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24;
  321. }
  322. static inline uint32_t
  323. hamt_bitindex(uint32_t bitmap, uint32_t bit)
  324. {
  325. return hamt_bitcount(bitmap & (bit - 1));
  326. }
  327. /////////////////////////////////// Dump Helpers
  328. #ifdef Py_DEBUG
  329. static int
  330. _hamt_dump_ident(_PyUnicodeWriter *writer, int level)
  331. {
  332. /* Write `' ' * level` to the `writer` */
  333. PyObject *str = NULL;
  334. PyObject *num = NULL;
  335. PyObject *res = NULL;
  336. int ret = -1;
  337. str = PyUnicode_FromString(" ");
  338. if (str == NULL) {
  339. goto error;
  340. }
  341. num = PyLong_FromLong((long)level);
  342. if (num == NULL) {
  343. goto error;
  344. }
  345. res = PyNumber_Multiply(str, num);
  346. if (res == NULL) {
  347. goto error;
  348. }
  349. ret = _PyUnicodeWriter_WriteStr(writer, res);
  350. error:
  351. Py_XDECREF(res);
  352. Py_XDECREF(str);
  353. Py_XDECREF(num);
  354. return ret;
  355. }
  356. static int
  357. _hamt_dump_format(_PyUnicodeWriter *writer, const char *format, ...)
  358. {
  359. /* A convenient helper combining _PyUnicodeWriter_WriteStr and
  360. PyUnicode_FromFormatV.
  361. */
  362. PyObject* msg;
  363. int ret;
  364. va_list vargs;
  365. #ifdef HAVE_STDARG_PROTOTYPES
  366. va_start(vargs, format);
  367. #else
  368. va_start(vargs);
  369. #endif
  370. msg = PyUnicode_FromFormatV(format, vargs);
  371. va_end(vargs);
  372. if (msg == NULL) {
  373. return -1;
  374. }
  375. ret = _PyUnicodeWriter_WriteStr(writer, msg);
  376. Py_DECREF(msg);
  377. return ret;
  378. }
  379. #endif /* Py_DEBUG */
  380. /////////////////////////////////// Bitmap Node
  381. static PyHamtNode *
  382. hamt_node_bitmap_new(Py_ssize_t size)
  383. {
  384. /* Create a new bitmap node of size 'size' */
  385. PyHamtNode_Bitmap *node;
  386. Py_ssize_t i;
  387. assert(size >= 0);
  388. assert(size % 2 == 0);
  389. if (size == 0 && _empty_bitmap_node != NULL) {
  390. Py_INCREF(_empty_bitmap_node);
  391. return (PyHamtNode *)_empty_bitmap_node;
  392. }
  393. /* No freelist; allocate a new bitmap node */
  394. node = PyObject_GC_NewVar(
  395. PyHamtNode_Bitmap, &_PyHamt_BitmapNode_Type, size);
  396. if (node == NULL) {
  397. return NULL;
  398. }
  399. Py_SIZE(node) = size;
  400. for (i = 0; i < size; i++) {
  401. node->b_array[i] = NULL;
  402. }
  403. node->b_bitmap = 0;
  404. _PyObject_GC_TRACK(node);
  405. if (size == 0 && _empty_bitmap_node == NULL) {
  406. /* Since bitmap nodes are immutable, we can cache the instance
  407. for size=0 and reuse it whenever we need an empty bitmap node.
  408. */
  409. _empty_bitmap_node = node;
  410. Py_INCREF(_empty_bitmap_node);
  411. }
  412. return (PyHamtNode *)node;
  413. }
  414. static inline Py_ssize_t
  415. hamt_node_bitmap_count(PyHamtNode_Bitmap *node)
  416. {
  417. return Py_SIZE(node) / 2;
  418. }
  419. static PyHamtNode_Bitmap *
  420. hamt_node_bitmap_clone(PyHamtNode_Bitmap *node)
  421. {
  422. /* Clone a bitmap node; return a new one with the same child notes. */
  423. PyHamtNode_Bitmap *clone;
  424. Py_ssize_t i;
  425. clone = (PyHamtNode_Bitmap *)hamt_node_bitmap_new(Py_SIZE(node));
  426. if (clone == NULL) {
  427. return NULL;
  428. }
  429. for (i = 0; i < Py_SIZE(node); i++) {
  430. Py_XINCREF(node->b_array[i]);
  431. clone->b_array[i] = node->b_array[i];
  432. }
  433. clone->b_bitmap = node->b_bitmap;
  434. return clone;
  435. }
  436. static PyHamtNode_Bitmap *
  437. hamt_node_bitmap_clone_without(PyHamtNode_Bitmap *o, uint32_t bit)
  438. {
  439. assert(bit & o->b_bitmap);
  440. assert(hamt_node_bitmap_count(o) > 1);
  441. PyHamtNode_Bitmap *new = (PyHamtNode_Bitmap *)hamt_node_bitmap_new(
  442. Py_SIZE(o) - 2);
  443. if (new == NULL) {
  444. return NULL;
  445. }
  446. uint32_t idx = hamt_bitindex(o->b_bitmap, bit);
  447. uint32_t key_idx = 2 * idx;
  448. uint32_t val_idx = key_idx + 1;
  449. uint32_t i;
  450. for (i = 0; i < key_idx; i++) {
  451. Py_XINCREF(o->b_array[i]);
  452. new->b_array[i] = o->b_array[i];
  453. }
  454. assert(Py_SIZE(o) >= 0 && Py_SIZE(o) <= 32);
  455. for (i = val_idx + 1; i < (uint32_t)Py_SIZE(o); i++) {
  456. Py_XINCREF(o->b_array[i]);
  457. new->b_array[i - 2] = o->b_array[i];
  458. }
  459. new->b_bitmap = o->b_bitmap & ~bit;
  460. return new;
  461. }
  462. static PyHamtNode *
  463. hamt_node_new_bitmap_or_collision(uint32_t shift,
  464. PyObject *key1, PyObject *val1,
  465. int32_t key2_hash,
  466. PyObject *key2, PyObject *val2)
  467. {
  468. /* Helper method. Creates a new node for key1/val and key2/val2
  469. pairs.
  470. If key1 hash is equal to the hash of key2, a Collision node
  471. will be created. If they are not equal, a Bitmap node is
  472. created.
  473. */
  474. int32_t key1_hash = hamt_hash(key1);
  475. if (key1_hash == -1) {
  476. return NULL;
  477. }
  478. if (key1_hash == key2_hash) {
  479. PyHamtNode_Collision *n;
  480. n = (PyHamtNode_Collision *)hamt_node_collision_new(key1_hash, 4);
  481. if (n == NULL) {
  482. return NULL;
  483. }
  484. Py_INCREF(key1);
  485. n->c_array[0] = key1;
  486. Py_INCREF(val1);
  487. n->c_array[1] = val1;
  488. Py_INCREF(key2);
  489. n->c_array[2] = key2;
  490. Py_INCREF(val2);
  491. n->c_array[3] = val2;
  492. return (PyHamtNode *)n;
  493. }
  494. else {
  495. int added_leaf = 0;
  496. PyHamtNode *n = hamt_node_bitmap_new(0);
  497. if (n == NULL) {
  498. return NULL;
  499. }
  500. PyHamtNode *n2 = hamt_node_assoc(
  501. n, shift, key1_hash, key1, val1, &added_leaf);
  502. Py_DECREF(n);
  503. if (n2 == NULL) {
  504. return NULL;
  505. }
  506. n = hamt_node_assoc(n2, shift, key2_hash, key2, val2, &added_leaf);
  507. Py_DECREF(n2);
  508. if (n == NULL) {
  509. return NULL;
  510. }
  511. return n;
  512. }
  513. }
  514. static PyHamtNode *
  515. hamt_node_bitmap_assoc(PyHamtNode_Bitmap *self,
  516. uint32_t shift, int32_t hash,
  517. PyObject *key, PyObject *val, int* added_leaf)
  518. {
  519. /* assoc operation for bitmap nodes.
  520. Return: a new node, or self if key/val already is in the
  521. collection.
  522. 'added_leaf' is later used in '_PyHamt_Assoc' to determine if
  523. `hamt.set(key, val)` increased the size of the collection.
  524. */
  525. uint32_t bit = hamt_bitpos(hash, shift);
  526. uint32_t idx = hamt_bitindex(self->b_bitmap, bit);
  527. /* Bitmap node layout:
  528. +------+------+------+------+ --- +------+------+
  529. | key1 | val1 | key2 | val2 | ... | keyN | valN |
  530. +------+------+------+------+ --- +------+------+
  531. where `N < Py_SIZE(node)`.
  532. The `node->b_bitmap` field is a bitmap. For a given
  533. `(shift, hash)` pair we can determine:
  534. - If this node has the corresponding key/val slots.
  535. - The index of key/val slots.
  536. */
  537. if (self->b_bitmap & bit) {
  538. /* The key is set in this node */
  539. uint32_t key_idx = 2 * idx;
  540. uint32_t val_idx = key_idx + 1;
  541. assert(val_idx < (size_t)Py_SIZE(self));
  542. PyObject *key_or_null = self->b_array[key_idx];
  543. PyObject *val_or_node = self->b_array[val_idx];
  544. if (key_or_null == NULL) {
  545. /* key is NULL. This means that we have a few keys
  546. that have the same (hash, shift) pair. */
  547. assert(val_or_node != NULL);
  548. PyHamtNode *sub_node = hamt_node_assoc(
  549. (PyHamtNode *)val_or_node,
  550. shift + 5, hash, key, val, added_leaf);
  551. if (sub_node == NULL) {
  552. return NULL;
  553. }
  554. if (val_or_node == (PyObject *)sub_node) {
  555. Py_DECREF(sub_node);
  556. Py_INCREF(self);
  557. return (PyHamtNode *)self;
  558. }
  559. PyHamtNode_Bitmap *ret = hamt_node_bitmap_clone(self);
  560. if (ret == NULL) {
  561. return NULL;
  562. }
  563. Py_SETREF(ret->b_array[val_idx], (PyObject*)sub_node);
  564. return (PyHamtNode *)ret;
  565. }
  566. assert(key != NULL);
  567. /* key is not NULL. This means that we have only one other
  568. key in this collection that matches our hash for this shift. */
  569. int comp_err = PyObject_RichCompareBool(key, key_or_null, Py_EQ);
  570. if (comp_err < 0) { /* exception in __eq__ */
  571. return NULL;
  572. }
  573. if (comp_err == 1) { /* key == key_or_null */
  574. if (val == val_or_node) {
  575. /* we already have the same key/val pair; return self. */
  576. Py_INCREF(self);
  577. return (PyHamtNode *)self;
  578. }
  579. /* We're setting a new value for the key we had before.
  580. Make a new bitmap node with a replaced value, and return it. */
  581. PyHamtNode_Bitmap *ret = hamt_node_bitmap_clone(self);
  582. if (ret == NULL) {
  583. return NULL;
  584. }
  585. Py_INCREF(val);
  586. Py_SETREF(ret->b_array[val_idx], val);
  587. return (PyHamtNode *)ret;
  588. }
  589. /* It's a new key, and it has the same index as *one* another key.
  590. We have a collision. We need to create a new node which will
  591. combine the existing key and the key we're adding.
  592. `hamt_node_new_bitmap_or_collision` will either create a new
  593. Collision node if the keys have identical hashes, or
  594. a new Bitmap node.
  595. */
  596. PyHamtNode *sub_node = hamt_node_new_bitmap_or_collision(
  597. shift + 5,
  598. key_or_null, val_or_node, /* existing key/val */
  599. hash,
  600. key, val /* new key/val */
  601. );
  602. if (sub_node == NULL) {
  603. return NULL;
  604. }
  605. PyHamtNode_Bitmap *ret = hamt_node_bitmap_clone(self);
  606. if (ret == NULL) {
  607. Py_DECREF(sub_node);
  608. return NULL;
  609. }
  610. Py_SETREF(ret->b_array[key_idx], NULL);
  611. Py_SETREF(ret->b_array[val_idx], (PyObject *)sub_node);
  612. *added_leaf = 1;
  613. return (PyHamtNode *)ret;
  614. }
  615. else {
  616. /* There was no key before with the same (shift,hash). */
  617. uint32_t n = hamt_bitcount(self->b_bitmap);
  618. if (n >= 16) {
  619. /* When we have a situation where we want to store more
  620. than 16 nodes at one level of the tree, we no longer
  621. want to use the Bitmap node with bitmap encoding.
  622. Instead we start using an Array node, which has
  623. simpler (faster) implementation at the expense of
  624. having preallocated 32 pointers for its keys/values
  625. pairs.
  626. Small hamt objects (<30 keys) usually don't have any
  627. Array nodes at all. Between ~30 and ~400 keys hamt
  628. objects usually have one Array node, and usually it's
  629. a root node.
  630. */
  631. uint32_t jdx = hamt_mask(hash, shift);
  632. /* 'jdx' is the index of where the new key should be added
  633. in the new Array node we're about to create. */
  634. PyHamtNode *empty = NULL;
  635. PyHamtNode_Array *new_node = NULL;
  636. PyHamtNode *res = NULL;
  637. /* Create a new Array node. */
  638. new_node = (PyHamtNode_Array *)hamt_node_array_new(n + 1);
  639. if (new_node == NULL) {
  640. goto fin;
  641. }
  642. /* Create an empty bitmap node for the next
  643. hamt_node_assoc call. */
  644. empty = hamt_node_bitmap_new(0);
  645. if (empty == NULL) {
  646. goto fin;
  647. }
  648. /* Make a new bitmap node for the key/val we're adding.
  649. Set that bitmap node to new-array-node[jdx]. */
  650. new_node->a_array[jdx] = hamt_node_assoc(
  651. empty, shift + 5, hash, key, val, added_leaf);
  652. if (new_node->a_array[jdx] == NULL) {
  653. goto fin;
  654. }
  655. /* Copy existing key/value pairs from the current Bitmap
  656. node to the new Array node we've just created. */
  657. Py_ssize_t i, j;
  658. for (i = 0, j = 0; i < HAMT_ARRAY_NODE_SIZE; i++) {
  659. if (((self->b_bitmap >> i) & 1) != 0) {
  660. /* Ensure we don't accidentally override `jdx` element
  661. we set few lines above.
  662. */
  663. assert(new_node->a_array[i] == NULL);
  664. if (self->b_array[j] == NULL) {
  665. new_node->a_array[i] =
  666. (PyHamtNode *)self->b_array[j + 1];
  667. Py_INCREF(new_node->a_array[i]);
  668. }
  669. else {
  670. int32_t rehash = hamt_hash(self->b_array[j]);
  671. if (rehash == -1) {
  672. goto fin;
  673. }
  674. new_node->a_array[i] = hamt_node_assoc(
  675. empty, shift + 5,
  676. rehash,
  677. self->b_array[j],
  678. self->b_array[j + 1],
  679. added_leaf);
  680. if (new_node->a_array[i] == NULL) {
  681. goto fin;
  682. }
  683. }
  684. j += 2;
  685. }
  686. }
  687. VALIDATE_ARRAY_NODE(new_node)
  688. /* That's it! */
  689. res = (PyHamtNode *)new_node;
  690. fin:
  691. Py_XDECREF(empty);
  692. if (res == NULL) {
  693. Py_XDECREF(new_node);
  694. }
  695. return res;
  696. }
  697. else {
  698. /* We have less than 16 keys at this level; let's just
  699. create a new bitmap node out of this node with the
  700. new key/val pair added. */
  701. uint32_t key_idx = 2 * idx;
  702. uint32_t val_idx = key_idx + 1;
  703. uint32_t i;
  704. *added_leaf = 1;
  705. /* Allocate new Bitmap node which can have one more key/val
  706. pair in addition to what we have already. */
  707. PyHamtNode_Bitmap *new_node =
  708. (PyHamtNode_Bitmap *)hamt_node_bitmap_new(2 * (n + 1));
  709. if (new_node == NULL) {
  710. return NULL;
  711. }
  712. /* Copy all keys/values that will be before the new key/value
  713. we are adding. */
  714. for (i = 0; i < key_idx; i++) {
  715. Py_XINCREF(self->b_array[i]);
  716. new_node->b_array[i] = self->b_array[i];
  717. }
  718. /* Set the new key/value to the new Bitmap node. */
  719. Py_INCREF(key);
  720. new_node->b_array[key_idx] = key;
  721. Py_INCREF(val);
  722. new_node->b_array[val_idx] = val;
  723. /* Copy all keys/values that will be after the new key/value
  724. we are adding. */
  725. assert(Py_SIZE(self) >= 0 && Py_SIZE(self) <= 32);
  726. for (i = key_idx; i < (uint32_t)Py_SIZE(self); i++) {
  727. Py_XINCREF(self->b_array[i]);
  728. new_node->b_array[i + 2] = self->b_array[i];
  729. }
  730. new_node->b_bitmap = self->b_bitmap | bit;
  731. return (PyHamtNode *)new_node;
  732. }
  733. }
  734. }
  735. static hamt_without_t
  736. hamt_node_bitmap_without(PyHamtNode_Bitmap *self,
  737. uint32_t shift, int32_t hash,
  738. PyObject *key,
  739. PyHamtNode **new_node)
  740. {
  741. uint32_t bit = hamt_bitpos(hash, shift);
  742. if ((self->b_bitmap & bit) == 0) {
  743. return W_NOT_FOUND;
  744. }
  745. uint32_t idx = hamt_bitindex(self->b_bitmap, bit);
  746. uint32_t key_idx = 2 * idx;
  747. uint32_t val_idx = key_idx + 1;
  748. PyObject *key_or_null = self->b_array[key_idx];
  749. PyObject *val_or_node = self->b_array[val_idx];
  750. if (key_or_null == NULL) {
  751. /* key == NULL means that 'value' is another tree node. */
  752. PyHamtNode *sub_node = NULL;
  753. hamt_without_t res = hamt_node_without(
  754. (PyHamtNode *)val_or_node,
  755. shift + 5, hash, key, &sub_node);
  756. switch (res) {
  757. case W_EMPTY:
  758. /* It's impossible for us to receive a W_EMPTY here:
  759. - Array nodes are converted to Bitmap nodes when
  760. we delete 16th item from them;
  761. - Collision nodes are converted to Bitmap when
  762. there is one item in them;
  763. - Bitmap node's without() inlines single-item
  764. sub-nodes.
  765. So in no situation we can have a single-item
  766. Bitmap child of another Bitmap node.
  767. */
  768. Py_UNREACHABLE();
  769. case W_NEWNODE: {
  770. assert(sub_node != NULL);
  771. if (IS_BITMAP_NODE(sub_node)) {
  772. PyHamtNode_Bitmap *sub_tree = (PyHamtNode_Bitmap *)sub_node;
  773. if (hamt_node_bitmap_count(sub_tree) == 1 &&
  774. sub_tree->b_array[0] != NULL)
  775. {
  776. /* A bitmap node with one key/value pair. Just
  777. merge it into this node.
  778. Note that we don't inline Bitmap nodes that
  779. have a NULL key -- those nodes point to another
  780. tree level, and we cannot simply move tree levels
  781. up or down.
  782. */
  783. PyHamtNode_Bitmap *clone = hamt_node_bitmap_clone(self);
  784. if (clone == NULL) {
  785. Py_DECREF(sub_node);
  786. return W_ERROR;
  787. }
  788. PyObject *key = sub_tree->b_array[0];
  789. PyObject *val = sub_tree->b_array[1];
  790. Py_INCREF(key);
  791. Py_XSETREF(clone->b_array[key_idx], key);
  792. Py_INCREF(val);
  793. Py_SETREF(clone->b_array[val_idx], val);
  794. Py_DECREF(sub_tree);
  795. *new_node = (PyHamtNode *)clone;
  796. return W_NEWNODE;
  797. }
  798. }
  799. #ifdef Py_DEBUG
  800. /* Ensure that Collision.without implementation
  801. converts to Bitmap nodes itself.
  802. */
  803. if (IS_COLLISION_NODE(sub_node)) {
  804. assert(hamt_node_collision_count(
  805. (PyHamtNode_Collision*)sub_node) > 1);
  806. }
  807. #endif
  808. PyHamtNode_Bitmap *clone = hamt_node_bitmap_clone(self);
  809. if (clone == NULL) {
  810. return W_ERROR;
  811. }
  812. Py_SETREF(clone->b_array[val_idx],
  813. (PyObject *)sub_node); /* borrow */
  814. *new_node = (PyHamtNode *)clone;
  815. return W_NEWNODE;
  816. }
  817. case W_ERROR:
  818. case W_NOT_FOUND:
  819. assert(sub_node == NULL);
  820. return res;
  821. default:
  822. Py_UNREACHABLE();
  823. }
  824. }
  825. else {
  826. /* We have a regular key/value pair */
  827. int cmp = PyObject_RichCompareBool(key_or_null, key, Py_EQ);
  828. if (cmp < 0) {
  829. return W_ERROR;
  830. }
  831. if (cmp == 0) {
  832. return W_NOT_FOUND;
  833. }
  834. if (hamt_node_bitmap_count(self) == 1) {
  835. return W_EMPTY;
  836. }
  837. *new_node = (PyHamtNode *)
  838. hamt_node_bitmap_clone_without(self, bit);
  839. if (*new_node == NULL) {
  840. return W_ERROR;
  841. }
  842. return W_NEWNODE;
  843. }
  844. }
  845. static hamt_find_t
  846. hamt_node_bitmap_find(PyHamtNode_Bitmap *self,
  847. uint32_t shift, int32_t hash,
  848. PyObject *key, PyObject **val)
  849. {
  850. /* Lookup a key in a Bitmap node. */
  851. uint32_t bit = hamt_bitpos(hash, shift);
  852. uint32_t idx;
  853. uint32_t key_idx;
  854. uint32_t val_idx;
  855. PyObject *key_or_null;
  856. PyObject *val_or_node;
  857. int comp_err;
  858. if ((self->b_bitmap & bit) == 0) {
  859. return F_NOT_FOUND;
  860. }
  861. idx = hamt_bitindex(self->b_bitmap, bit);
  862. key_idx = idx * 2;
  863. val_idx = key_idx + 1;
  864. assert(val_idx < (size_t)Py_SIZE(self));
  865. key_or_null = self->b_array[key_idx];
  866. val_or_node = self->b_array[val_idx];
  867. if (key_or_null == NULL) {
  868. /* There are a few keys that have the same hash at the current shift
  869. that match our key. Dispatch the lookup further down the tree. */
  870. assert(val_or_node != NULL);
  871. return hamt_node_find((PyHamtNode *)val_or_node,
  872. shift + 5, hash, key, val);
  873. }
  874. /* We have only one key -- a potential match. Let's compare if the
  875. key we are looking at is equal to the key we are looking for. */
  876. assert(key != NULL);
  877. comp_err = PyObject_RichCompareBool(key, key_or_null, Py_EQ);
  878. if (comp_err < 0) { /* exception in __eq__ */
  879. return F_ERROR;
  880. }
  881. if (comp_err == 1) { /* key == key_or_null */
  882. *val = val_or_node;
  883. return F_FOUND;
  884. }
  885. return F_NOT_FOUND;
  886. }
  887. static int
  888. hamt_node_bitmap_traverse(PyHamtNode_Bitmap *self, visitproc visit, void *arg)
  889. {
  890. /* Bitmap's tp_traverse */
  891. Py_ssize_t i;
  892. for (i = Py_SIZE(self); --i >= 0; ) {
  893. Py_VISIT(self->b_array[i]);
  894. }
  895. return 0;
  896. }
  897. static void
  898. hamt_node_bitmap_dealloc(PyHamtNode_Bitmap *self)
  899. {
  900. /* Bitmap's tp_dealloc */
  901. Py_ssize_t len = Py_SIZE(self);
  902. Py_ssize_t i;
  903. PyObject_GC_UnTrack(self);
  904. Py_TRASHCAN_BEGIN(self, hamt_node_bitmap_dealloc)
  905. if (len > 0) {
  906. i = len;
  907. while (--i >= 0) {
  908. Py_XDECREF(self->b_array[i]);
  909. }
  910. }
  911. Py_TYPE(self)->tp_free((PyObject *)self);
  912. Py_TRASHCAN_END
  913. }
  914. #ifdef Py_DEBUG
  915. static int
  916. hamt_node_bitmap_dump(PyHamtNode_Bitmap *node,
  917. _PyUnicodeWriter *writer, int level)
  918. {
  919. /* Debug build: __dump__() method implementation for Bitmap nodes. */
  920. Py_ssize_t i;
  921. PyObject *tmp1;
  922. PyObject *tmp2;
  923. if (_hamt_dump_ident(writer, level + 1)) {
  924. goto error;
  925. }
  926. if (_hamt_dump_format(writer, "BitmapNode(size=%zd count=%zd ",
  927. Py_SIZE(node), Py_SIZE(node) / 2))
  928. {
  929. goto error;
  930. }
  931. tmp1 = PyLong_FromUnsignedLong(node->b_bitmap);
  932. if (tmp1 == NULL) {
  933. goto error;
  934. }
  935. tmp2 = _PyLong_Format(tmp1, 2);
  936. Py_DECREF(tmp1);
  937. if (tmp2 == NULL) {
  938. goto error;
  939. }
  940. if (_hamt_dump_format(writer, "bitmap=%S id=%p):\n", tmp2, node)) {
  941. Py_DECREF(tmp2);
  942. goto error;
  943. }
  944. Py_DECREF(tmp2);
  945. for (i = 0; i < Py_SIZE(node); i += 2) {
  946. PyObject *key_or_null = node->b_array[i];
  947. PyObject *val_or_node = node->b_array[i + 1];
  948. if (_hamt_dump_ident(writer, level + 2)) {
  949. goto error;
  950. }
  951. if (key_or_null == NULL) {
  952. if (_hamt_dump_format(writer, "NULL:\n")) {
  953. goto error;
  954. }
  955. if (hamt_node_dump((PyHamtNode *)val_or_node,
  956. writer, level + 2))
  957. {
  958. goto error;
  959. }
  960. }
  961. else {
  962. if (_hamt_dump_format(writer, "%R: %R", key_or_null,
  963. val_or_node))
  964. {
  965. goto error;
  966. }
  967. }
  968. if (_hamt_dump_format(writer, "\n")) {
  969. goto error;
  970. }
  971. }
  972. return 0;
  973. error:
  974. return -1;
  975. }
  976. #endif /* Py_DEBUG */
  977. /////////////////////////////////// Collision Node
  978. static PyHamtNode *
  979. hamt_node_collision_new(int32_t hash, Py_ssize_t size)
  980. {
  981. /* Create a new Collision node. */
  982. PyHamtNode_Collision *node;
  983. Py_ssize_t i;
  984. assert(size >= 4);
  985. assert(size % 2 == 0);
  986. node = PyObject_GC_NewVar(
  987. PyHamtNode_Collision, &_PyHamt_CollisionNode_Type, size);
  988. if (node == NULL) {
  989. return NULL;
  990. }
  991. for (i = 0; i < size; i++) {
  992. node->c_array[i] = NULL;
  993. }
  994. Py_SIZE(node) = size;
  995. node->c_hash = hash;
  996. _PyObject_GC_TRACK(node);
  997. return (PyHamtNode *)node;
  998. }
  999. static hamt_find_t
  1000. hamt_node_collision_find_index(PyHamtNode_Collision *self, PyObject *key,
  1001. Py_ssize_t *idx)
  1002. {
  1003. /* Lookup `key` in the Collision node `self`. Set the index of the
  1004. found key to 'idx'. */
  1005. Py_ssize_t i;
  1006. PyObject *el;
  1007. for (i = 0; i < Py_SIZE(self); i += 2) {
  1008. el = self->c_array[i];
  1009. assert(el != NULL);
  1010. int cmp = PyObject_RichCompareBool(key, el, Py_EQ);
  1011. if (cmp < 0) {
  1012. return F_ERROR;
  1013. }
  1014. if (cmp == 1) {
  1015. *idx = i;
  1016. return F_FOUND;
  1017. }
  1018. }
  1019. return F_NOT_FOUND;
  1020. }
  1021. static PyHamtNode *
  1022. hamt_node_collision_assoc(PyHamtNode_Collision *self,
  1023. uint32_t shift, int32_t hash,
  1024. PyObject *key, PyObject *val, int* added_leaf)
  1025. {
  1026. /* Set a new key to this level (currently a Collision node)
  1027. of the tree. */
  1028. if (hash == self->c_hash) {
  1029. /* The hash of the 'key' we are adding matches the hash of
  1030. other keys in this Collision node. */
  1031. Py_ssize_t key_idx = -1;
  1032. hamt_find_t found;
  1033. PyHamtNode_Collision *new_node;
  1034. Py_ssize_t i;
  1035. /* Let's try to lookup the new 'key', maybe we already have it. */
  1036. found = hamt_node_collision_find_index(self, key, &key_idx);
  1037. switch (found) {
  1038. case F_ERROR:
  1039. /* Exception. */
  1040. return NULL;
  1041. case F_NOT_FOUND:
  1042. /* This is a totally new key. Clone the current node,
  1043. add a new key/value to the cloned node. */
  1044. new_node = (PyHamtNode_Collision *)hamt_node_collision_new(
  1045. self->c_hash, Py_SIZE(self) + 2);
  1046. if (new_node == NULL) {
  1047. return NULL;
  1048. }
  1049. for (i = 0; i < Py_SIZE(self); i++) {
  1050. Py_INCREF(self->c_array[i]);
  1051. new_node->c_array[i] = self->c_array[i];
  1052. }
  1053. Py_INCREF(key);
  1054. new_node->c_array[i] = key;
  1055. Py_INCREF(val);
  1056. new_node->c_array[i + 1] = val;
  1057. *added_leaf = 1;
  1058. return (PyHamtNode *)new_node;
  1059. case F_FOUND:
  1060. /* There's a key which is equal to the key we are adding. */
  1061. assert(key_idx >= 0);
  1062. assert(key_idx < Py_SIZE(self));
  1063. Py_ssize_t val_idx = key_idx + 1;
  1064. if (self->c_array[val_idx] == val) {
  1065. /* We're setting a key/value pair that's already set. */
  1066. Py_INCREF(self);
  1067. return (PyHamtNode *)self;
  1068. }
  1069. /* We need to replace old value for the key
  1070. with a new value. Create a new Collision node.*/
  1071. new_node = (PyHamtNode_Collision *)hamt_node_collision_new(
  1072. self->c_hash, Py_SIZE(self));
  1073. if (new_node == NULL) {
  1074. return NULL;
  1075. }
  1076. /* Copy all elements of the old node to the new one. */
  1077. for (i = 0; i < Py_SIZE(self); i++) {
  1078. Py_INCREF(self->c_array[i]);
  1079. new_node->c_array[i] = self->c_array[i];
  1080. }
  1081. /* Replace the old value with the new value for the our key. */
  1082. Py_DECREF(new_node->c_array[val_idx]);
  1083. Py_INCREF(val);
  1084. new_node->c_array[val_idx] = val;
  1085. return (PyHamtNode *)new_node;
  1086. default:
  1087. Py_UNREACHABLE();
  1088. }
  1089. }
  1090. else {
  1091. /* The hash of the new key is different from the hash that
  1092. all keys of this Collision node have.
  1093. Create a Bitmap node inplace with two children:
  1094. key/value pair that we're adding, and the Collision node
  1095. we're replacing on this tree level.
  1096. */
  1097. PyHamtNode_Bitmap *new_node;
  1098. PyHamtNode *assoc_res;
  1099. new_node = (PyHamtNode_Bitmap *)hamt_node_bitmap_new(2);
  1100. if (new_node == NULL) {
  1101. return NULL;
  1102. }
  1103. new_node->b_bitmap = hamt_bitpos(self->c_hash, shift);
  1104. Py_INCREF(self);
  1105. new_node->b_array[1] = (PyObject*) self;
  1106. assoc_res = hamt_node_bitmap_assoc(
  1107. new_node, shift, hash, key, val, added_leaf);
  1108. Py_DECREF(new_node);
  1109. return assoc_res;
  1110. }
  1111. }
  1112. static inline Py_ssize_t
  1113. hamt_node_collision_count(PyHamtNode_Collision *node)
  1114. {
  1115. return Py_SIZE(node) / 2;
  1116. }
  1117. static hamt_without_t
  1118. hamt_node_collision_without(PyHamtNode_Collision *self,
  1119. uint32_t shift, int32_t hash,
  1120. PyObject *key,
  1121. PyHamtNode **new_node)
  1122. {
  1123. if (hash != self->c_hash) {
  1124. return W_NOT_FOUND;
  1125. }
  1126. Py_ssize_t key_idx = -1;
  1127. hamt_find_t found = hamt_node_collision_find_index(self, key, &key_idx);
  1128. switch (found) {
  1129. case F_ERROR:
  1130. return W_ERROR;
  1131. case F_NOT_FOUND:
  1132. return W_NOT_FOUND;
  1133. case F_FOUND:
  1134. assert(key_idx >= 0);
  1135. assert(key_idx < Py_SIZE(self));
  1136. Py_ssize_t new_count = hamt_node_collision_count(self) - 1;
  1137. if (new_count == 0) {
  1138. /* The node has only one key/value pair and it's for the
  1139. key we're trying to delete. So a new node will be empty
  1140. after the removal.
  1141. */
  1142. return W_EMPTY;
  1143. }
  1144. if (new_count == 1) {
  1145. /* The node has two keys, and after deletion the
  1146. new Collision node would have one. Collision nodes
  1147. with one key shouldn't exist, so convert it to a
  1148. Bitmap node.
  1149. */
  1150. PyHamtNode_Bitmap *node = (PyHamtNode_Bitmap *)
  1151. hamt_node_bitmap_new(2);
  1152. if (node == NULL) {
  1153. return W_ERROR;
  1154. }
  1155. if (key_idx == 0) {
  1156. Py_INCREF(self->c_array[2]);
  1157. node->b_array[0] = self->c_array[2];
  1158. Py_INCREF(self->c_array[3]);
  1159. node->b_array[1] = self->c_array[3];
  1160. }
  1161. else {
  1162. assert(key_idx == 2);
  1163. Py_INCREF(self->c_array[0]);
  1164. node->b_array[0] = self->c_array[0];
  1165. Py_INCREF(self->c_array[1]);
  1166. node->b_array[1] = self->c_array[1];
  1167. }
  1168. node->b_bitmap = hamt_bitpos(hash, shift);
  1169. *new_node = (PyHamtNode *)node;
  1170. return W_NEWNODE;
  1171. }
  1172. /* Allocate a new Collision node with capacity for one
  1173. less key/value pair */
  1174. PyHamtNode_Collision *new = (PyHamtNode_Collision *)
  1175. hamt_node_collision_new(
  1176. self->c_hash, Py_SIZE(self) - 2);
  1177. if (new == NULL) {
  1178. return W_ERROR;
  1179. }
  1180. /* Copy all other keys from `self` to `new` */
  1181. Py_ssize_t i;
  1182. for (i = 0; i < key_idx; i++) {
  1183. Py_INCREF(self->c_array[i]);
  1184. new->c_array[i] = self->c_array[i];
  1185. }
  1186. for (i = key_idx + 2; i < Py_SIZE(self); i++) {
  1187. Py_INCREF(self->c_array[i]);
  1188. new->c_array[i - 2] = self->c_array[i];
  1189. }
  1190. *new_node = (PyHamtNode*)new;
  1191. return W_NEWNODE;
  1192. default:
  1193. Py_UNREACHABLE();
  1194. }
  1195. }
  1196. static hamt_find_t
  1197. hamt_node_collision_find(PyHamtNode_Collision *self,
  1198. uint32_t shift, int32_t hash,
  1199. PyObject *key, PyObject **val)
  1200. {
  1201. /* Lookup `key` in the Collision node `self`. Set the value
  1202. for the found key to 'val'. */
  1203. Py_ssize_t idx = -1;
  1204. hamt_find_t res;
  1205. res = hamt_node_collision_find_index(self, key, &idx);
  1206. if (res == F_ERROR || res == F_NOT_FOUND) {
  1207. return res;
  1208. }
  1209. assert(idx >= 0);
  1210. assert(idx + 1 < Py_SIZE(self));
  1211. *val = self->c_array[idx + 1];
  1212. assert(*val != NULL);
  1213. return F_FOUND;
  1214. }
  1215. static int
  1216. hamt_node_collision_traverse(PyHamtNode_Collision *self,
  1217. visitproc visit, void *arg)
  1218. {
  1219. /* Collision's tp_traverse */
  1220. Py_ssize_t i;
  1221. for (i = Py_SIZE(self); --i >= 0; ) {
  1222. Py_VISIT(self->c_array[i]);
  1223. }
  1224. return 0;
  1225. }
  1226. static void
  1227. hamt_node_collision_dealloc(PyHamtNode_Collision *self)
  1228. {
  1229. /* Collision's tp_dealloc */
  1230. Py_ssize_t len = Py_SIZE(self);
  1231. PyObject_GC_UnTrack(self);
  1232. Py_TRASHCAN_BEGIN(self, hamt_node_collision_dealloc)
  1233. if (len > 0) {
  1234. while (--len >= 0) {
  1235. Py_XDECREF(self->c_array[len]);
  1236. }
  1237. }
  1238. Py_TYPE(self)->tp_free((PyObject *)self);
  1239. Py_TRASHCAN_END
  1240. }
  1241. #ifdef Py_DEBUG
  1242. static int
  1243. hamt_node_collision_dump(PyHamtNode_Collision *node,
  1244. _PyUnicodeWriter *writer, int level)
  1245. {
  1246. /* Debug build: __dump__() method implementation for Collision nodes. */
  1247. Py_ssize_t i;
  1248. if (_hamt_dump_ident(writer, level + 1)) {
  1249. goto error;
  1250. }
  1251. if (_hamt_dump_format(writer, "CollisionNode(size=%zd id=%p):\n",
  1252. Py_SIZE(node), node))
  1253. {
  1254. goto error;
  1255. }
  1256. for (i = 0; i < Py_SIZE(node); i += 2) {
  1257. PyObject *key = node->c_array[i];
  1258. PyObject *val = node->c_array[i + 1];
  1259. if (_hamt_dump_ident(writer, level + 2)) {
  1260. goto error;
  1261. }
  1262. if (_hamt_dump_format(writer, "%R: %R\n", key, val)) {
  1263. goto error;
  1264. }
  1265. }
  1266. return 0;
  1267. error:
  1268. return -1;
  1269. }
  1270. #endif /* Py_DEBUG */
  1271. /////////////////////////////////// Array Node
  1272. static PyHamtNode *
  1273. hamt_node_array_new(Py_ssize_t count)
  1274. {
  1275. Py_ssize_t i;
  1276. PyHamtNode_Array *node = PyObject_GC_New(
  1277. PyHamtNode_Array, &_PyHamt_ArrayNode_Type);
  1278. if (node == NULL) {
  1279. return NULL;
  1280. }
  1281. for (i = 0; i < HAMT_ARRAY_NODE_SIZE; i++) {
  1282. node->a_array[i] = NULL;
  1283. }
  1284. node->a_count = count;
  1285. _PyObject_GC_TRACK(node);
  1286. return (PyHamtNode *)node;
  1287. }
  1288. static PyHamtNode_Array *
  1289. hamt_node_array_clone(PyHamtNode_Array *node)
  1290. {
  1291. PyHamtNode_Array *clone;
  1292. Py_ssize_t i;
  1293. VALIDATE_ARRAY_NODE(node)
  1294. /* Create a new Array node. */
  1295. clone = (PyHamtNode_Array *)hamt_node_array_new(node->a_count);
  1296. if (clone == NULL) {
  1297. return NULL;
  1298. }
  1299. /* Copy all elements from the current Array node to the new one. */
  1300. for (i = 0; i < HAMT_ARRAY_NODE_SIZE; i++) {
  1301. Py_XINCREF(node->a_array[i]);
  1302. clone->a_array[i] = node->a_array[i];
  1303. }
  1304. VALIDATE_ARRAY_NODE(clone)
  1305. return clone;
  1306. }
  1307. static PyHamtNode *
  1308. hamt_node_array_assoc(PyHamtNode_Array *self,
  1309. uint32_t shift, int32_t hash,
  1310. PyObject *key, PyObject *val, int* added_leaf)
  1311. {
  1312. /* Set a new key to this level (currently a Collision node)
  1313. of the tree.
  1314. Array nodes don't store values, they can only point to
  1315. other nodes. They are simple arrays of 32 BaseNode pointers/
  1316. */
  1317. uint32_t idx = hamt_mask(hash, shift);
  1318. PyHamtNode *node = self->a_array[idx];
  1319. PyHamtNode *child_node;
  1320. PyHamtNode_Array *new_node;
  1321. Py_ssize_t i;
  1322. if (node == NULL) {
  1323. /* There's no child node for the given hash. Create a new
  1324. Bitmap node for this key. */
  1325. PyHamtNode_Bitmap *empty = NULL;
  1326. /* Get an empty Bitmap node to work with. */
  1327. empty = (PyHamtNode_Bitmap *)hamt_node_bitmap_new(0);
  1328. if (empty == NULL) {
  1329. return NULL;
  1330. }
  1331. /* Set key/val to the newly created empty Bitmap, thus
  1332. creating a new Bitmap node with our key/value pair. */
  1333. child_node = hamt_node_bitmap_assoc(
  1334. empty,
  1335. shift + 5, hash, key, val, added_leaf);
  1336. Py_DECREF(empty);
  1337. if (child_node == NULL) {
  1338. return NULL;
  1339. }
  1340. /* Create a new Array node. */
  1341. new_node = (PyHamtNode_Array *)hamt_node_array_new(self->a_count + 1);
  1342. if (new_node == NULL) {
  1343. Py_DECREF(child_node);
  1344. return NULL;
  1345. }
  1346. /* Copy all elements from the current Array node to the
  1347. new one. */
  1348. for (i = 0; i < HAMT_ARRAY_NODE_SIZE; i++) {
  1349. Py_XINCREF(self->a_array[i]);
  1350. new_node->a_array[i] = self->a_array[i];
  1351. }
  1352. assert(new_node->a_array[idx] == NULL);
  1353. new_node->a_array[idx] = child_node; /* borrow */
  1354. VALIDATE_ARRAY_NODE(new_node)
  1355. }
  1356. else {
  1357. /* There's a child node for the given hash.
  1358. Set the key to it./ */
  1359. child_node = hamt_node_assoc(
  1360. node, shift + 5, hash, key, val, added_leaf);
  1361. if (child_node == NULL) {
  1362. return NULL;
  1363. }
  1364. else if (child_node == (PyHamtNode *)self) {
  1365. Py_DECREF(child_node);
  1366. return (PyHamtNode *)self;
  1367. }
  1368. new_node = hamt_node_array_clone(self);
  1369. if (new_node == NULL) {
  1370. Py_DECREF(child_node);
  1371. return NULL;
  1372. }
  1373. Py_SETREF(new_node->a_array[idx], child_node); /* borrow */
  1374. VALIDATE_ARRAY_NODE(new_node)
  1375. }
  1376. return (PyHamtNode *)new_node;
  1377. }
  1378. static hamt_without_t
  1379. hamt_node_array_without(PyHamtNode_Array *self,
  1380. uint32_t shift, int32_t hash,
  1381. PyObject *key,
  1382. PyHamtNode **new_node)
  1383. {
  1384. uint32_t idx = hamt_mask(hash, shift);
  1385. PyHamtNode *node = self->a_array[idx];
  1386. if (node == NULL) {
  1387. return W_NOT_FOUND;
  1388. }
  1389. PyHamtNode *sub_node = NULL;
  1390. hamt_without_t res = hamt_node_without(
  1391. (PyHamtNode *)node,
  1392. shift + 5, hash, key, &sub_node);
  1393. switch (res) {
  1394. case W_NOT_FOUND:
  1395. case W_ERROR:
  1396. assert(sub_node == NULL);
  1397. return res;
  1398. case W_NEWNODE: {
  1399. /* We need to replace a node at the `idx` index.
  1400. Clone this node and replace.
  1401. */
  1402. assert(sub_node != NULL);
  1403. PyHamtNode_Array *clone = hamt_node_array_clone(self);
  1404. if (clone == NULL) {
  1405. Py_DECREF(sub_node);
  1406. return W_ERROR;
  1407. }
  1408. Py_SETREF(clone->a_array[idx], sub_node); /* borrow */
  1409. *new_node = (PyHamtNode*)clone; /* borrow */
  1410. return W_NEWNODE;
  1411. }
  1412. case W_EMPTY: {
  1413. assert(sub_node == NULL);
  1414. /* We need to remove a node at the `idx` index.
  1415. Calculate the size of the replacement Array node.
  1416. */
  1417. Py_ssize_t new_count = self->a_count - 1;
  1418. if (new_count == 0) {
  1419. return W_EMPTY;
  1420. }
  1421. if (new_count >= 16) {
  1422. /* We convert Bitmap nodes to Array nodes, when a
  1423. Bitmap node needs to store more than 15 key/value
  1424. pairs. So we will create a new Array node if we
  1425. the number of key/values after deletion is still
  1426. greater than 15.
  1427. */
  1428. PyHamtNode_Array *new = hamt_node_array_clone(self);
  1429. if (new == NULL) {
  1430. return W_ERROR;
  1431. }
  1432. new->a_count = new_count;
  1433. Py_CLEAR(new->a_array[idx]);
  1434. *new_node = (PyHamtNode*)new; /* borrow */
  1435. return W_NEWNODE;
  1436. }
  1437. /* New Array node would have less than 16 key/value
  1438. pairs. We need to create a replacement Bitmap node. */
  1439. Py_ssize_t bitmap_size = new_count * 2;
  1440. uint32_t bitmap = 0;
  1441. PyHamtNode_Bitmap *new = (PyHamtNode_Bitmap *)
  1442. hamt_node_bitmap_new(bitmap_size);
  1443. if (new == NULL) {
  1444. return W_ERROR;
  1445. }
  1446. Py_ssize_t new_i = 0;
  1447. for (uint32_t i = 0; i < HAMT_ARRAY_NODE_SIZE; i++) {
  1448. if (i == idx) {
  1449. /* Skip the node we are deleting. */
  1450. continue;
  1451. }
  1452. PyHamtNode *node = self->a_array[i];
  1453. if (node == NULL) {
  1454. /* Skip any missing nodes. */
  1455. continue;
  1456. }
  1457. bitmap |= 1U << i;
  1458. if (IS_BITMAP_NODE(node)) {
  1459. PyHamtNode_Bitmap *child = (PyHamtNode_Bitmap *)node;
  1460. if (hamt_node_bitmap_count(child) == 1 &&
  1461. child->b_array[0] != NULL)
  1462. {
  1463. /* node is a Bitmap with one key/value pair, just
  1464. merge it into the new Bitmap node we're building.
  1465. Note that we don't inline Bitmap nodes that
  1466. have a NULL key -- those nodes point to another
  1467. tree level, and we cannot simply move tree levels
  1468. up or down.
  1469. */
  1470. PyObject *key = child->b_array[0];
  1471. PyObject *val = child->b_array[1];
  1472. Py_INCREF(key);
  1473. new->b_array[new_i] = key;
  1474. Py_INCREF(val);
  1475. new->b_array[new_i + 1] = val;
  1476. }
  1477. else {
  1478. new->b_array[new_i] = NULL;
  1479. Py_INCREF(node);
  1480. new->b_array[new_i + 1] = (PyObject*)node;
  1481. }
  1482. }
  1483. else {
  1484. #ifdef Py_DEBUG
  1485. if (IS_COLLISION_NODE(node)) {
  1486. Py_ssize_t child_count = hamt_node_collision_count(
  1487. (PyHamtNode_Collision*)node);
  1488. assert(child_count > 1);
  1489. }
  1490. else if (IS_ARRAY_NODE(node)) {
  1491. assert(((PyHamtNode_Array*)node)->a_count >= 16);
  1492. }
  1493. #endif
  1494. /* Just copy the node into our new Bitmap */
  1495. new->b_array[new_i] = NULL;
  1496. Py_INCREF(node);
  1497. new->b_array[new_i + 1] = (PyObject*)node;
  1498. }
  1499. new_i += 2;
  1500. }
  1501. new->b_bitmap = bitmap;
  1502. *new_node = (PyHamtNode*)new; /* borrow */
  1503. return W_NEWNODE;
  1504. }
  1505. default:
  1506. Py_UNREACHABLE();
  1507. }
  1508. }
  1509. static hamt_find_t
  1510. hamt_node_array_find(PyHamtNode_Array *self,
  1511. uint32_t shift, int32_t hash,
  1512. PyObject *key, PyObject **val)
  1513. {
  1514. /* Lookup `key` in the Array node `self`. Set the value
  1515. for the found key to 'val'. */
  1516. uint32_t idx = hamt_mask(hash, shift);
  1517. PyHamtNode *node;
  1518. node = self->a_array[idx];
  1519. if (node == NULL) {
  1520. return F_NOT_FOUND;
  1521. }
  1522. /* Dispatch to the generic hamt_node_find */
  1523. return hamt_node_find(node, shift + 5, hash, key, val);
  1524. }
  1525. static int
  1526. hamt_node_array_traverse(PyHamtNode_Array *self,
  1527. visitproc visit, void *arg)
  1528. {
  1529. /* Array's tp_traverse */
  1530. Py_ssize_t i;
  1531. for (i = 0; i < HAMT_ARRAY_NODE_SIZE; i++) {
  1532. Py_VISIT(self->a_array[i]);
  1533. }
  1534. return 0;
  1535. }
  1536. static void
  1537. hamt_node_array_dealloc(PyHamtNode_Array *self)
  1538. {
  1539. /* Array's tp_dealloc */
  1540. Py_ssize_t i;
  1541. PyObject_GC_UnTrack(self);
  1542. Py_TRASHCAN_BEGIN(self, hamt_node_array_dealloc)
  1543. for (i = 0; i < HAMT_ARRAY_NODE_SIZE; i++) {
  1544. Py_XDECREF(self->a_array[i]);
  1545. }
  1546. Py_TYPE(self)->tp_free((PyObject *)self);
  1547. Py_TRASHCAN_END
  1548. }
  1549. #ifdef Py_DEBUG
  1550. static int
  1551. hamt_node_array_dump(PyHamtNode_Array *node,
  1552. _PyUnicodeWriter *writer, int level)
  1553. {
  1554. /* Debug build: __dump__() method implementation for Array nodes. */
  1555. Py_ssize_t i;
  1556. if (_hamt_dump_ident(writer, level + 1)) {
  1557. goto error;
  1558. }
  1559. if (_hamt_dump_format(writer, "ArrayNode(id=%p):\n", node)) {
  1560. goto error;
  1561. }
  1562. for (i = 0; i < HAMT_ARRAY_NODE_SIZE; i++) {
  1563. if (node->a_array[i] == NULL) {
  1564. continue;
  1565. }
  1566. if (_hamt_dump_ident(writer, level + 2)) {
  1567. goto error;
  1568. }
  1569. if (_hamt_dump_format(writer, "%zd::\n", i)) {
  1570. goto error;
  1571. }
  1572. if (hamt_node_dump(node->a_array[i], writer, level + 1)) {
  1573. goto error;
  1574. }
  1575. if (_hamt_dump_format(writer, "\n")) {
  1576. goto error;
  1577. }
  1578. }
  1579. return 0;
  1580. error:
  1581. return -1;
  1582. }
  1583. #endif /* Py_DEBUG */
  1584. /////////////////////////////////// Node Dispatch
  1585. static PyHamtNode *
  1586. hamt_node_assoc(PyHamtNode *node,
  1587. uint32_t shift, int32_t hash,
  1588. PyObject *key, PyObject *val, int* added_leaf)
  1589. {
  1590. /* Set key/value to the 'node' starting with the given shift/hash.
  1591. Return a new node, or the same node if key/value already
  1592. set.
  1593. added_leaf will be set to 1 if key/value wasn't in the
  1594. tree before.
  1595. This method automatically dispatches to the suitable
  1596. hamt_node_{nodetype}_assoc method.
  1597. */
  1598. if (IS_BITMAP_NODE(node)) {
  1599. return hamt_node_bitmap_assoc(
  1600. (PyHamtNode_Bitmap *)node,
  1601. shift, hash, key, val, added_leaf);
  1602. }
  1603. else if (IS_ARRAY_NODE(node)) {
  1604. return hamt_node_array_assoc(
  1605. (PyHamtNode_Array *)node,
  1606. shift, hash, key, val, added_leaf);
  1607. }
  1608. else {
  1609. assert(IS_COLLISION_NODE(node));
  1610. return hamt_node_collision_assoc(
  1611. (PyHamtNode_Collision *)node,
  1612. shift, hash, key, val, added_leaf);
  1613. }
  1614. }
  1615. static hamt_without_t
  1616. hamt_node_without(PyHamtNode *node,
  1617. uint32_t shift, int32_t hash,
  1618. PyObject *key,
  1619. PyHamtNode **new_node)
  1620. {
  1621. if (IS_BITMAP_NODE(node)) {
  1622. return hamt_node_bitmap_without(
  1623. (PyHamtNode_Bitmap *)node,
  1624. shift, hash, key,
  1625. new_node);
  1626. }
  1627. else if (IS_ARRAY_NODE(node)) {
  1628. return hamt_node_array_without(
  1629. (PyHamtNode_Array *)node,
  1630. shift, hash, key,
  1631. new_node);
  1632. }
  1633. else {
  1634. assert(IS_COLLISION_NODE(node));
  1635. return hamt_node_collision_without(
  1636. (PyHamtNode_Collision *)node,
  1637. shift, hash, key,
  1638. new_node);
  1639. }
  1640. }
  1641. static hamt_find_t
  1642. hamt_node_find(PyHamtNode *node,
  1643. uint32_t shift, int32_t hash,
  1644. PyObject *key, PyObject **val)
  1645. {
  1646. /* Find the key in the node starting with the given shift/hash.
  1647. If a value is found, the result will be set to F_FOUND, and
  1648. *val will point to the found value object.
  1649. If a value wasn't found, the result will be set to F_NOT_FOUND.
  1650. If an exception occurs during the call, the result will be F_ERROR.
  1651. This method automatically dispatches to the suitable
  1652. hamt_node_{nodetype}_find method.
  1653. */
  1654. if (IS_BITMAP_NODE(node)) {
  1655. return hamt_node_bitmap_find(
  1656. (PyHamtNode_Bitmap *)node,
  1657. shift, hash, key, val);
  1658. }
  1659. else if (IS_ARRAY_NODE(node)) {
  1660. return hamt_node_array_find(
  1661. (PyHamtNode_Array *)node,
  1662. shift, hash, key, val);
  1663. }
  1664. else {
  1665. assert(IS_COLLISION_NODE(node));
  1666. return hamt_node_collision_find(
  1667. (PyHamtNode_Collision *)node,
  1668. shift, hash, key, val);
  1669. }
  1670. }
  1671. #ifdef Py_DEBUG
  1672. static int
  1673. hamt_node_dump(PyHamtNode *node,
  1674. _PyUnicodeWriter *writer, int level)
  1675. {
  1676. /* Debug build: __dump__() method implementation for a node.
  1677. This method automatically dispatches to the suitable
  1678. hamt_node_{nodetype})_dump method.
  1679. */
  1680. if (IS_BITMAP_NODE(node)) {
  1681. return hamt_node_bitmap_dump(
  1682. (PyHamtNode_Bitmap *)node, writer, level);
  1683. }
  1684. else if (IS_ARRAY_NODE(node)) {
  1685. return hamt_node_array_dump(
  1686. (PyHamtNode_Array *)node, writer, level);
  1687. }
  1688. else {
  1689. assert(IS_COLLISION_NODE(node));
  1690. return hamt_node_collision_dump(
  1691. (PyHamtNode_Collision *)node, writer, level);
  1692. }
  1693. }
  1694. #endif /* Py_DEBUG */
  1695. /////////////////////////////////// Iterators: Machinery
  1696. static hamt_iter_t
  1697. hamt_iterator_next(PyHamtIteratorState *iter, PyObject **key, PyObject **val);
  1698. static void
  1699. hamt_iterator_init(PyHamtIteratorState *iter, PyHamtNode *root)
  1700. {
  1701. for (uint32_t i = 0; i < _Py_HAMT_MAX_TREE_DEPTH; i++) {
  1702. iter->i_nodes[i] = NULL;
  1703. iter->i_pos[i] = 0;
  1704. }
  1705. iter->i_level = 0;
  1706. /* Note: we don't incref/decref nodes in i_nodes. */
  1707. iter->i_nodes[0] = root;
  1708. }
  1709. static hamt_iter_t
  1710. hamt_iterator_bitmap_next(PyHamtIteratorState *iter,
  1711. PyObject **key, PyObject **val)
  1712. {
  1713. int8_t level = iter->i_level;
  1714. PyHamtNode_Bitmap *node = (PyHamtNode_Bitmap *)(iter->i_nodes[level]);
  1715. Py_ssize_t pos = iter->i_pos[level];
  1716. if (pos + 1 >= Py_SIZE(node)) {
  1717. #ifdef Py_DEBUG
  1718. assert(iter->i_level >= 0);
  1719. iter->i_nodes[iter->i_level] = NULL;
  1720. #endif
  1721. iter->i_level--;
  1722. return hamt_iterator_next(iter, key, val);
  1723. }
  1724. if (node->b_array[pos] == NULL) {
  1725. iter->i_pos[level] = pos + 2;
  1726. int8_t next_level = level + 1;
  1727. assert(next_level < _Py_HAMT_MAX_TREE_DEPTH);
  1728. iter->i_level = next_level;
  1729. iter->i_pos[next_level] = 0;
  1730. iter->i_nodes[next_level] = (PyHamtNode *)
  1731. node->b_array[pos + 1];
  1732. return hamt_iterator_next(iter, key, val);
  1733. }
  1734. *key = node->b_array[pos];
  1735. *val = node->b_array[pos + 1];
  1736. iter->i_pos[level] = pos + 2;
  1737. return I_ITEM;
  1738. }
  1739. static hamt_iter_t
  1740. hamt_iterator_collision_next(PyHamtIteratorState *iter,
  1741. PyObject **key, PyObject **val)
  1742. {
  1743. int8_t level = iter->i_level;
  1744. PyHamtNode_Collision *node = (PyHamtNode_Collision *)(iter->i_nodes[level]);
  1745. Py_ssize_t pos = iter->i_pos[level];
  1746. if (pos + 1 >= Py_SIZE(node)) {
  1747. #ifdef Py_DEBUG
  1748. assert(iter->i_level >= 0);
  1749. iter->i_nodes[iter->i_level] = NULL;
  1750. #endif
  1751. iter->i_level--;
  1752. return hamt_iterator_next(iter, key, val);
  1753. }
  1754. *key = node->c_array[pos];
  1755. *val = node->c_array[pos + 1];
  1756. iter->i_pos[level] = pos + 2;
  1757. return I_ITEM;
  1758. }
  1759. static hamt_iter_t
  1760. hamt_iterator_array_next(PyHamtIteratorState *iter,
  1761. PyObject **key, PyObject **val)
  1762. {
  1763. int8_t level = iter->i_level;
  1764. PyHamtNode_Array *node = (PyHamtNode_Array *)(iter->i_nodes[level]);
  1765. Py_ssize_t pos = iter->i_pos[level];
  1766. if (pos >= HAMT_ARRAY_NODE_SIZE) {
  1767. #ifdef Py_DEBUG
  1768. assert(iter->i_level >= 0);
  1769. iter->i_nodes[iter->i_level] = NULL;
  1770. #endif
  1771. iter->i_level--;
  1772. return hamt_iterator_next(iter, key, val);
  1773. }
  1774. for (Py_ssize_t i = pos; i < HAMT_ARRAY_NODE_SIZE; i++) {
  1775. if (node->a_array[i] != NULL) {
  1776. iter->i_pos[level] = i + 1;
  1777. int8_t next_level = level + 1;
  1778. assert(next_level < _Py_HAMT_MAX_TREE_DEPTH);
  1779. iter->i_pos[next_level] = 0;
  1780. iter->i_nodes[next_level] = node->a_array[i];
  1781. iter->i_level = next_level;
  1782. return hamt_iterator_next(iter, key, val);
  1783. }
  1784. }
  1785. #ifdef Py_DEBUG
  1786. assert(iter->i_level >= 0);
  1787. iter->i_nodes[iter->i_level] = NULL;
  1788. #endif
  1789. iter->i_level--;
  1790. return hamt_iterator_next(iter, key, val);
  1791. }
  1792. static hamt_iter_t
  1793. hamt_iterator_next(PyHamtIteratorState *iter, PyObject **key, PyObject **val)
  1794. {
  1795. if (iter->i_level < 0) {
  1796. return I_END;
  1797. }
  1798. assert(iter->i_level < _Py_HAMT_MAX_TREE_DEPTH);
  1799. PyHamtNode *current = iter->i_nodes[iter->i_level];
  1800. if (IS_BITMAP_NODE(current)) {
  1801. return hamt_iterator_bitmap_next(iter, key, val);
  1802. }
  1803. else if (IS_ARRAY_NODE(current)) {
  1804. return hamt_iterator_array_next(iter, key, val);
  1805. }
  1806. else {
  1807. assert(IS_COLLISION_NODE(current));
  1808. return hamt_iterator_collision_next(iter, key, val);
  1809. }
  1810. }
  1811. /////////////////////////////////// HAMT high-level functions
  1812. PyHamtObject *
  1813. _PyHamt_Assoc(PyHamtObject *o, PyObject *key, PyObject *val)
  1814. {
  1815. int32_t key_hash;
  1816. int added_leaf = 0;
  1817. PyHamtNode *new_root;
  1818. PyHamtObject *new_o;
  1819. key_hash = hamt_hash(key);
  1820. if (key_hash == -1) {
  1821. return NULL;
  1822. }
  1823. new_root = hamt_node_assoc(
  1824. (PyHamtNode *)(o->h_root),
  1825. 0, key_hash, key, val, &added_leaf);
  1826. if (new_root == NULL) {
  1827. return NULL;
  1828. }
  1829. if (new_root == o->h_root) {
  1830. Py_DECREF(new_root);
  1831. Py_INCREF(o);
  1832. return o;
  1833. }
  1834. new_o = hamt_alloc();
  1835. if (new_o == NULL) {
  1836. Py_DECREF(new_root);
  1837. return NULL;
  1838. }
  1839. new_o->h_root = new_root; /* borrow */
  1840. new_o->h_count = added_leaf ? o->h_count + 1 : o->h_count;
  1841. return new_o;
  1842. }
  1843. PyHamtObject *
  1844. _PyHamt_Without(PyHamtObject *o, PyObject *key)
  1845. {
  1846. int32_t key_hash = hamt_hash(key);
  1847. if (key_hash == -1) {
  1848. return NULL;
  1849. }
  1850. PyHamtNode *new_root = NULL;
  1851. hamt_without_t res = hamt_node_without(
  1852. (PyHamtNode *)(o->h_root),
  1853. 0, key_hash, key,
  1854. &new_root);
  1855. switch (res) {
  1856. case W_ERROR:
  1857. return NULL;
  1858. case W_EMPTY:
  1859. return _PyHamt_New();
  1860. case W_NOT_FOUND:
  1861. Py_INCREF(o);
  1862. return o;
  1863. case W_NEWNODE: {
  1864. assert(new_root != NULL);
  1865. PyHamtObject *new_o = hamt_alloc();
  1866. if (new_o == NULL) {
  1867. Py_DECREF(new_root);
  1868. return NULL;
  1869. }
  1870. new_o->h_root = new_root; /* borrow */
  1871. new_o->h_count = o->h_count - 1;
  1872. assert(new_o->h_count >= 0);
  1873. return new_o;
  1874. }
  1875. default:
  1876. Py_UNREACHABLE();
  1877. }
  1878. }
  1879. static hamt_find_t
  1880. hamt_find(PyHamtObject *o, PyObject *key, PyObject **val)
  1881. {
  1882. if (o->h_count == 0) {
  1883. return F_NOT_FOUND;
  1884. }
  1885. int32_t key_hash = hamt_hash(key);
  1886. if (key_hash == -1) {
  1887. return F_ERROR;
  1888. }
  1889. return hamt_node_find(o->h_root, 0, key_hash, key, val);
  1890. }
  1891. int
  1892. _PyHamt_Find(PyHamtObject *o, PyObject *key, PyObject **val)
  1893. {
  1894. hamt_find_t res = hamt_find(o, key, val);
  1895. switch (res) {
  1896. case F_ERROR:
  1897. return -1;
  1898. case F_NOT_FOUND:
  1899. return 0;
  1900. case F_FOUND:
  1901. return 1;
  1902. default:
  1903. Py_UNREACHABLE();
  1904. }
  1905. }
  1906. int
  1907. _PyHamt_Eq(PyHamtObject *v, PyHamtObject *w)
  1908. {
  1909. if (v == w) {
  1910. return 1;
  1911. }
  1912. if (v->h_count != w->h_count) {
  1913. return 0;
  1914. }
  1915. PyHamtIteratorState iter;
  1916. hamt_iter_t iter_res;
  1917. hamt_find_t find_res;
  1918. PyObject *v_key;
  1919. PyObject *v_val;
  1920. PyObject *w_val;
  1921. hamt_iterator_init(&iter, v->h_root);
  1922. do {
  1923. iter_res = hamt_iterator_next(&iter, &v_key, &v_val);
  1924. if (iter_res == I_ITEM) {
  1925. find_res = hamt_find(w, v_key, &w_val);
  1926. switch (find_res) {
  1927. case F_ERROR:
  1928. return -1;
  1929. case F_NOT_FOUND:
  1930. return 0;
  1931. case F_FOUND: {
  1932. int cmp = PyObject_RichCompareBool(v_val, w_val, Py_EQ);
  1933. if (cmp < 0) {
  1934. return -1;
  1935. }
  1936. if (cmp == 0) {
  1937. return 0;
  1938. }
  1939. }
  1940. }
  1941. }
  1942. } while (iter_res != I_END);
  1943. return 1;
  1944. }
  1945. Py_ssize_t
  1946. _PyHamt_Len(PyHamtObject *o)
  1947. {
  1948. return o->h_count;
  1949. }
  1950. static PyHamtObject *
  1951. hamt_alloc(void)
  1952. {
  1953. PyHamtObject *o;
  1954. o = PyObject_GC_New(PyHamtObject, &_PyHamt_Type);
  1955. if (o == NULL) {
  1956. return NULL;
  1957. }
  1958. o->h_count = 0;
  1959. o->h_root = NULL;
  1960. o->h_weakreflist = NULL;
  1961. PyObject_GC_Track(o);
  1962. return o;
  1963. }
  1964. PyHamtObject *
  1965. _PyHamt_New(void)
  1966. {
  1967. if (_empty_hamt != NULL) {
  1968. /* HAMT is an immutable object so we can easily cache an
  1969. empty instance. */
  1970. Py_INCREF(_empty_hamt);
  1971. return _empty_hamt;
  1972. }
  1973. PyHamtObject *o = hamt_alloc();
  1974. if (o == NULL) {
  1975. return NULL;
  1976. }
  1977. o->h_root = hamt_node_bitmap_new(0);
  1978. if (o->h_root == NULL) {
  1979. Py_DECREF(o);
  1980. return NULL;
  1981. }
  1982. o->h_count = 0;
  1983. if (_empty_hamt == NULL) {
  1984. Py_INCREF(o);
  1985. _empty_hamt = o;
  1986. }
  1987. return o;
  1988. }
  1989. #ifdef Py_DEBUG
  1990. static PyObject *
  1991. hamt_dump(PyHamtObject *self)
  1992. {
  1993. _PyUnicodeWriter writer;
  1994. _PyUnicodeWriter_Init(&writer);
  1995. if (_hamt_dump_format(&writer, "HAMT(len=%zd):\n", self->h_count)) {
  1996. goto error;
  1997. }
  1998. if (hamt_node_dump(self->h_root, &writer, 0)) {
  1999. goto error;
  2000. }
  2001. return _PyUnicodeWriter_Finish(&writer);
  2002. error:
  2003. _PyUnicodeWriter_Dealloc(&writer);
  2004. return NULL;
  2005. }
  2006. #endif /* Py_DEBUG */
  2007. /////////////////////////////////// Iterators: Shared Iterator Implementation
  2008. static int
  2009. hamt_baseiter_tp_clear(PyHamtIterator *it)
  2010. {
  2011. Py_CLEAR(it->hi_obj);
  2012. return 0;
  2013. }
  2014. static void
  2015. hamt_baseiter_tp_dealloc(PyHamtIterator *it)
  2016. {
  2017. PyObject_GC_UnTrack(it);
  2018. (void)hamt_baseiter_tp_clear(it);
  2019. PyObject_GC_Del(it);
  2020. }
  2021. static int
  2022. hamt_baseiter_tp_traverse(PyHamtIterator *it, visitproc visit, void *arg)
  2023. {
  2024. Py_VISIT(it->hi_obj);
  2025. return 0;
  2026. }
  2027. static PyObject *
  2028. hamt_baseiter_tp_iternext(PyHamtIterator *it)
  2029. {
  2030. PyObject *key;
  2031. PyObject *val;
  2032. hamt_iter_t res = hamt_iterator_next(&it->hi_iter, &key, &val);
  2033. switch (res) {
  2034. case I_END:
  2035. PyErr_SetNone(PyExc_StopIteration);
  2036. return NULL;
  2037. case I_ITEM: {
  2038. return (*(it->hi_yield))(key, val);
  2039. }
  2040. default: {
  2041. Py_UNREACHABLE();
  2042. }
  2043. }
  2044. }
  2045. static Py_ssize_t
  2046. hamt_baseiter_tp_len(PyHamtIterator *it)
  2047. {
  2048. return it->hi_obj->h_count;
  2049. }
  2050. static PyMappingMethods PyHamtIterator_as_mapping = {
  2051. (lenfunc)hamt_baseiter_tp_len,
  2052. };
  2053. static PyObject *
  2054. hamt_baseiter_new(PyTypeObject *type, binaryfunc yield, PyHamtObject *o)
  2055. {
  2056. PyHamtIterator *it = PyObject_GC_New(PyHamtIterator, type);
  2057. if (it == NULL) {
  2058. return NULL;
  2059. }
  2060. Py_INCREF(o);
  2061. it->hi_obj = o;
  2062. it->hi_yield = yield;
  2063. hamt_iterator_init(&it->hi_iter, o->h_root);
  2064. return (PyObject*)it;
  2065. }
  2066. #define ITERATOR_TYPE_SHARED_SLOTS \
  2067. .tp_basicsize = sizeof(PyHamtIterator), \
  2068. .tp_itemsize = 0, \
  2069. .tp_as_mapping = &PyHamtIterator_as_mapping, \
  2070. .tp_dealloc = (destructor)hamt_baseiter_tp_dealloc, \
  2071. .tp_getattro = PyObject_GenericGetAttr, \
  2072. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, \
  2073. .tp_traverse = (traverseproc)hamt_baseiter_tp_traverse, \
  2074. .tp_clear = (inquiry)hamt_baseiter_tp_clear, \
  2075. .tp_iter = PyObject_SelfIter, \
  2076. .tp_iternext = (iternextfunc)hamt_baseiter_tp_iternext,
  2077. /////////////////////////////////// _PyHamtItems_Type
  2078. PyTypeObject _PyHamtItems_Type = {
  2079. PyVarObject_HEAD_INIT(NULL, 0)
  2080. "items",
  2081. ITERATOR_TYPE_SHARED_SLOTS
  2082. };
  2083. static PyObject *
  2084. hamt_iter_yield_items(PyObject *key, PyObject *val)
  2085. {
  2086. return PyTuple_Pack(2, key, val);
  2087. }
  2088. PyObject *
  2089. _PyHamt_NewIterItems(PyHamtObject *o)
  2090. {
  2091. return hamt_baseiter_new(
  2092. &_PyHamtItems_Type, hamt_iter_yield_items, o);
  2093. }
  2094. /////////////////////////////////// _PyHamtKeys_Type
  2095. PyTypeObject _PyHamtKeys_Type = {
  2096. PyVarObject_HEAD_INIT(NULL, 0)
  2097. "keys",
  2098. ITERATOR_TYPE_SHARED_SLOTS
  2099. };
  2100. static PyObject *
  2101. hamt_iter_yield_keys(PyObject *key, PyObject *val)
  2102. {
  2103. Py_INCREF(key);
  2104. return key;
  2105. }
  2106. PyObject *
  2107. _PyHamt_NewIterKeys(PyHamtObject *o)
  2108. {
  2109. return hamt_baseiter_new(
  2110. &_PyHamtKeys_Type, hamt_iter_yield_keys, o);
  2111. }
  2112. /////////////////////////////////// _PyHamtValues_Type
  2113. PyTypeObject _PyHamtValues_Type = {
  2114. PyVarObject_HEAD_INIT(NULL, 0)
  2115. "values",
  2116. ITERATOR_TYPE_SHARED_SLOTS
  2117. };
  2118. static PyObject *
  2119. hamt_iter_yield_values(PyObject *key, PyObject *val)
  2120. {
  2121. Py_INCREF(val);
  2122. return val;
  2123. }
  2124. PyObject *
  2125. _PyHamt_NewIterValues(PyHamtObject *o)
  2126. {
  2127. return hamt_baseiter_new(
  2128. &_PyHamtValues_Type, hamt_iter_yield_values, o);
  2129. }
  2130. /////////////////////////////////// _PyHamt_Type
  2131. #ifdef Py_DEBUG
  2132. static PyObject *
  2133. hamt_dump(PyHamtObject *self);
  2134. #endif
  2135. static PyObject *
  2136. hamt_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  2137. {
  2138. return (PyObject*)_PyHamt_New();
  2139. }
  2140. static int
  2141. hamt_tp_clear(PyHamtObject *self)
  2142. {
  2143. Py_CLEAR(self->h_root);
  2144. return 0;
  2145. }
  2146. static int
  2147. hamt_tp_traverse(PyHamtObject *self, visitproc visit, void *arg)
  2148. {
  2149. Py_VISIT(self->h_root);
  2150. return 0;
  2151. }
  2152. static void
  2153. hamt_tp_dealloc(PyHamtObject *self)
  2154. {
  2155. PyObject_GC_UnTrack(self);
  2156. if (self->h_weakreflist != NULL) {
  2157. PyObject_ClearWeakRefs((PyObject*)self);
  2158. }
  2159. (void)hamt_tp_clear(self);
  2160. Py_TYPE(self)->tp_free(self);
  2161. }
  2162. static PyObject *
  2163. hamt_tp_richcompare(PyObject *v, PyObject *w, int op)
  2164. {
  2165. if (!PyHamt_Check(v) || !PyHamt_Check(w) || (op != Py_EQ && op != Py_NE)) {
  2166. Py_RETURN_NOTIMPLEMENTED;
  2167. }
  2168. int res = _PyHamt_Eq((PyHamtObject *)v, (PyHamtObject *)w);
  2169. if (res < 0) {
  2170. return NULL;
  2171. }
  2172. if (op == Py_NE) {
  2173. res = !res;
  2174. }
  2175. if (res) {
  2176. Py_RETURN_TRUE;
  2177. }
  2178. else {
  2179. Py_RETURN_FALSE;
  2180. }
  2181. }
  2182. static int
  2183. hamt_tp_contains(PyHamtObject *self, PyObject *key)
  2184. {
  2185. PyObject *val;
  2186. return _PyHamt_Find(self, key, &val);
  2187. }
  2188. static PyObject *
  2189. hamt_tp_subscript(PyHamtObject *self, PyObject *key)
  2190. {
  2191. PyObject *val;
  2192. hamt_find_t res = hamt_find(self, key, &val);
  2193. switch (res) {
  2194. case F_ERROR:
  2195. return NULL;
  2196. case F_FOUND:
  2197. Py_INCREF(val);
  2198. return val;
  2199. case F_NOT_FOUND:
  2200. PyErr_SetObject(PyExc_KeyError, key);
  2201. return NULL;
  2202. default:
  2203. Py_UNREACHABLE();
  2204. }
  2205. }
  2206. static Py_ssize_t
  2207. hamt_tp_len(PyHamtObject *self)
  2208. {
  2209. return _PyHamt_Len(self);
  2210. }
  2211. static PyObject *
  2212. hamt_tp_iter(PyHamtObject *self)
  2213. {
  2214. return _PyHamt_NewIterKeys(self);
  2215. }
  2216. static PyObject *
  2217. hamt_py_set(PyHamtObject *self, PyObject *args)
  2218. {
  2219. PyObject *key;
  2220. PyObject *val;
  2221. if (!PyArg_UnpackTuple(args, "set", 2, 2, &key, &val)) {
  2222. return NULL;
  2223. }
  2224. return (PyObject *)_PyHamt_Assoc(self, key, val);
  2225. }
  2226. static PyObject *
  2227. hamt_py_get(PyHamtObject *self, PyObject *args)
  2228. {
  2229. PyObject *key;
  2230. PyObject *def = NULL;
  2231. if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &def)) {
  2232. return NULL;
  2233. }
  2234. PyObject *val = NULL;
  2235. hamt_find_t res = hamt_find(self, key, &val);
  2236. switch (res) {
  2237. case F_ERROR:
  2238. return NULL;
  2239. case F_FOUND:
  2240. Py_INCREF(val);
  2241. return val;
  2242. case F_NOT_FOUND:
  2243. if (def == NULL) {
  2244. Py_RETURN_NONE;
  2245. }
  2246. Py_INCREF(def);
  2247. return def;
  2248. default:
  2249. Py_UNREACHABLE();
  2250. }
  2251. }
  2252. static PyObject *
  2253. hamt_py_delete(PyHamtObject *self, PyObject *key)
  2254. {
  2255. return (PyObject *)_PyHamt_Without(self, key);
  2256. }
  2257. static PyObject *
  2258. hamt_py_items(PyHamtObject *self, PyObject *args)
  2259. {
  2260. return _PyHamt_NewIterItems(self);
  2261. }
  2262. static PyObject *
  2263. hamt_py_values(PyHamtObject *self, PyObject *args)
  2264. {
  2265. return _PyHamt_NewIterValues(self);
  2266. }
  2267. static PyObject *
  2268. hamt_py_keys(PyHamtObject *self, PyObject *args)
  2269. {
  2270. return _PyHamt_NewIterKeys(self);
  2271. }
  2272. #ifdef Py_DEBUG
  2273. static PyObject *
  2274. hamt_py_dump(PyHamtObject *self, PyObject *args)
  2275. {
  2276. return hamt_dump(self);
  2277. }
  2278. #endif
  2279. static PyMethodDef PyHamt_methods[] = {
  2280. {"set", (PyCFunction)hamt_py_set, METH_VARARGS, NULL},
  2281. {"get", (PyCFunction)hamt_py_get, METH_VARARGS, NULL},
  2282. {"delete", (PyCFunction)hamt_py_delete, METH_O, NULL},
  2283. {"items", (PyCFunction)hamt_py_items, METH_NOARGS, NULL},
  2284. {"keys", (PyCFunction)hamt_py_keys, METH_NOARGS, NULL},
  2285. {"values", (PyCFunction)hamt_py_values, METH_NOARGS, NULL},
  2286. #ifdef Py_DEBUG
  2287. {"__dump__", (PyCFunction)hamt_py_dump, METH_NOARGS, NULL},
  2288. #endif
  2289. {NULL, NULL}
  2290. };
  2291. static PySequenceMethods PyHamt_as_sequence = {
  2292. 0, /* sq_length */
  2293. 0, /* sq_concat */
  2294. 0, /* sq_repeat */
  2295. 0, /* sq_item */
  2296. 0, /* sq_slice */
  2297. 0, /* sq_ass_item */
  2298. 0, /* sq_ass_slice */
  2299. (objobjproc)hamt_tp_contains, /* sq_contains */
  2300. 0, /* sq_inplace_concat */
  2301. 0, /* sq_inplace_repeat */
  2302. };
  2303. static PyMappingMethods PyHamt_as_mapping = {
  2304. (lenfunc)hamt_tp_len, /* mp_length */
  2305. (binaryfunc)hamt_tp_subscript, /* mp_subscript */
  2306. };
  2307. PyTypeObject _PyHamt_Type = {
  2308. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  2309. "hamt",
  2310. sizeof(PyHamtObject),
  2311. .tp_methods = PyHamt_methods,
  2312. .tp_as_mapping = &PyHamt_as_mapping,
  2313. .tp_as_sequence = &PyHamt_as_sequence,
  2314. .tp_iter = (getiterfunc)hamt_tp_iter,
  2315. .tp_dealloc = (destructor)hamt_tp_dealloc,
  2316. .tp_getattro = PyObject_GenericGetAttr,
  2317. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
  2318. .tp_richcompare = hamt_tp_richcompare,
  2319. .tp_traverse = (traverseproc)hamt_tp_traverse,
  2320. .tp_clear = (inquiry)hamt_tp_clear,
  2321. .tp_new = hamt_tp_new,
  2322. .tp_weaklistoffset = offsetof(PyHamtObject, h_weakreflist),
  2323. .tp_hash = PyObject_HashNotImplemented,
  2324. };
  2325. /////////////////////////////////// Tree Node Types
  2326. PyTypeObject _PyHamt_ArrayNode_Type = {
  2327. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  2328. "hamt_array_node",
  2329. sizeof(PyHamtNode_Array),
  2330. 0,
  2331. .tp_dealloc = (destructor)hamt_node_array_dealloc,
  2332. .tp_getattro = PyObject_GenericGetAttr,
  2333. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
  2334. .tp_traverse = (traverseproc)hamt_node_array_traverse,
  2335. .tp_free = PyObject_GC_Del,
  2336. .tp_hash = PyObject_HashNotImplemented,
  2337. };
  2338. PyTypeObject _PyHamt_BitmapNode_Type = {
  2339. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  2340. "hamt_bitmap_node",
  2341. sizeof(PyHamtNode_Bitmap) - sizeof(PyObject *),
  2342. sizeof(PyObject *),
  2343. .tp_dealloc = (destructor)hamt_node_bitmap_dealloc,
  2344. .tp_getattro = PyObject_GenericGetAttr,
  2345. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
  2346. .tp_traverse = (traverseproc)hamt_node_bitmap_traverse,
  2347. .tp_free = PyObject_GC_Del,
  2348. .tp_hash = PyObject_HashNotImplemented,
  2349. };
  2350. PyTypeObject _PyHamt_CollisionNode_Type = {
  2351. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  2352. "hamt_collision_node",
  2353. sizeof(PyHamtNode_Collision) - sizeof(PyObject *),
  2354. sizeof(PyObject *),
  2355. .tp_dealloc = (destructor)hamt_node_collision_dealloc,
  2356. .tp_getattro = PyObject_GenericGetAttr,
  2357. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
  2358. .tp_traverse = (traverseproc)hamt_node_collision_traverse,
  2359. .tp_free = PyObject_GC_Del,
  2360. .tp_hash = PyObject_HashNotImplemented,
  2361. };
  2362. int
  2363. _PyHamt_Init(void)
  2364. {
  2365. if ((PyType_Ready(&_PyHamt_Type) < 0) ||
  2366. (PyType_Ready(&_PyHamt_ArrayNode_Type) < 0) ||
  2367. (PyType_Ready(&_PyHamt_BitmapNode_Type) < 0) ||
  2368. (PyType_Ready(&_PyHamt_CollisionNode_Type) < 0) ||
  2369. (PyType_Ready(&_PyHamtKeys_Type) < 0) ||
  2370. (PyType_Ready(&_PyHamtValues_Type) < 0) ||
  2371. (PyType_Ready(&_PyHamtItems_Type) < 0))
  2372. {
  2373. return 0;
  2374. }
  2375. return 1;
  2376. }
  2377. void
  2378. _PyHamt_Fini(void)
  2379. {
  2380. Py_CLEAR(_empty_hamt);
  2381. Py_CLEAR(_empty_bitmap_node);
  2382. }