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.

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