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.

2995 lines
79 KiB

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