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.

2438 lines
77 KiB

10 years ago
  1. /* Ordered Dictionary object implementation.
  2. This implementation is necessarily explicitly equivalent to the pure Python
  3. OrderedDict class in Lib/collections/__init__.py. The strategy there
  4. involves using a doubly-linked-list to capture the order. We keep to that
  5. strategy, using a lower-level linked-list.
  6. About the Linked-List
  7. =====================
  8. For the linked list we use a basic doubly-linked-list. Using a circularly-
  9. linked-list does have some benefits, but they don't apply so much here
  10. since OrderedDict is focused on the ends of the list (for the most part).
  11. Furthermore, there are some features of generic linked-lists that we simply
  12. don't need for OrderedDict. Thus a simple custom implementation meets our
  13. needs. Alternatives to our simple approach include the QCIRCLE_*
  14. macros from BSD's queue.h, and the linux's list.h.
  15. Getting O(1) Node Lookup
  16. ------------------------
  17. One invariant of Python's OrderedDict is that it preserves time complexity
  18. of dict's methods, particularly the O(1) operations. Simply adding a
  19. linked-list on top of dict is not sufficient here; operations for nodes in
  20. the middle of the linked-list implicitly require finding the node first.
  21. With a simple linked-list like we're using, that is an O(n) operation.
  22. Consequently, methods like __delitem__() would change from O(1) to O(n),
  23. which is unacceptable.
  24. In order to preserve O(1) performance for node removal (finding nodes), we
  25. must do better than just looping through the linked-list. Here are options
  26. we've considered:
  27. 1. use a second dict to map keys to nodes (a la the pure Python version).
  28. 2. keep a simple hash table mirroring the order of dict's, mapping each key
  29. to the corresponding node in the linked-list.
  30. 3. use a version of shared keys (split dict) that allows non-unicode keys.
  31. 4. have the value stored for each key be a (value, node) pair, and adjust
  32. __getitem__(), get(), etc. accordingly.
  33. The approach with the least performance impact (time and space) is #2,
  34. mirroring the key order of dict's dk_entries with an array of node pointers.
  35. While lookdict() and friends (dk_lookup) don't give us the index into the
  36. array, we make use of pointer arithmetic to get that index. An alternative
  37. would be to refactor lookdict() to provide the index, explicitly exposing
  38. the implementation detail. We could even just use a custom lookup function
  39. for OrderedDict that facilitates our need. However, both approaches are
  40. significantly more complicated than just using pointer arithmetic.
  41. The catch with mirroring the hash table ordering is that we have to keep
  42. the ordering in sync through any dict resizes. However, that order only
  43. matters during node lookup. We can simply defer any potential resizing
  44. until we need to do a lookup.
  45. Linked-List Nodes
  46. -----------------
  47. The current implementation stores a pointer to the associated key only.
  48. One alternative would be to store a pointer to the PyDictKeyEntry instead.
  49. This would save one pointer de-reference per item, which is nice during
  50. calls to values() and items(). However, it adds unnecessary overhead
  51. otherwise, so we stick with just the key.
  52. Linked-List API
  53. ---------------
  54. As noted, the linked-list implemented here does not have all the bells and
  55. whistles. However, we recognize that the implementation may need to
  56. change to accommodate performance improvements or extra functionality. To
  57. that end, We use a simple API to interact with the linked-list. Here's a
  58. summary of the methods/macros:
  59. Node info:
  60. * _odictnode_KEY(node)
  61. * _odictnode_VALUE(od, node)
  62. * _odictnode_PREV(node)
  63. * _odictnode_NEXT(node)
  64. Linked-List info:
  65. * _odict_FIRST(od)
  66. * _odict_LAST(od)
  67. * _odict_EMPTY(od)
  68. * _odict_FOREACH(od, node) - used in place of `for (node=...)`
  69. For adding nodes:
  70. * _odict_add_head(od, node)
  71. * _odict_add_tail(od, node)
  72. * _odict_add_new_node(od, key, hash)
  73. For removing nodes:
  74. * _odict_clear_node(od, node, key, hash)
  75. * _odict_clear_nodes(od, clear_each)
  76. Others:
  77. * _odict_find_node_hash(od, key, hash)
  78. * _odict_find_node(od, key)
  79. * _odict_keys_equal(od1, od2)
  80. Used, but specific to the linked-list implementation:
  81. * _odict_free_fast_nodes(od)
  82. And here's a look at how the linked-list relates to the OrderedDict API:
  83. ============ === === ==== ==== ==== === ==== ===== ==== ==== === ==== === ===
  84. method key val prev next mem 1st last empty iter find add rmv clr keq
  85. ============ === === ==== ==== ==== === ==== ===== ==== ==== === ==== === ===
  86. __del__ ~ X
  87. __delitem__ free ~ node
  88. __eq__ ~ X
  89. __iter__ X X
  90. __new__ X X
  91. __reduce__ X ~ X
  92. __repr__ X X X
  93. __reversed__ X X
  94. __setitem__ key
  95. __sizeof__ size X
  96. clear ~ ~ X
  97. copy X X X
  98. items X X X
  99. keys X X
  100. move_to_end X X X ~ h/t key
  101. pop free key
  102. popitem X X free X X node
  103. setdefault ~ ? ~
  104. values X X
  105. ============ === === ==== ==== ==== === ==== ===== ==== ==== === ==== === ===
  106. __delitem__ is the only method that directly relies on finding an arbitrary
  107. node in the linked-list. Everything else is iteration or relates to the
  108. ends of the linked-list.
  109. Situation that Endangers Consistency
  110. ------------------------------------
  111. Using a raw linked-list for OrderedDict exposes a key situation that can
  112. cause problems. If a node is stored in a variable, there is a chance that
  113. the node may have been deallocated before the variable gets used, thus
  114. potentially leading to a segmentation fault. A key place where this shows
  115. up is during iteration through the linked list (via _odict_FOREACH or
  116. otherwise).
  117. A number of solutions are available to resolve this situation:
  118. * defer looking up the node until as late as possible and certainly after
  119. any code that could possibly result in a deletion;
  120. * if the node is needed both before and after a point where the node might
  121. be removed, do a check before using the node at the "after" location to
  122. see if the node is still valid;
  123. * like the last one, but simply pull the node again to ensure it's right;
  124. * keep the key in the variable instead of the node and then look up the
  125. node using the key at the point where the node is needed (this is what
  126. we do for the iterators).
  127. Another related problem, preserving consistent ordering during iteration,
  128. is described below. That one is not exclusive to using linked-lists.
  129. Challenges from Subclassing dict
  130. ================================
  131. OrderedDict subclasses dict, which is an unusual relationship between two
  132. builtin types (other than the base object type). Doing so results in
  133. some complication and deserves further explanation. There are two things
  134. to consider here. First, in what circumstances or with what adjustments
  135. can OrderedDict be used as a drop-in replacement for dict (at the C level)?
  136. Second, how can the OrderedDict implementation leverage the dict
  137. implementation effectively without introducing unnecessary coupling or
  138. inefficiencies?
  139. This second point is reflected here and in the implementation, so the
  140. further focus is on the first point. It is worth noting that for
  141. overridden methods, the dict implementation is deferred to as much as
  142. possible. Furthermore, coupling is limited to as little as is reasonable.
  143. Concrete API Compatibility
  144. --------------------------
  145. Use of the concrete C-API for dict (PyDict_*) with OrderedDict is
  146. problematic. (See http://bugs.python.org/issue10977.) The concrete API
  147. has a number of hard-coded assumptions tied to the dict implementation.
  148. This is, in part, due to performance reasons, which is understandable
  149. given the part dict plays in Python.
  150. Any attempt to replace dict with OrderedDict for any role in the
  151. interpreter (e.g. **kwds) faces a challenge. Such any effort must
  152. recognize that the instances in affected locations currently interact with
  153. the concrete API.
  154. Here are some ways to address this challenge:
  155. 1. Change the relevant usage of the concrete API in CPython and add
  156. PyDict_CheckExact() calls to each of the concrete API functions.
  157. 2. Adjust the relevant concrete API functions to explicitly accommodate
  158. OrderedDict.
  159. 3. As with #1, add the checks, but improve the abstract API with smart fast
  160. paths for dict and OrderedDict, and refactor CPython to use the abstract
  161. API. Improvements to the abstract API would be valuable regardless.
  162. Adding the checks to the concrete API would help make any interpreter
  163. switch to OrderedDict less painful for extension modules. However, this
  164. won't work. The equivalent C API call to `dict.__setitem__(obj, k, v)`
  165. is 'PyDict_SetItem(obj, k, v)`. This illustrates how subclasses in C call
  166. the base class's methods, since there is no equivalent of super() in the
  167. C API. Calling into Python for parent class API would work, but some
  168. extension modules already rely on this feature of the concrete API.
  169. For reference, here is a breakdown of some of the dict concrete API:
  170. ========================== ============= =======================
  171. concrete API uses abstract API
  172. ========================== ============= =======================
  173. PyDict_Check PyMapping_Check
  174. (PyDict_CheckExact) -
  175. (PyDict_New) -
  176. (PyDictProxy_New) -
  177. PyDict_Clear -
  178. PyDict_Contains PySequence_Contains
  179. PyDict_Copy -
  180. PyDict_SetItem PyObject_SetItem
  181. PyDict_SetItemString PyMapping_SetItemString
  182. PyDict_DelItem PyMapping_DelItem
  183. PyDict_DelItemString PyMapping_DelItemString
  184. PyDict_GetItem -
  185. PyDict_GetItemWithError PyObject_GetItem
  186. _PyDict_GetItemIdWithError -
  187. PyDict_GetItemString PyMapping_GetItemString
  188. PyDict_Items PyMapping_Items
  189. PyDict_Keys PyMapping_Keys
  190. PyDict_Values PyMapping_Values
  191. PyDict_Size PyMapping_Size
  192. PyMapping_Length
  193. PyDict_Next PyIter_Next
  194. _PyDict_Next -
  195. PyDict_Merge -
  196. PyDict_Update -
  197. PyDict_MergeFromSeq2 -
  198. PyDict_ClearFreeList -
  199. - PyMapping_HasKeyString
  200. - PyMapping_HasKey
  201. ========================== ============= =======================
  202. The dict Interface Relative to OrderedDict
  203. ==========================================
  204. Since OrderedDict subclasses dict, understanding the various methods and
  205. attributes of dict is important for implementing OrderedDict.
  206. Relevant Type Slots
  207. -------------------
  208. ================= ================ =================== ================
  209. slot attribute object dict
  210. ================= ================ =================== ================
  211. tp_dealloc - object_dealloc dict_dealloc
  212. tp_repr __repr__ object_repr dict_repr
  213. sq_contains __contains__ - dict_contains
  214. mp_length __len__ - dict_length
  215. mp_subscript __getitem__ - dict_subscript
  216. mp_ass_subscript __setitem__ - dict_ass_sub
  217. __delitem__
  218. tp_hash __hash__ _Py_HashPointer ..._HashNotImpl
  219. tp_str __str__ object_str -
  220. tp_getattro __getattribute__ ..._GenericGetAttr (repeated)
  221. __getattr__
  222. tp_setattro __setattr__ ..._GenericSetAttr (disabled)
  223. tp_doc __doc__ (literal) dictionary_doc
  224. tp_traverse - - dict_traverse
  225. tp_clear - - dict_tp_clear
  226. tp_richcompare __eq__ object_richcompare dict_richcompare
  227. __ne__
  228. tp_weaklistoffset (__weakref__) - -
  229. tp_iter __iter__ - dict_iter
  230. tp_dictoffset (__dict__) - -
  231. tp_init __init__ object_init dict_init
  232. tp_alloc - PyType_GenericAlloc (repeated)
  233. tp_new __new__ object_new dict_new
  234. tp_free - PyObject_Del PyObject_GC_Del
  235. ================= ================ =================== ================
  236. Relevant Methods
  237. ----------------
  238. ================ =================== ===============
  239. method object dict
  240. ================ =================== ===============
  241. __reduce__ object_reduce -
  242. __sizeof__ object_sizeof dict_sizeof
  243. clear - dict_clear
  244. copy - dict_copy
  245. fromkeys - dict_fromkeys
  246. get - dict_get
  247. items - dictitems_new
  248. keys - dictkeys_new
  249. pop - dict_pop
  250. popitem - dict_popitem
  251. setdefault - dict_setdefault
  252. update - dict_update
  253. values - dictvalues_new
  254. ================ =================== ===============
  255. Pure Python OrderedDict
  256. =======================
  257. As already noted, compatibility with the pure Python OrderedDict
  258. implementation is a key goal of this C implementation. To further that
  259. goal, here's a summary of how OrderedDict-specific methods are implemented
  260. in collections/__init__.py. Also provided is an indication of which
  261. methods directly mutate or iterate the object, as well as any relationship
  262. with the underlying linked-list.
  263. ============= ============== == ================ === === ====
  264. method impl used ll uses inq mut iter
  265. ============= ============== == ================ === === ====
  266. __contains__ dict - - X
  267. __delitem__ OrderedDict Y dict.__delitem__ X
  268. __eq__ OrderedDict N OrderedDict ~
  269. dict.__eq__
  270. __iter__
  271. __getitem__ dict - - X
  272. __iter__ OrderedDict Y - X
  273. __init__ OrderedDict N update
  274. __len__ dict - - X
  275. __ne__ MutableMapping - __eq__ ~
  276. __reduce__ OrderedDict N OrderedDict ~
  277. __iter__
  278. __getitem__
  279. __repr__ OrderedDict N __class__ ~
  280. items
  281. __reversed__ OrderedDict Y - X
  282. __setitem__ OrderedDict Y __contains__ X
  283. dict.__setitem__
  284. __sizeof__ OrderedDict Y __len__ ~
  285. __dict__
  286. clear OrderedDict Y dict.clear X
  287. copy OrderedDict N __class__
  288. __init__
  289. fromkeys OrderedDict N __setitem__
  290. get dict - - ~
  291. items MutableMapping - ItemsView X
  292. keys MutableMapping - KeysView X
  293. move_to_end OrderedDict Y - X
  294. pop OrderedDict N __contains__ X
  295. __getitem__
  296. __delitem__
  297. popitem OrderedDict Y dict.pop X
  298. setdefault OrderedDict N __contains__ ~
  299. __getitem__
  300. __setitem__
  301. update MutableMapping - __setitem__ ~
  302. values MutableMapping - ValuesView X
  303. ============= ============== == ================ === === ====
  304. __reversed__ and move_to_end are both exclusive to OrderedDict.
  305. C OrderedDict Implementation
  306. ============================
  307. ================= ================
  308. slot impl
  309. ================= ================
  310. tp_dealloc odict_dealloc
  311. tp_repr odict_repr
  312. mp_ass_subscript odict_ass_sub
  313. tp_doc odict_doc
  314. tp_traverse odict_traverse
  315. tp_clear odict_tp_clear
  316. tp_richcompare odict_richcompare
  317. tp_weaklistoffset (offset)
  318. tp_iter odict_iter
  319. tp_dictoffset (offset)
  320. tp_init odict_init
  321. tp_alloc (repeated)
  322. tp_new odict_new
  323. ================= ================
  324. ================= ================
  325. method impl
  326. ================= ================
  327. __reduce__ odict_reduce
  328. __sizeof__ odict_sizeof
  329. clear odict_clear
  330. copy odict_copy
  331. fromkeys odict_fromkeys
  332. items odictitems_new
  333. keys odictkeys_new
  334. pop odict_pop
  335. popitem odict_popitem
  336. setdefault odict_setdefault
  337. update odict_update
  338. values odictvalues_new
  339. ================= ================
  340. Inherited unchanged from object/dict:
  341. ================ ==========================
  342. method type field
  343. ================ ==========================
  344. - tp_free
  345. __contains__ tp_as_sequence.sq_contains
  346. __getattr__ tp_getattro
  347. __getattribute__ tp_getattro
  348. __getitem__ tp_as_mapping.mp_subscript
  349. __hash__ tp_hash
  350. __len__ tp_as_mapping.mp_length
  351. __setattr__ tp_setattro
  352. __str__ tp_str
  353. get -
  354. ================ ==========================
  355. Other Challenges
  356. ================
  357. Preserving Ordering During Iteration
  358. ------------------------------------
  359. During iteration through an OrderedDict, it is possible that items could
  360. get added, removed, or reordered. For a linked-list implementation, as
  361. with some other implementations, that situation may lead to undefined
  362. behavior. The documentation for dict mentions this in the `iter()` section
  363. of http://docs.python.org/3.4/library/stdtypes.html#dictionary-view-objects.
  364. In this implementation we follow dict's lead (as does the pure Python
  365. implementation) for __iter__(), keys(), values(), and items().
  366. For internal iteration (using _odict_FOREACH or not), there is still the
  367. risk that not all nodes that we expect to be seen in the loop actually get
  368. seen. Thus, we are careful in each of those places to ensure that they
  369. are. This comes, of course, at a small price at each location. The
  370. solutions are much the same as those detailed in the `Situation that
  371. Endangers Consistency` section above.
  372. Potential Optimizations
  373. =======================
  374. * Allocate the nodes as a block via od_fast_nodes instead of individually.
  375. - Set node->key to NULL to indicate the node is not-in-use.
  376. - Add _odict_EXISTS()?
  377. - How to maintain consistency across resizes? Existing node pointers
  378. would be invalidate after a resize, which is particularly problematic
  379. for the iterators.
  380. * Use a more stream-lined implementation of update() and, likely indirectly,
  381. __init__().
  382. */
  383. /* TODO
  384. sooner:
  385. - reentrancy (make sure everything is at a thread-safe state when calling
  386. into Python). I've already checked this multiple times, but want to
  387. make one more pass.
  388. - add unit tests for reentrancy?
  389. later:
  390. - make the dict views support the full set API (the pure Python impl does)
  391. - implement a fuller MutableMapping API in C?
  392. - move the MutableMapping implementation to abstract.c?
  393. - optimize mutablemapping_update
  394. - use PyObject_MALLOC (small object allocator) for odict nodes?
  395. - support subclasses better (e.g. in odict_richcompare)
  396. */
  397. #include "Python.h"
  398. #include "structmember.h"
  399. #include "dict-common.h"
  400. #include <stddef.h>
  401. typedef struct _odictnode _ODictNode;
  402. /* PyODictObject */
  403. struct _odictobject {
  404. PyDictObject od_dict; /* the underlying dict */
  405. _ODictNode *od_first; /* first node in the linked list, if any */
  406. _ODictNode *od_last; /* last node in the linked list, if any */
  407. /* od_fast_nodes, od_fast_nodes_size and od_resize_sentinel are managed
  408. * by _odict_resize().
  409. * Note that we rely on implementation details of dict for both. */
  410. _ODictNode **od_fast_nodes; /* hash table that mirrors the dict table */
  411. Py_ssize_t od_fast_nodes_size;
  412. void *od_resize_sentinel; /* changes if odict should be resized */
  413. size_t od_state; /* incremented whenever the LL changes */
  414. PyObject *od_inst_dict; /* OrderedDict().__dict__ */
  415. PyObject *od_weakreflist; /* holds weakrefs to the odict */
  416. };
  417. /* ----------------------------------------------
  418. * odict keys (a simple doubly-linked list)
  419. */
  420. struct _odictnode {
  421. PyObject *key;
  422. Py_hash_t hash;
  423. _ODictNode *next;
  424. _ODictNode *prev;
  425. };
  426. #define _odictnode_KEY(node) \
  427. (node->key)
  428. #define _odictnode_HASH(node) \
  429. (node->hash)
  430. /* borrowed reference */
  431. #define _odictnode_VALUE(node, od) \
  432. PyODict_GetItemWithError((PyObject *)od, _odictnode_KEY(node))
  433. #define _odictnode_PREV(node) (node->prev)
  434. #define _odictnode_NEXT(node) (node->next)
  435. #define _odict_FIRST(od) (((PyODictObject *)od)->od_first)
  436. #define _odict_LAST(od) (((PyODictObject *)od)->od_last)
  437. #define _odict_EMPTY(od) (_odict_FIRST(od) == NULL)
  438. #define _odict_FOREACH(od, node) \
  439. for (node = _odict_FIRST(od); node != NULL; node = _odictnode_NEXT(node))
  440. #define _odict_FAST_SIZE(od) ((PyDictObject *)od)->ma_keys->dk_size
  441. static void
  442. _odict_free_fast_nodes(PyODictObject *od) {
  443. if (od->od_fast_nodes) {
  444. PyMem_FREE(od->od_fast_nodes);
  445. }
  446. }
  447. /* Return the index into the hash table, regardless of a valid node. */
  448. static Py_ssize_t
  449. _odict_get_index_raw(PyODictObject *od, PyObject *key, Py_hash_t hash)
  450. {
  451. PyObject **value_addr = NULL;
  452. PyDictKeysObject *keys = ((PyDictObject *)od)->ma_keys;
  453. Py_ssize_t ix;
  454. ix = (keys->dk_lookup)((PyDictObject *)od, key, hash, &value_addr, NULL);
  455. if (ix == DKIX_EMPTY) {
  456. return keys->dk_nentries; /* index of new entry */
  457. }
  458. if (ix < 0)
  459. return -1;
  460. /* We use pointer arithmetic to get the entry's index into the table. */
  461. return ix;
  462. }
  463. /* Replace od->od_fast_nodes with a new table matching the size of dict's. */
  464. static int
  465. _odict_resize(PyODictObject *od) {
  466. Py_ssize_t size, i;
  467. _ODictNode **fast_nodes, *node;
  468. /* Initialize a new "fast nodes" table. */
  469. size = ((PyDictObject *)od)->ma_keys->dk_size;
  470. fast_nodes = PyMem_NEW(_ODictNode *, size);
  471. if (fast_nodes == NULL) {
  472. PyErr_NoMemory();
  473. return -1;
  474. }
  475. for (i = 0; i < size; i++)
  476. fast_nodes[i] = NULL;
  477. /* Copy the current nodes into the table. */
  478. _odict_FOREACH(od, node) {
  479. i = _odict_get_index_raw(od, _odictnode_KEY(node),
  480. _odictnode_HASH(node));
  481. if (i < 0) {
  482. PyMem_FREE(fast_nodes);
  483. return -1;
  484. }
  485. fast_nodes[i] = node;
  486. }
  487. /* Replace the old fast nodes table. */
  488. _odict_free_fast_nodes(od);
  489. od->od_fast_nodes = fast_nodes;
  490. od->od_fast_nodes_size = size;
  491. od->od_resize_sentinel = ((PyDictObject *)od)->ma_keys;
  492. return 0;
  493. }
  494. /* Return the index into the hash table, regardless of a valid node. */
  495. static Py_ssize_t
  496. _odict_get_index(PyODictObject *od, PyObject *key, Py_hash_t hash)
  497. {
  498. PyDictKeysObject *keys;
  499. assert(key != NULL);
  500. keys = ((PyDictObject *)od)->ma_keys;
  501. /* Ensure od_fast_nodes and dk_entries are in sync. */
  502. if (od->od_resize_sentinel != keys ||
  503. od->od_fast_nodes_size != keys->dk_size) {
  504. int resize_res = _odict_resize(od);
  505. if (resize_res < 0)
  506. return -1;
  507. }
  508. return _odict_get_index_raw(od, key, hash);
  509. }
  510. /* Returns NULL if there was some error or the key was not found. */
  511. static _ODictNode *
  512. _odict_find_node_hash(PyODictObject *od, PyObject *key, Py_hash_t hash)
  513. {
  514. Py_ssize_t index;
  515. if (_odict_EMPTY(od))
  516. return NULL;
  517. index = _odict_get_index(od, key, hash);
  518. if (index < 0)
  519. return NULL;
  520. return od->od_fast_nodes[index];
  521. }
  522. static _ODictNode *
  523. _odict_find_node(PyODictObject *od, PyObject *key)
  524. {
  525. Py_ssize_t index;
  526. Py_hash_t hash;
  527. if (_odict_EMPTY(od))
  528. return NULL;
  529. hash = PyObject_Hash(key);
  530. if (hash == -1)
  531. return NULL;
  532. index = _odict_get_index(od, key, hash);
  533. if (index < 0)
  534. return NULL;
  535. return od->od_fast_nodes[index];
  536. }
  537. static void
  538. _odict_add_head(PyODictObject *od, _ODictNode *node)
  539. {
  540. _odictnode_PREV(node) = NULL;
  541. _odictnode_NEXT(node) = _odict_FIRST(od);
  542. if (_odict_FIRST(od) == NULL)
  543. _odict_LAST(od) = node;
  544. else
  545. _odictnode_PREV(_odict_FIRST(od)) = node;
  546. _odict_FIRST(od) = node;
  547. od->od_state++;
  548. }
  549. static void
  550. _odict_add_tail(PyODictObject *od, _ODictNode *node)
  551. {
  552. _odictnode_PREV(node) = _odict_LAST(od);
  553. _odictnode_NEXT(node) = NULL;
  554. if (_odict_LAST(od) == NULL)
  555. _odict_FIRST(od) = node;
  556. else
  557. _odictnode_NEXT(_odict_LAST(od)) = node;
  558. _odict_LAST(od) = node;
  559. od->od_state++;
  560. }
  561. /* adds the node to the end of the list */
  562. static int
  563. _odict_add_new_node(PyODictObject *od, PyObject *key, Py_hash_t hash)
  564. {
  565. Py_ssize_t i;
  566. _ODictNode *node;
  567. Py_INCREF(key);
  568. i = _odict_get_index(od, key, hash);
  569. if (i < 0) {
  570. if (!PyErr_Occurred())
  571. PyErr_SetObject(PyExc_KeyError, key);
  572. Py_DECREF(key);
  573. return -1;
  574. }
  575. else if (od->od_fast_nodes[i] != NULL) {
  576. /* We already have a node for the key so there's no need to add one. */
  577. Py_DECREF(key);
  578. return 0;
  579. }
  580. /* must not be added yet */
  581. node = (_ODictNode *)PyMem_MALLOC(sizeof(_ODictNode));
  582. if (node == NULL) {
  583. Py_DECREF(key);
  584. PyErr_NoMemory();
  585. return -1;
  586. }
  587. _odictnode_KEY(node) = key;
  588. _odictnode_HASH(node) = hash;
  589. _odict_add_tail(od, node);
  590. od->od_fast_nodes[i] = node;
  591. return 0;
  592. }
  593. /* Putting the decref after the free causes problems. */
  594. #define _odictnode_DEALLOC(node) \
  595. do { \
  596. Py_DECREF(_odictnode_KEY(node)); \
  597. PyMem_FREE((void *)node); \
  598. } while (0)
  599. /* Repeated calls on the same node are no-ops. */
  600. static void
  601. _odict_remove_node(PyODictObject *od, _ODictNode *node)
  602. {
  603. if (_odict_FIRST(od) == node)
  604. _odict_FIRST(od) = _odictnode_NEXT(node);
  605. else if (_odictnode_PREV(node) != NULL)
  606. _odictnode_NEXT(_odictnode_PREV(node)) = _odictnode_NEXT(node);
  607. if (_odict_LAST(od) == node)
  608. _odict_LAST(od) = _odictnode_PREV(node);
  609. else if (_odictnode_NEXT(node) != NULL)
  610. _odictnode_PREV(_odictnode_NEXT(node)) = _odictnode_PREV(node);
  611. _odictnode_PREV(node) = NULL;
  612. _odictnode_NEXT(node) = NULL;
  613. od->od_state++;
  614. }
  615. /* If someone calls PyDict_DelItem() directly on an OrderedDict, we'll
  616. get all sorts of problems here. In PyODict_DelItem we make sure to
  617. call _odict_clear_node first.
  618. This matters in the case of colliding keys. Suppose we add 3 keys:
  619. [A, B, C], where the hash of C collides with A and the next possible
  620. index in the hash table is occupied by B. If we remove B then for C
  621. the dict's looknode func will give us the old index of B instead of
  622. the index we got before deleting B. However, the node for C in
  623. od_fast_nodes is still at the old dict index of C. Thus to be sure
  624. things don't get out of sync, we clear the node in od_fast_nodes
  625. *before* calling PyDict_DelItem.
  626. The same must be done for any other OrderedDict operations where
  627. we modify od_fast_nodes.
  628. */
  629. static int
  630. _odict_clear_node(PyODictObject *od, _ODictNode *node, PyObject *key,
  631. Py_hash_t hash)
  632. {
  633. Py_ssize_t i;
  634. assert(key != NULL);
  635. if (_odict_EMPTY(od)) {
  636. /* Let later code decide if this is a KeyError. */
  637. return 0;
  638. }
  639. i = _odict_get_index(od, key, hash);
  640. if (i < 0)
  641. return PyErr_Occurred() ? -1 : 0;
  642. if (node == NULL)
  643. node = od->od_fast_nodes[i];
  644. assert(node == od->od_fast_nodes[i]);
  645. if (node == NULL) {
  646. /* Let later code decide if this is a KeyError. */
  647. return 0;
  648. }
  649. // Now clear the node.
  650. od->od_fast_nodes[i] = NULL;
  651. _odict_remove_node(od, node);
  652. _odictnode_DEALLOC(node);
  653. return 0;
  654. }
  655. static void
  656. _odict_clear_nodes(PyODictObject *od)
  657. {
  658. _ODictNode *node, *next;
  659. _odict_free_fast_nodes(od);
  660. od->od_fast_nodes = NULL;
  661. node = _odict_FIRST(od);
  662. _odict_FIRST(od) = NULL;
  663. _odict_LAST(od) = NULL;
  664. while (node != NULL) {
  665. next = _odictnode_NEXT(node);
  666. _odictnode_DEALLOC(node);
  667. node = next;
  668. }
  669. }
  670. /* There isn't any memory management of nodes past this point. */
  671. #undef _odictnode_DEALLOC
  672. static int
  673. _odict_keys_equal(PyODictObject *a, PyODictObject *b)
  674. {
  675. _ODictNode *node_a, *node_b;
  676. node_a = _odict_FIRST(a);
  677. node_b = _odict_FIRST(b);
  678. while (1) {
  679. if (node_a == NULL && node_b == NULL)
  680. /* success: hit the end of each at the same time */
  681. return 1;
  682. else if (node_a == NULL || node_b == NULL)
  683. /* unequal length */
  684. return 0;
  685. else {
  686. int res = PyObject_RichCompareBool(
  687. (PyObject *)_odictnode_KEY(node_a),
  688. (PyObject *)_odictnode_KEY(node_b),
  689. Py_EQ);
  690. if (res < 0)
  691. return res;
  692. else if (res == 0)
  693. return 0;
  694. /* otherwise it must match, so move on to the next one */
  695. node_a = _odictnode_NEXT(node_a);
  696. node_b = _odictnode_NEXT(node_b);
  697. }
  698. }
  699. }
  700. /* ----------------------------------------------
  701. * OrderedDict mapping methods
  702. */
  703. /* mp_ass_subscript: __setitem__() and __delitem__() */
  704. static int
  705. odict_mp_ass_sub(PyODictObject *od, PyObject *v, PyObject *w)
  706. {
  707. if (w == NULL)
  708. return PyODict_DelItem((PyObject *)od, v);
  709. else
  710. return PyODict_SetItem((PyObject *)od, v, w);
  711. }
  712. /* tp_as_mapping */
  713. static PyMappingMethods odict_as_mapping = {
  714. 0, /*mp_length*/
  715. 0, /*mp_subscript*/
  716. (objobjargproc)odict_mp_ass_sub, /*mp_ass_subscript*/
  717. };
  718. /* ----------------------------------------------
  719. * OrderedDict methods
  720. */
  721. /* __delitem__() */
  722. PyDoc_STRVAR(odict_delitem__doc__, "od.__delitem__(y) <==> del od[y]");
  723. /* __eq__() */
  724. PyDoc_STRVAR(odict_eq__doc__,
  725. "od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive \n\
  726. while comparison to a regular mapping is order-insensitive.\n\
  727. ");
  728. /* forward */
  729. static PyObject * odict_richcompare(PyObject *v, PyObject *w, int op);
  730. static PyObject *
  731. odict_eq(PyObject *a, PyObject *b)
  732. {
  733. return odict_richcompare(a, b, Py_EQ);
  734. }
  735. /* __init__() */
  736. PyDoc_STRVAR(odict_init__doc__,
  737. "Initialize an ordered dictionary. The signature is the same as\n\
  738. regular dictionaries, but keyword arguments are not recommended because\n\
  739. their insertion order is arbitrary.\n\
  740. \n\
  741. ");
  742. /* forward */
  743. static int odict_init(PyObject *self, PyObject *args, PyObject *kwds);
  744. /* __iter__() */
  745. PyDoc_STRVAR(odict_iter__doc__, "od.__iter__() <==> iter(od)");
  746. static PyObject * odict_iter(PyODictObject *self); /* forward */
  747. /* __ne__() */
  748. /* Mapping.__ne__() does not have a docstring. */
  749. PyDoc_STRVAR(odict_ne__doc__, "");
  750. static PyObject *
  751. odict_ne(PyObject *a, PyObject *b)
  752. {
  753. return odict_richcompare(a, b, Py_NE);
  754. }
  755. /* __repr__() */
  756. PyDoc_STRVAR(odict_repr__doc__, "od.__repr__() <==> repr(od)");
  757. static PyObject * odict_repr(PyODictObject *self); /* forward */
  758. /* __setitem__() */
  759. PyDoc_STRVAR(odict_setitem__doc__, "od.__setitem__(i, y) <==> od[i]=y");
  760. /* fromkeys() */
  761. PyDoc_STRVAR(odict_fromkeys__doc__,
  762. "OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.\n\
  763. If not specified, the value defaults to None.\n\
  764. \n\
  765. ");
  766. static PyObject *
  767. odict_fromkeys(PyObject *cls, PyObject *args, PyObject *kwargs)
  768. {
  769. static char *kwlist[] = {"iterable", "value", 0};
  770. PyObject *seq;
  771. PyObject *value = Py_None;
  772. /* both borrowed */
  773. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O:fromkeys", kwlist,
  774. &seq, &value)) {
  775. return NULL;
  776. }
  777. return _PyDict_FromKeys(cls, seq, value);
  778. }
  779. /* __sizeof__() */
  780. /* OrderedDict.__sizeof__() does not have a docstring. */
  781. PyDoc_STRVAR(odict_sizeof__doc__, "");
  782. static PyObject *
  783. odict_sizeof(PyODictObject *od)
  784. {
  785. Py_ssize_t res = _PyDict_SizeOf((PyDictObject *)od);
  786. res += sizeof(_ODictNode *) * _odict_FAST_SIZE(od); /* od_fast_nodes */
  787. if (!_odict_EMPTY(od)) {
  788. res += sizeof(_ODictNode) * PyODict_SIZE(od); /* linked-list */
  789. }
  790. return PyLong_FromSsize_t(res);
  791. }
  792. /* __reduce__() */
  793. PyDoc_STRVAR(odict_reduce__doc__, "Return state information for pickling");
  794. static PyObject *
  795. odict_reduce(register PyODictObject *od)
  796. {
  797. _Py_IDENTIFIER(__dict__);
  798. _Py_IDENTIFIER(items);
  799. PyObject *dict = NULL, *result = NULL;
  800. PyObject *items_iter, *items, *args = NULL;
  801. /* capture any instance state */
  802. dict = _PyObject_GetAttrId((PyObject *)od, &PyId___dict__);
  803. if (dict == NULL)
  804. goto Done;
  805. else {
  806. /* od.__dict__ isn't necessarily a dict... */
  807. Py_ssize_t dict_len = PyObject_Length(dict);
  808. if (dict_len == -1)
  809. goto Done;
  810. if (!dict_len) {
  811. /* nothing to pickle in od.__dict__ */
  812. Py_CLEAR(dict);
  813. }
  814. }
  815. /* build the result */
  816. args = PyTuple_New(0);
  817. if (args == NULL)
  818. goto Done;
  819. items = _PyObject_CallMethodIdObjArgs((PyObject *)od, &PyId_items, NULL);
  820. if (items == NULL)
  821. goto Done;
  822. items_iter = PyObject_GetIter(items);
  823. Py_DECREF(items);
  824. if (items_iter == NULL)
  825. goto Done;
  826. result = PyTuple_Pack(5, Py_TYPE(od), args, dict ? dict : Py_None, Py_None, items_iter);
  827. Py_DECREF(items_iter);
  828. Done:
  829. Py_XDECREF(dict);
  830. Py_XDECREF(args);
  831. return result;
  832. }
  833. /* setdefault() */
  834. PyDoc_STRVAR(odict_setdefault__doc__,
  835. "od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od");
  836. /* Skips __missing__() calls. */
  837. static PyObject *
  838. odict_setdefault(register PyODictObject *od, PyObject *args, PyObject *kwargs)
  839. {
  840. static char *kwlist[] = {"key", "default", 0};
  841. PyObject *key, *result = NULL;
  842. PyObject *failobj = Py_None;
  843. /* both borrowed */
  844. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O:setdefault", kwlist,
  845. &key, &failobj)) {
  846. return NULL;
  847. }
  848. if (PyODict_CheckExact(od)) {
  849. result = PyODict_GetItemWithError(od, key); /* borrowed */
  850. if (result == NULL) {
  851. if (PyErr_Occurred())
  852. return NULL;
  853. assert(_odict_find_node(od, key) == NULL);
  854. if (PyODict_SetItem((PyObject *)od, key, failobj) >= 0) {
  855. result = failobj;
  856. Py_INCREF(failobj);
  857. }
  858. }
  859. else {
  860. Py_INCREF(result);
  861. }
  862. }
  863. else {
  864. int exists = PySequence_Contains((PyObject *)od, key);
  865. if (exists < 0) {
  866. return NULL;
  867. }
  868. else if (exists) {
  869. result = PyObject_GetItem((PyObject *)od, key);
  870. }
  871. else if (PyObject_SetItem((PyObject *)od, key, failobj) >= 0) {
  872. result = failobj;
  873. Py_INCREF(failobj);
  874. }
  875. }
  876. return result;
  877. }
  878. /* pop() */
  879. PyDoc_STRVAR(odict_pop__doc__,
  880. "od.pop(k[,d]) -> v, remove specified key and return the corresponding\n\
  881. value. If key is not found, d is returned if given, otherwise KeyError\n\
  882. is raised.\n\
  883. \n\
  884. ");
  885. /* forward */
  886. static PyObject * _odict_popkey(PyObject *, PyObject *, PyObject *);
  887. /* Skips __missing__() calls. */
  888. static PyObject *
  889. odict_pop(PyObject *od, PyObject *args, PyObject *kwargs)
  890. {
  891. static char *kwlist[] = {"key", "default", 0};
  892. PyObject *key, *failobj = NULL;
  893. /* borrowed */
  894. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O:pop", kwlist,
  895. &key, &failobj)) {
  896. return NULL;
  897. }
  898. return _odict_popkey(od, key, failobj);
  899. }
  900. static PyObject *
  901. _odict_popkey_hash(PyObject *od, PyObject *key, PyObject *failobj,
  902. Py_hash_t hash)
  903. {
  904. _ODictNode *node;
  905. PyObject *value = NULL;
  906. /* Pop the node first to avoid a possible dict resize (due to
  907. eval loop reentrancy) and complications due to hash collision
  908. resolution. */
  909. node = _odict_find_node_hash((PyODictObject *)od, key, hash);
  910. if (node == NULL) {
  911. if (PyErr_Occurred())
  912. return NULL;
  913. }
  914. else {
  915. int res = _odict_clear_node((PyODictObject *)od, node, key, hash);
  916. if (res < 0) {
  917. return NULL;
  918. }
  919. }
  920. /* Now delete the value from the dict. */
  921. if (PyODict_CheckExact(od)) {
  922. if (node != NULL) {
  923. value = _PyDict_GetItem_KnownHash(od, key, hash); /* borrowed */
  924. if (value != NULL) {
  925. Py_INCREF(value);
  926. if (_PyDict_DelItem_KnownHash(od, key, hash) < 0) {
  927. Py_DECREF(value);
  928. return NULL;
  929. }
  930. }
  931. }
  932. }
  933. else {
  934. int exists = PySequence_Contains(od, key);
  935. if (exists < 0)
  936. return NULL;
  937. if (exists) {
  938. value = PyObject_GetItem(od, key);
  939. if (value != NULL) {
  940. if (PyObject_DelItem(od, key) == -1) {
  941. Py_CLEAR(value);
  942. }
  943. }
  944. }
  945. }
  946. /* Apply the fallback value, if necessary. */
  947. if (value == NULL && !PyErr_Occurred()) {
  948. if (failobj) {
  949. value = failobj;
  950. Py_INCREF(failobj);
  951. }
  952. else {
  953. PyErr_SetObject(PyExc_KeyError, key);
  954. }
  955. }
  956. return value;
  957. }
  958. static PyObject *
  959. _odict_popkey(PyObject *od, PyObject *key, PyObject *failobj)
  960. {
  961. Py_hash_t hash = PyObject_Hash(key);
  962. if (hash == -1)
  963. return NULL;
  964. return _odict_popkey_hash(od, key, failobj, hash);
  965. }
  966. /* popitem() */
  967. PyDoc_STRVAR(odict_popitem__doc__,
  968. "od.popitem() -> (k, v), return and remove a (key, value) pair.\n\
  969. Pairs are returned in LIFO order if last is true or FIFO order if false.\n\
  970. \n\
  971. ");
  972. static PyObject *
  973. odict_popitem(PyObject *od, PyObject *args, PyObject *kwargs)
  974. {
  975. static char *kwlist[] = {"last", 0};
  976. PyObject *key, *value, *item = NULL;
  977. _ODictNode *node;
  978. int last = 1;
  979. /* pull the item */
  980. /* borrowed */
  981. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|p:popitem", kwlist,
  982. &last)) {
  983. return NULL;
  984. }
  985. if (_odict_EMPTY(od)) {
  986. PyErr_SetString(PyExc_KeyError, "dictionary is empty");
  987. return NULL;
  988. }
  989. node = last ? _odict_LAST(od) : _odict_FIRST(od);
  990. key = _odictnode_KEY(node);
  991. Py_INCREF(key);
  992. value = _odict_popkey_hash(od, key, NULL, _odictnode_HASH(node));
  993. if (value == NULL)
  994. return NULL;
  995. item = PyTuple_Pack(2, key, value);
  996. Py_DECREF(key);
  997. Py_DECREF(value);
  998. return item;
  999. }
  1000. /* keys() */
  1001. /* MutableMapping.keys() does not have a docstring. */
  1002. PyDoc_STRVAR(odict_keys__doc__, "");
  1003. static PyObject * odictkeys_new(PyObject *od); /* forward */
  1004. /* values() */
  1005. /* MutableMapping.values() does not have a docstring. */
  1006. PyDoc_STRVAR(odict_values__doc__, "");
  1007. static PyObject * odictvalues_new(PyObject *od); /* forward */
  1008. /* items() */
  1009. /* MutableMapping.items() does not have a docstring. */
  1010. PyDoc_STRVAR(odict_items__doc__, "");
  1011. static PyObject * odictitems_new(PyObject *od); /* forward */
  1012. /* update() */
  1013. /* MutableMapping.update() does not have a docstring. */
  1014. PyDoc_STRVAR(odict_update__doc__, "");
  1015. /* forward */
  1016. static PyObject * mutablemapping_update(PyObject *, PyObject *, PyObject *);
  1017. #define odict_update mutablemapping_update
  1018. /* clear() */
  1019. PyDoc_STRVAR(odict_clear__doc__,
  1020. "od.clear() -> None. Remove all items from od.");
  1021. static PyObject *
  1022. odict_clear(register PyODictObject *od)
  1023. {
  1024. PyDict_Clear((PyObject *)od);
  1025. _odict_clear_nodes(od);
  1026. if (_odict_resize(od) < 0)
  1027. return NULL;
  1028. Py_RETURN_NONE;
  1029. }
  1030. /* copy() */
  1031. /* forward */
  1032. static int _PyODict_SetItem_KnownHash(PyObject *, PyObject *, PyObject *,
  1033. Py_hash_t);
  1034. PyDoc_STRVAR(odict_copy__doc__, "od.copy() -> a shallow copy of od");
  1035. static PyObject *
  1036. odict_copy(register PyODictObject *od)
  1037. {
  1038. _ODictNode *node;
  1039. PyObject *od_copy;
  1040. if (PyODict_CheckExact(od))
  1041. od_copy = PyODict_New();
  1042. else
  1043. od_copy = PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(od), NULL);
  1044. if (od_copy == NULL)
  1045. return NULL;
  1046. if (PyODict_CheckExact(od)) {
  1047. _odict_FOREACH(od, node) {
  1048. PyObject *key = _odictnode_KEY(node);
  1049. PyObject *value = _odictnode_VALUE(node, od);
  1050. if (value == NULL) {
  1051. if (!PyErr_Occurred())
  1052. PyErr_SetObject(PyExc_KeyError, key);
  1053. goto fail;
  1054. }
  1055. if (_PyODict_SetItem_KnownHash((PyObject *)od_copy, key, value,
  1056. _odictnode_HASH(node)) != 0)
  1057. goto fail;
  1058. }
  1059. }
  1060. else {
  1061. _odict_FOREACH(od, node) {
  1062. int res;
  1063. PyObject *value = PyObject_GetItem((PyObject *)od,
  1064. _odictnode_KEY(node));
  1065. if (value == NULL)
  1066. goto fail;
  1067. res = PyObject_SetItem((PyObject *)od_copy,
  1068. _odictnode_KEY(node), value);
  1069. Py_DECREF(value);
  1070. if (res != 0)
  1071. goto fail;
  1072. }
  1073. }
  1074. return od_copy;
  1075. fail:
  1076. Py_DECREF(od_copy);
  1077. return NULL;
  1078. }
  1079. /* __reversed__() */
  1080. PyDoc_STRVAR(odict_reversed__doc__, "od.__reversed__() <==> reversed(od)");
  1081. #define _odict_ITER_REVERSED 1
  1082. #define _odict_ITER_KEYS 2
  1083. #define _odict_ITER_VALUES 4
  1084. /* forward */
  1085. static PyObject * odictiter_new(PyODictObject *, int);
  1086. static PyObject *
  1087. odict_reversed(PyODictObject *od)
  1088. {
  1089. return odictiter_new(od, _odict_ITER_KEYS|_odict_ITER_REVERSED);
  1090. }
  1091. /* move_to_end() */
  1092. PyDoc_STRVAR(odict_move_to_end__doc__,
  1093. "Move an existing element to the end (or beginning if last==False).\n\
  1094. \n\
  1095. Raises KeyError if the element does not exist.\n\
  1096. When last=True, acts like a fast version of self[key]=self.pop(key).\n\
  1097. \n\
  1098. ");
  1099. static PyObject *
  1100. odict_move_to_end(PyODictObject *od, PyObject *args, PyObject *kwargs)
  1101. {
  1102. static char *kwlist[] = {"key", "last", 0};
  1103. PyObject *key;
  1104. int last = 1;
  1105. _ODictNode *node;
  1106. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|p:move_to_end", kwlist,
  1107. &key, &last)) {
  1108. return NULL;
  1109. }
  1110. if (_odict_EMPTY(od)) {
  1111. PyErr_SetObject(PyExc_KeyError, key);
  1112. return NULL;
  1113. }
  1114. node = last ? _odict_LAST(od) : _odict_FIRST(od);
  1115. if (key != _odictnode_KEY(node)) {
  1116. node = _odict_find_node(od, key);
  1117. if (node == NULL) {
  1118. if (!PyErr_Occurred())
  1119. PyErr_SetObject(PyExc_KeyError, key);
  1120. return NULL;
  1121. }
  1122. if (last) {
  1123. /* Only move if not already the last one. */
  1124. if (node != _odict_LAST(od)) {
  1125. _odict_remove_node(od, node);
  1126. _odict_add_tail(od, node);
  1127. }
  1128. }
  1129. else {
  1130. /* Only move if not already the first one. */
  1131. if (node != _odict_FIRST(od)) {
  1132. _odict_remove_node(od, node);
  1133. _odict_add_head(od, node);
  1134. }
  1135. }
  1136. }
  1137. Py_RETURN_NONE;
  1138. }
  1139. /* tp_methods */
  1140. static PyMethodDef odict_methods[] = {
  1141. /* explicitly defined so we can align docstrings with
  1142. * collections.OrderedDict */
  1143. {"__delitem__", (PyCFunction)odict_mp_ass_sub, METH_NOARGS,
  1144. odict_delitem__doc__},
  1145. {"__eq__", (PyCFunction)odict_eq, METH_NOARGS,
  1146. odict_eq__doc__},
  1147. {"__init__", (PyCFunction)odict_init, METH_NOARGS,
  1148. odict_init__doc__},
  1149. {"__iter__", (PyCFunction)odict_iter, METH_NOARGS,
  1150. odict_iter__doc__},
  1151. {"__ne__", (PyCFunction)odict_ne, METH_NOARGS,
  1152. odict_ne__doc__},
  1153. {"__repr__", (PyCFunction)odict_repr, METH_NOARGS,
  1154. odict_repr__doc__},
  1155. {"__setitem__", (PyCFunction)odict_mp_ass_sub, METH_NOARGS,
  1156. odict_setitem__doc__},
  1157. {"fromkeys", (PyCFunction)odict_fromkeys,
  1158. METH_VARARGS | METH_KEYWORDS | METH_CLASS, odict_fromkeys__doc__},
  1159. /* overridden dict methods */
  1160. {"__sizeof__", (PyCFunction)odict_sizeof, METH_NOARGS,
  1161. odict_sizeof__doc__},
  1162. {"__reduce__", (PyCFunction)odict_reduce, METH_NOARGS,
  1163. odict_reduce__doc__},
  1164. {"setdefault", (PyCFunction)odict_setdefault,
  1165. METH_VARARGS | METH_KEYWORDS, odict_setdefault__doc__},
  1166. {"pop", (PyCFunction)odict_pop,
  1167. METH_VARARGS | METH_KEYWORDS, odict_pop__doc__},
  1168. {"popitem", (PyCFunction)odict_popitem,
  1169. METH_VARARGS | METH_KEYWORDS, odict_popitem__doc__},
  1170. {"keys", (PyCFunction)odictkeys_new, METH_NOARGS,
  1171. odict_keys__doc__},
  1172. {"values", (PyCFunction)odictvalues_new, METH_NOARGS,
  1173. odict_values__doc__},
  1174. {"items", (PyCFunction)odictitems_new, METH_NOARGS,
  1175. odict_items__doc__},
  1176. {"update", (PyCFunction)odict_update, METH_VARARGS | METH_KEYWORDS,
  1177. odict_update__doc__},
  1178. {"clear", (PyCFunction)odict_clear, METH_NOARGS,
  1179. odict_clear__doc__},
  1180. {"copy", (PyCFunction)odict_copy, METH_NOARGS,
  1181. odict_copy__doc__},
  1182. /* new methods */
  1183. {"__reversed__", (PyCFunction)odict_reversed, METH_NOARGS,
  1184. odict_reversed__doc__},
  1185. {"move_to_end", (PyCFunction)odict_move_to_end,
  1186. METH_VARARGS | METH_KEYWORDS, odict_move_to_end__doc__},
  1187. {NULL, NULL} /* sentinel */
  1188. };
  1189. /* ----------------------------------------------
  1190. * OrderedDict members
  1191. */
  1192. /* tp_getset */
  1193. static PyGetSetDef odict_getset[] = {
  1194. {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
  1195. {NULL}
  1196. };
  1197. /* ----------------------------------------------
  1198. * OrderedDict type slot methods
  1199. */
  1200. /* tp_dealloc */
  1201. static void
  1202. odict_dealloc(PyODictObject *self)
  1203. {
  1204. PyThreadState *tstate = PyThreadState_GET();
  1205. PyObject_GC_UnTrack(self);
  1206. Py_TRASHCAN_SAFE_BEGIN(self)
  1207. Py_XDECREF(self->od_inst_dict);
  1208. if (self->od_weakreflist != NULL)
  1209. PyObject_ClearWeakRefs((PyObject *)self);
  1210. _odict_clear_nodes(self);
  1211. /* Call the base tp_dealloc(). Since it too uses the trashcan mechanism,
  1212. * temporarily decrement trash_delete_nesting to prevent triggering it
  1213. * and putting the partially deallocated object on the trashcan's
  1214. * to-be-deleted-later list.
  1215. */
  1216. --tstate->trash_delete_nesting;
  1217. assert(_tstate->trash_delete_nesting < PyTrash_UNWIND_LEVEL);
  1218. PyDict_Type.tp_dealloc((PyObject *)self);
  1219. ++tstate->trash_delete_nesting;
  1220. Py_TRASHCAN_SAFE_END(self)
  1221. }
  1222. /* tp_repr */
  1223. static PyObject *
  1224. odict_repr(PyODictObject *self)
  1225. {
  1226. int i;
  1227. _Py_IDENTIFIER(items);
  1228. PyObject *pieces = NULL, *result = NULL;
  1229. const char *classname;
  1230. classname = strrchr(Py_TYPE(self)->tp_name, '.');
  1231. if (classname == NULL)
  1232. classname = Py_TYPE(self)->tp_name;
  1233. else
  1234. classname++;
  1235. if (PyODict_SIZE(self) == 0)
  1236. return PyUnicode_FromFormat("%s()", classname);
  1237. i = Py_ReprEnter((PyObject *)self);
  1238. if (i != 0) {
  1239. return i > 0 ? PyUnicode_FromString("...") : NULL;
  1240. }
  1241. if (PyODict_CheckExact(self)) {
  1242. Py_ssize_t count = 0;
  1243. _ODictNode *node;
  1244. pieces = PyList_New(PyODict_SIZE(self));
  1245. if (pieces == NULL)
  1246. goto Done;
  1247. _odict_FOREACH(self, node) {
  1248. PyObject *pair;
  1249. PyObject *key = _odictnode_KEY(node);
  1250. PyObject *value = _odictnode_VALUE(node, self);
  1251. if (value == NULL) {
  1252. if (!PyErr_Occurred())
  1253. PyErr_SetObject(PyExc_KeyError, key);
  1254. goto Done;
  1255. }
  1256. pair = PyTuple_Pack(2, key, value);
  1257. if (pair == NULL)
  1258. goto Done;
  1259. if (count < PyList_GET_SIZE(pieces))
  1260. PyList_SET_ITEM(pieces, count, pair); /* steals reference */
  1261. else {
  1262. if (PyList_Append(pieces, pair) < 0) {
  1263. Py_DECREF(pair);
  1264. goto Done;
  1265. }
  1266. Py_DECREF(pair);
  1267. }
  1268. count++;
  1269. }
  1270. if (count < PyList_GET_SIZE(pieces))
  1271. PyList_GET_SIZE(pieces) = count;
  1272. }
  1273. else {
  1274. PyObject *items = _PyObject_CallMethodIdObjArgs((PyObject *)self,
  1275. &PyId_items, NULL);
  1276. if (items == NULL)
  1277. goto Done;
  1278. pieces = PySequence_List(items);
  1279. Py_DECREF(items);
  1280. if (pieces == NULL)
  1281. goto Done;
  1282. }
  1283. result = PyUnicode_FromFormat("%s(%R)", classname, pieces);
  1284. Done:
  1285. Py_XDECREF(pieces);
  1286. Py_ReprLeave((PyObject *)self);
  1287. return result;
  1288. }
  1289. /* tp_doc */
  1290. PyDoc_STRVAR(odict_doc,
  1291. "Dictionary that remembers insertion order");
  1292. /* tp_traverse */
  1293. static int
  1294. odict_traverse(PyODictObject *od, visitproc visit, void *arg)
  1295. {
  1296. _ODictNode *node;
  1297. Py_VISIT(od->od_inst_dict);
  1298. Py_VISIT(od->od_weakreflist);
  1299. _odict_FOREACH(od, node) {
  1300. Py_VISIT(_odictnode_KEY(node));
  1301. }
  1302. return PyDict_Type.tp_traverse((PyObject *)od, visit, arg);
  1303. }
  1304. /* tp_clear */
  1305. static int
  1306. odict_tp_clear(PyODictObject *od)
  1307. {
  1308. PyObject *res;
  1309. Py_CLEAR(od->od_inst_dict);
  1310. Py_CLEAR(od->od_weakreflist);
  1311. res = odict_clear(od);
  1312. if (res == NULL)
  1313. return -1;
  1314. Py_DECREF(res);
  1315. return 0;
  1316. }
  1317. /* tp_richcompare */
  1318. static PyObject *
  1319. odict_richcompare(PyObject *v, PyObject *w, int op)
  1320. {
  1321. if (!PyODict_Check(v) || !PyDict_Check(w)) {
  1322. Py_RETURN_NOTIMPLEMENTED;
  1323. }
  1324. if (op == Py_EQ || op == Py_NE) {
  1325. PyObject *res, *cmp;
  1326. int eq;
  1327. cmp = PyDict_Type.tp_richcompare(v, w, op);
  1328. if (cmp == NULL)
  1329. return NULL;
  1330. if (!PyODict_Check(w))
  1331. return cmp;
  1332. if (op == Py_EQ && cmp == Py_False)
  1333. return cmp;
  1334. if (op == Py_NE && cmp == Py_True)
  1335. return cmp;
  1336. Py_DECREF(cmp);
  1337. /* Try comparing odict keys. */
  1338. eq = _odict_keys_equal((PyODictObject *)v, (PyODictObject *)w);
  1339. if (eq < 0)
  1340. return NULL;
  1341. res = (eq == (op == Py_EQ)) ? Py_True : Py_False;
  1342. Py_INCREF(res);
  1343. return res;
  1344. } else {
  1345. Py_RETURN_NOTIMPLEMENTED;
  1346. }
  1347. }
  1348. /* tp_iter */
  1349. static PyObject *
  1350. odict_iter(PyODictObject *od)
  1351. {
  1352. return odictiter_new(od, _odict_ITER_KEYS);
  1353. }
  1354. /* tp_init */
  1355. static int
  1356. odict_init(PyObject *self, PyObject *args, PyObject *kwds)
  1357. {
  1358. PyObject *res;
  1359. Py_ssize_t len = PyObject_Length(args);
  1360. if (len == -1)
  1361. return -1;
  1362. if (len > 1) {
  1363. char *msg = "expected at most 1 arguments, got %d";
  1364. PyErr_Format(PyExc_TypeError, msg, len);
  1365. return -1;
  1366. }
  1367. /* __init__() triggering update() is just the way things are! */
  1368. res = odict_update(self, args, kwds);
  1369. if (res == NULL) {
  1370. return -1;
  1371. } else {
  1372. Py_DECREF(res);
  1373. return 0;
  1374. }
  1375. }
  1376. /* tp_new */
  1377. static PyObject *
  1378. odict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  1379. {
  1380. PyODictObject *od;
  1381. od = (PyODictObject *)PyDict_Type.tp_new(type, args, kwds);
  1382. if (od == NULL)
  1383. return NULL;
  1384. /* type constructor fills the memory with zeros (see
  1385. PyType_GenericAlloc()), there is no need to set them to zero again */
  1386. if (_odict_resize(od) < 0) {
  1387. Py_DECREF(od);
  1388. return NULL;
  1389. }
  1390. return (PyObject*)od;
  1391. }
  1392. /* PyODict_Type */
  1393. PyTypeObject PyODict_Type = {
  1394. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1395. "collections.OrderedDict", /* tp_name */
  1396. sizeof(PyODictObject), /* tp_basicsize */
  1397. 0, /* tp_itemsize */
  1398. (destructor)odict_dealloc, /* tp_dealloc */
  1399. 0, /* tp_print */
  1400. 0, /* tp_getattr */
  1401. 0, /* tp_setattr */
  1402. 0, /* tp_reserved */
  1403. (reprfunc)odict_repr, /* tp_repr */
  1404. 0, /* tp_as_number */
  1405. 0, /* tp_as_sequence */
  1406. &odict_as_mapping, /* tp_as_mapping */
  1407. 0, /* tp_hash */
  1408. 0, /* tp_call */
  1409. 0, /* tp_str */
  1410. 0, /* tp_getattro */
  1411. 0, /* tp_setattro */
  1412. 0, /* tp_as_buffer */
  1413. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  1414. odict_doc, /* tp_doc */
  1415. (traverseproc)odict_traverse, /* tp_traverse */
  1416. (inquiry)odict_tp_clear, /* tp_clear */
  1417. (richcmpfunc)odict_richcompare, /* tp_richcompare */
  1418. offsetof(PyODictObject, od_weakreflist), /* tp_weaklistoffset */
  1419. (getiterfunc)odict_iter, /* tp_iter */
  1420. 0, /* tp_iternext */
  1421. odict_methods, /* tp_methods */
  1422. 0, /* tp_members */
  1423. odict_getset, /* tp_getset */
  1424. &PyDict_Type, /* tp_base */
  1425. 0, /* tp_dict */
  1426. 0, /* tp_descr_get */
  1427. 0, /* tp_descr_set */
  1428. offsetof(PyODictObject, od_inst_dict), /* tp_dictoffset */
  1429. (initproc)odict_init, /* tp_init */
  1430. PyType_GenericAlloc, /* tp_alloc */
  1431. (newfunc)odict_new, /* tp_new */
  1432. 0, /* tp_free */
  1433. };
  1434. /* ----------------------------------------------
  1435. * the public OrderedDict API
  1436. */
  1437. PyObject *
  1438. PyODict_New(void) {
  1439. return odict_new(&PyODict_Type, NULL, NULL);
  1440. }
  1441. static int
  1442. _PyODict_SetItem_KnownHash(PyObject *od, PyObject *key, PyObject *value,
  1443. Py_hash_t hash)
  1444. {
  1445. int res = _PyDict_SetItem_KnownHash(od, key, value, hash);
  1446. if (res == 0) {
  1447. res = _odict_add_new_node((PyODictObject *)od, key, hash);
  1448. if (res < 0) {
  1449. /* Revert setting the value on the dict */
  1450. PyObject *exc, *val, *tb;
  1451. PyErr_Fetch(&exc, &val, &tb);
  1452. (void) _PyDict_DelItem_KnownHash(od, key, hash);
  1453. _PyErr_ChainExceptions(exc, val, tb);
  1454. }
  1455. }
  1456. return res;
  1457. }
  1458. int
  1459. PyODict_SetItem(PyObject *od, PyObject *key, PyObject *value)
  1460. {
  1461. Py_hash_t hash = PyObject_Hash(key);
  1462. if (hash == -1)
  1463. return -1;
  1464. return _PyODict_SetItem_KnownHash(od, key, value, hash);
  1465. }
  1466. int
  1467. PyODict_DelItem(PyObject *od, PyObject *key)
  1468. {
  1469. int res;
  1470. Py_hash_t hash = PyObject_Hash(key);
  1471. if (hash == -1)
  1472. return -1;
  1473. res = _odict_clear_node((PyODictObject *)od, NULL, key, hash);
  1474. if (res < 0)
  1475. return -1;
  1476. return _PyDict_DelItem_KnownHash(od, key, hash);
  1477. }
  1478. /* -------------------------------------------
  1479. * The OrderedDict views (keys/values/items)
  1480. */
  1481. typedef struct {
  1482. PyObject_HEAD
  1483. int kind;
  1484. PyODictObject *di_odict;
  1485. Py_ssize_t di_size;
  1486. size_t di_state;
  1487. PyObject *di_current;
  1488. PyObject *di_result; /* reusable result tuple for iteritems */
  1489. } odictiterobject;
  1490. static void
  1491. odictiter_dealloc(odictiterobject *di)
  1492. {
  1493. _PyObject_GC_UNTRACK(di);
  1494. Py_XDECREF(di->di_odict);
  1495. Py_XDECREF(di->di_current);
  1496. if (di->kind & (_odict_ITER_KEYS | _odict_ITER_VALUES)) {
  1497. Py_DECREF(di->di_result);
  1498. }
  1499. PyObject_GC_Del(di);
  1500. }
  1501. static int
  1502. odictiter_traverse(odictiterobject *di, visitproc visit, void *arg)
  1503. {
  1504. Py_VISIT(di->di_odict);
  1505. Py_VISIT(di->di_current); /* A key could be any type, not just str. */
  1506. Py_VISIT(di->di_result);
  1507. return 0;
  1508. }
  1509. /* In order to protect against modifications during iteration, we track
  1510. * the current key instead of the current node. */
  1511. static PyObject *
  1512. odictiter_nextkey(odictiterobject *di)
  1513. {
  1514. PyObject *key = NULL;
  1515. _ODictNode *node;
  1516. int reversed = di->kind & _odict_ITER_REVERSED;
  1517. if (di->di_odict == NULL)
  1518. return NULL;
  1519. if (di->di_current == NULL)
  1520. goto done; /* We're already done. */
  1521. /* Check for unsupported changes. */
  1522. if (di->di_odict->od_state != di->di_state) {
  1523. PyErr_SetString(PyExc_RuntimeError,
  1524. "OrderedDict mutated during iteration");
  1525. goto done;
  1526. }
  1527. if (di->di_size != PyODict_SIZE(di->di_odict)) {
  1528. PyErr_SetString(PyExc_RuntimeError,
  1529. "OrderedDict changed size during iteration");
  1530. di->di_size = -1; /* Make this state sticky */
  1531. return NULL;
  1532. }
  1533. /* Get the key. */
  1534. node = _odict_find_node(di->di_odict, di->di_current);
  1535. if (node == NULL) {
  1536. if (!PyErr_Occurred())
  1537. PyErr_SetObject(PyExc_KeyError, di->di_current);
  1538. /* Must have been deleted. */
  1539. Py_CLEAR(di->di_current);
  1540. return NULL;
  1541. }
  1542. key = di->di_current;
  1543. /* Advance to the next key. */
  1544. node = reversed ? _odictnode_PREV(node) : _odictnode_NEXT(node);
  1545. if (node == NULL) {
  1546. /* Reached the end. */
  1547. di->di_current = NULL;
  1548. }
  1549. else {
  1550. di->di_current = _odictnode_KEY(node);
  1551. Py_INCREF(di->di_current);
  1552. }
  1553. return key;
  1554. done:
  1555. Py_CLEAR(di->di_odict);
  1556. return key;
  1557. }
  1558. static PyObject *
  1559. odictiter_iternext(odictiterobject *di)
  1560. {
  1561. PyObject *result, *value;
  1562. PyObject *key = odictiter_nextkey(di); /* new reference */
  1563. if (key == NULL)
  1564. return NULL;
  1565. /* Handle the keys case. */
  1566. if (! (di->kind & _odict_ITER_VALUES)) {
  1567. return key;
  1568. }
  1569. value = PyODict_GetItem((PyObject *)di->di_odict, key); /* borrowed */
  1570. if (value == NULL) {
  1571. if (!PyErr_Occurred())
  1572. PyErr_SetObject(PyExc_KeyError, key);
  1573. Py_DECREF(key);
  1574. goto done;
  1575. }
  1576. Py_INCREF(value);
  1577. /* Handle the values case. */
  1578. if (!(di->kind & _odict_ITER_KEYS)) {
  1579. Py_DECREF(key);
  1580. return value;
  1581. }
  1582. /* Handle the items case. */
  1583. result = di->di_result;
  1584. if (Py_REFCNT(result) == 1) {
  1585. /* not in use so we can reuse it
  1586. * (the common case during iteration) */
  1587. Py_INCREF(result);
  1588. Py_DECREF(PyTuple_GET_ITEM(result, 0)); /* borrowed */
  1589. Py_DECREF(PyTuple_GET_ITEM(result, 1)); /* borrowed */
  1590. }
  1591. else {
  1592. result = PyTuple_New(2);
  1593. if (result == NULL) {
  1594. Py_DECREF(key);
  1595. Py_DECREF(value);
  1596. goto done;
  1597. }
  1598. }
  1599. PyTuple_SET_ITEM(result, 0, key); /* steals reference */
  1600. PyTuple_SET_ITEM(result, 1, value); /* steals reference */
  1601. return result;
  1602. done:
  1603. Py_CLEAR(di->di_current);
  1604. Py_CLEAR(di->di_odict);
  1605. return NULL;
  1606. }
  1607. /* No need for tp_clear because odictiterobject is not mutable. */
  1608. PyDoc_STRVAR(reduce_doc, "Return state information for pickling");
  1609. static PyObject *
  1610. odictiter_reduce(odictiterobject *di)
  1611. {
  1612. PyObject *list, *iter;
  1613. list = PyList_New(0);
  1614. if (!list)
  1615. return NULL;
  1616. /* iterate the temporary into a list */
  1617. for(;;) {
  1618. PyObject *element = odictiter_iternext(di);
  1619. if (element) {
  1620. if (PyList_Append(list, element)) {
  1621. Py_DECREF(element);
  1622. Py_DECREF(list);
  1623. return NULL;
  1624. }
  1625. Py_DECREF(element);
  1626. }
  1627. else {
  1628. /* done iterating? */
  1629. break;
  1630. }
  1631. }
  1632. if (PyErr_Occurred()) {
  1633. Py_DECREF(list);
  1634. return NULL;
  1635. }
  1636. iter = _PyObject_GetBuiltin("iter");
  1637. if (iter == NULL) {
  1638. Py_DECREF(list);
  1639. return NULL;
  1640. }
  1641. return Py_BuildValue("N(N)", iter, list);
  1642. }
  1643. static PyMethodDef odictiter_methods[] = {
  1644. {"__reduce__", (PyCFunction)odictiter_reduce, METH_NOARGS, reduce_doc},
  1645. {NULL, NULL} /* sentinel */
  1646. };
  1647. PyTypeObject PyODictIter_Type = {
  1648. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1649. "odict_iterator", /* tp_name */
  1650. sizeof(odictiterobject), /* tp_basicsize */
  1651. 0, /* tp_itemsize */
  1652. /* methods */
  1653. (destructor)odictiter_dealloc, /* tp_dealloc */
  1654. 0, /* tp_print */
  1655. 0, /* tp_getattr */
  1656. 0, /* tp_setattr */
  1657. 0, /* tp_reserved */
  1658. 0, /* tp_repr */
  1659. 0, /* tp_as_number */
  1660. 0, /* tp_as_sequence */
  1661. 0, /* tp_as_mapping */
  1662. 0, /* tp_hash */
  1663. 0, /* tp_call */
  1664. 0, /* tp_str */
  1665. PyObject_GenericGetAttr, /* tp_getattro */
  1666. 0, /* tp_setattro */
  1667. 0, /* tp_as_buffer */
  1668. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  1669. 0, /* tp_doc */
  1670. (traverseproc)odictiter_traverse, /* tp_traverse */
  1671. 0, /* tp_clear */
  1672. 0, /* tp_richcompare */
  1673. 0, /* tp_weaklistoffset */
  1674. PyObject_SelfIter, /* tp_iter */
  1675. (iternextfunc)odictiter_iternext, /* tp_iternext */
  1676. odictiter_methods, /* tp_methods */
  1677. 0,
  1678. };
  1679. static PyObject *
  1680. odictiter_new(PyODictObject *od, int kind)
  1681. {
  1682. odictiterobject *di;
  1683. _ODictNode *node;
  1684. int reversed = kind & _odict_ITER_REVERSED;
  1685. di = PyObject_GC_New(odictiterobject, &PyODictIter_Type);
  1686. if (di == NULL)
  1687. return NULL;
  1688. if (kind & (_odict_ITER_KEYS | _odict_ITER_VALUES)){
  1689. di->di_result = PyTuple_Pack(2, Py_None, Py_None);
  1690. if (di->di_result == NULL) {
  1691. Py_DECREF(di);
  1692. return NULL;
  1693. }
  1694. }
  1695. else
  1696. di->di_result = NULL;
  1697. di->kind = kind;
  1698. node = reversed ? _odict_LAST(od) : _odict_FIRST(od);
  1699. di->di_current = node ? _odictnode_KEY(node) : NULL;
  1700. Py_XINCREF(di->di_current);
  1701. di->di_size = PyODict_SIZE(od);
  1702. di->di_state = od->od_state;
  1703. di->di_odict = od;
  1704. Py_INCREF(od);
  1705. _PyObject_GC_TRACK(di);
  1706. return (PyObject *)di;
  1707. }
  1708. /* keys() */
  1709. static PyObject *
  1710. odictkeys_iter(_PyDictViewObject *dv)
  1711. {
  1712. if (dv->dv_dict == NULL) {
  1713. Py_RETURN_NONE;
  1714. }
  1715. return odictiter_new((PyODictObject *)dv->dv_dict,
  1716. _odict_ITER_KEYS);
  1717. }
  1718. static PyObject *
  1719. odictkeys_reversed(_PyDictViewObject *dv)
  1720. {
  1721. if (dv->dv_dict == NULL) {
  1722. Py_RETURN_NONE;
  1723. }
  1724. return odictiter_new((PyODictObject *)dv->dv_dict,
  1725. _odict_ITER_KEYS|_odict_ITER_REVERSED);
  1726. }
  1727. static PyMethodDef odictkeys_methods[] = {
  1728. {"__reversed__", (PyCFunction)odictkeys_reversed, METH_NOARGS, NULL},
  1729. {NULL, NULL} /* sentinel */
  1730. };
  1731. PyTypeObject PyODictKeys_Type = {
  1732. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1733. "odict_keys", /* tp_name */
  1734. 0, /* tp_basicsize */
  1735. 0, /* tp_itemsize */
  1736. 0, /* tp_dealloc */
  1737. 0, /* tp_print */
  1738. 0, /* tp_getattr */
  1739. 0, /* tp_setattr */
  1740. 0, /* tp_reserved */
  1741. 0, /* tp_repr */
  1742. 0, /* tp_as_number */
  1743. 0, /* tp_as_sequence */
  1744. 0, /* tp_as_mapping */
  1745. 0, /* tp_hash */
  1746. 0, /* tp_call */
  1747. 0, /* tp_str */
  1748. 0, /* tp_getattro */
  1749. 0, /* tp_setattro */
  1750. 0, /* tp_as_buffer */
  1751. 0, /* tp_flags */
  1752. 0, /* tp_doc */
  1753. 0, /* tp_traverse */
  1754. 0, /* tp_clear */
  1755. 0, /* tp_richcompare */
  1756. 0, /* tp_weaklistoffset */
  1757. (getiterfunc)odictkeys_iter, /* tp_iter */
  1758. 0, /* tp_iternext */
  1759. odictkeys_methods, /* tp_methods */
  1760. 0, /* tp_members */
  1761. 0, /* tp_getset */
  1762. &PyDictKeys_Type, /* tp_base */
  1763. };
  1764. static PyObject *
  1765. odictkeys_new(PyObject *od)
  1766. {
  1767. return _PyDictView_New(od, &PyODictKeys_Type);
  1768. }
  1769. /* items() */
  1770. static PyObject *
  1771. odictitems_iter(_PyDictViewObject *dv)
  1772. {
  1773. if (dv->dv_dict == NULL) {
  1774. Py_RETURN_NONE;
  1775. }
  1776. return odictiter_new((PyODictObject *)dv->dv_dict,
  1777. _odict_ITER_KEYS|_odict_ITER_VALUES);
  1778. }
  1779. static PyObject *
  1780. odictitems_reversed(_PyDictViewObject *dv)
  1781. {
  1782. if (dv->dv_dict == NULL) {
  1783. Py_RETURN_NONE;
  1784. }
  1785. return odictiter_new((PyODictObject *)dv->dv_dict,
  1786. _odict_ITER_KEYS|_odict_ITER_VALUES|_odict_ITER_REVERSED);
  1787. }
  1788. static PyMethodDef odictitems_methods[] = {
  1789. {"__reversed__", (PyCFunction)odictitems_reversed, METH_NOARGS, NULL},
  1790. {NULL, NULL} /* sentinel */
  1791. };
  1792. PyTypeObject PyODictItems_Type = {
  1793. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1794. "odict_items", /* tp_name */
  1795. 0, /* tp_basicsize */
  1796. 0, /* tp_itemsize */
  1797. 0, /* tp_dealloc */
  1798. 0, /* tp_print */
  1799. 0, /* tp_getattr */
  1800. 0, /* tp_setattr */
  1801. 0, /* tp_reserved */
  1802. 0, /* tp_repr */
  1803. 0, /* tp_as_number */
  1804. 0, /* tp_as_sequence */
  1805. 0, /* tp_as_mapping */
  1806. 0, /* tp_hash */
  1807. 0, /* tp_call */
  1808. 0, /* tp_str */
  1809. 0, /* tp_getattro */
  1810. 0, /* tp_setattro */
  1811. 0, /* tp_as_buffer */
  1812. 0, /* tp_flags */
  1813. 0, /* tp_doc */
  1814. 0, /* tp_traverse */
  1815. 0, /* tp_clear */
  1816. 0, /* tp_richcompare */
  1817. 0, /* tp_weaklistoffset */
  1818. (getiterfunc)odictitems_iter, /* tp_iter */
  1819. 0, /* tp_iternext */
  1820. odictitems_methods, /* tp_methods */
  1821. 0, /* tp_members */
  1822. 0, /* tp_getset */
  1823. &PyDictItems_Type, /* tp_base */
  1824. };
  1825. static PyObject *
  1826. odictitems_new(PyObject *od)
  1827. {
  1828. return _PyDictView_New(od, &PyODictItems_Type);
  1829. }
  1830. /* values() */
  1831. static PyObject *
  1832. odictvalues_iter(_PyDictViewObject *dv)
  1833. {
  1834. if (dv->dv_dict == NULL) {
  1835. Py_RETURN_NONE;
  1836. }
  1837. return odictiter_new((PyODictObject *)dv->dv_dict,
  1838. _odict_ITER_VALUES);
  1839. }
  1840. static PyObject *
  1841. odictvalues_reversed(_PyDictViewObject *dv)
  1842. {
  1843. if (dv->dv_dict == NULL) {
  1844. Py_RETURN_NONE;
  1845. }
  1846. return odictiter_new((PyODictObject *)dv->dv_dict,
  1847. _odict_ITER_VALUES|_odict_ITER_REVERSED);
  1848. }
  1849. static PyMethodDef odictvalues_methods[] = {
  1850. {"__reversed__", (PyCFunction)odictvalues_reversed, METH_NOARGS, NULL},
  1851. {NULL, NULL} /* sentinel */
  1852. };
  1853. PyTypeObject PyODictValues_Type = {
  1854. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1855. "odict_values", /* tp_name */
  1856. 0, /* tp_basicsize */
  1857. 0, /* tp_itemsize */
  1858. 0, /* tp_dealloc */
  1859. 0, /* tp_print */
  1860. 0, /* tp_getattr */
  1861. 0, /* tp_setattr */
  1862. 0, /* tp_reserved */
  1863. 0, /* tp_repr */
  1864. 0, /* tp_as_number */
  1865. 0, /* tp_as_sequence */
  1866. 0, /* tp_as_mapping */
  1867. 0, /* tp_hash */
  1868. 0, /* tp_call */
  1869. 0, /* tp_str */
  1870. 0, /* tp_getattro */
  1871. 0, /* tp_setattro */
  1872. 0, /* tp_as_buffer */
  1873. 0, /* tp_flags */
  1874. 0, /* tp_doc */
  1875. 0, /* tp_traverse */
  1876. 0, /* tp_clear */
  1877. 0, /* tp_richcompare */
  1878. 0, /* tp_weaklistoffset */
  1879. (getiterfunc)odictvalues_iter, /* tp_iter */
  1880. 0, /* tp_iternext */
  1881. odictvalues_methods, /* tp_methods */
  1882. 0, /* tp_members */
  1883. 0, /* tp_getset */
  1884. &PyDictValues_Type, /* tp_base */
  1885. };
  1886. static PyObject *
  1887. odictvalues_new(PyObject *od)
  1888. {
  1889. return _PyDictView_New(od, &PyODictValues_Type);
  1890. }
  1891. /* ----------------------------------------------
  1892. MutableMappping implementations
  1893. Mapping:
  1894. ============ ===========
  1895. method uses
  1896. ============ ===========
  1897. __contains__ __getitem__
  1898. __eq__ items
  1899. __getitem__ +
  1900. __iter__ +
  1901. __len__ +
  1902. __ne__ __eq__
  1903. get __getitem__
  1904. items ItemsView
  1905. keys KeysView
  1906. values ValuesView
  1907. ============ ===========
  1908. ItemsView uses __len__, __iter__, and __getitem__.
  1909. KeysView uses __len__, __iter__, and __contains__.
  1910. ValuesView uses __len__, __iter__, and __getitem__.
  1911. MutableMapping:
  1912. ============ ===========
  1913. method uses
  1914. ============ ===========
  1915. __delitem__ +
  1916. __setitem__ +
  1917. clear popitem
  1918. pop __getitem__
  1919. __delitem__
  1920. popitem __iter__
  1921. _getitem__
  1922. __delitem__
  1923. setdefault __getitem__
  1924. __setitem__
  1925. update __setitem__
  1926. ============ ===========
  1927. */
  1928. static int
  1929. mutablemapping_add_pairs(PyObject *self, PyObject *pairs)
  1930. {
  1931. PyObject *pair, *iterator, *unexpected;
  1932. int res = 0;
  1933. iterator = PyObject_GetIter(pairs);
  1934. if (iterator == NULL)
  1935. return -1;
  1936. PyErr_Clear();
  1937. while ((pair = PyIter_Next(iterator)) != NULL) {
  1938. /* could be more efficient (see UNPACK_SEQUENCE in ceval.c) */
  1939. PyObject *key = NULL, *value = NULL;
  1940. PyObject *pair_iterator = PyObject_GetIter(pair);
  1941. if (pair_iterator == NULL)
  1942. goto Done;
  1943. key = PyIter_Next(pair_iterator);
  1944. if (key == NULL) {
  1945. if (!PyErr_Occurred())
  1946. PyErr_SetString(PyExc_ValueError,
  1947. "need more than 0 values to unpack");
  1948. goto Done;
  1949. }
  1950. value = PyIter_Next(pair_iterator);
  1951. if (value == NULL) {
  1952. if (!PyErr_Occurred())
  1953. PyErr_SetString(PyExc_ValueError,
  1954. "need more than 1 value to unpack");
  1955. goto Done;
  1956. }
  1957. unexpected = PyIter_Next(pair_iterator);
  1958. if (unexpected != NULL) {
  1959. Py_DECREF(unexpected);
  1960. PyErr_SetString(PyExc_ValueError,
  1961. "too many values to unpack (expected 2)");
  1962. goto Done;
  1963. }
  1964. else if (PyErr_Occurred())
  1965. goto Done;
  1966. res = PyObject_SetItem(self, key, value);
  1967. Done:
  1968. Py_DECREF(pair);
  1969. Py_XDECREF(pair_iterator);
  1970. Py_XDECREF(key);
  1971. Py_XDECREF(value);
  1972. if (PyErr_Occurred())
  1973. break;
  1974. }
  1975. Py_DECREF(iterator);
  1976. if (res < 0 || PyErr_Occurred() != NULL)
  1977. return -1;
  1978. else
  1979. return 0;
  1980. }
  1981. static PyObject *
  1982. mutablemapping_update(PyObject *self, PyObject *args, PyObject *kwargs)
  1983. {
  1984. int res = 0;
  1985. Py_ssize_t len;
  1986. _Py_IDENTIFIER(items);
  1987. _Py_IDENTIFIER(keys);
  1988. /* first handle args, if any */
  1989. assert(args == NULL || PyTuple_Check(args));
  1990. len = (args != NULL) ? PyTuple_GET_SIZE(args) : 0;
  1991. if (len > 1) {
  1992. char *msg = "update() takes at most 1 positional argument (%d given)";
  1993. PyErr_Format(PyExc_TypeError, msg, len);
  1994. return NULL;
  1995. }
  1996. if (len) {
  1997. PyObject *other = PyTuple_GET_ITEM(args, 0); /* borrowed reference */
  1998. assert(other != NULL);
  1999. Py_INCREF(other);
  2000. if PyDict_CheckExact(other) {
  2001. PyObject *items;
  2002. if (PyDict_CheckExact(other))
  2003. items = PyDict_Items(other);
  2004. else
  2005. items = _PyObject_CallMethodId(other, &PyId_items, NULL);
  2006. Py_DECREF(other);
  2007. if (items == NULL)
  2008. return NULL;
  2009. res = mutablemapping_add_pairs(self, items);
  2010. Py_DECREF(items);
  2011. if (res == -1)
  2012. return NULL;
  2013. }
  2014. else if (_PyObject_HasAttrId(other, &PyId_keys)) { /* never fails */
  2015. PyObject *keys, *iterator, *key;
  2016. keys = _PyObject_CallMethodIdObjArgs(other, &PyId_keys, NULL);
  2017. if (keys == NULL) {
  2018. Py_DECREF(other);
  2019. return NULL;
  2020. }
  2021. iterator = PyObject_GetIter(keys);
  2022. Py_DECREF(keys);
  2023. if (iterator == NULL) {
  2024. Py_DECREF(other);
  2025. return NULL;
  2026. }
  2027. while (res == 0 && (key = PyIter_Next(iterator))) {
  2028. PyObject *value = PyObject_GetItem(other, key);
  2029. if (value != NULL) {
  2030. res = PyObject_SetItem(self, key, value);
  2031. Py_DECREF(value);
  2032. }
  2033. else {
  2034. res = -1;
  2035. }
  2036. Py_DECREF(key);
  2037. }
  2038. Py_DECREF(other);
  2039. Py_DECREF(iterator);
  2040. if (res != 0 || PyErr_Occurred())
  2041. return NULL;
  2042. }
  2043. else if (_PyObject_HasAttrId(other, &PyId_items)) { /* never fails */
  2044. PyObject *items;
  2045. if (PyDict_CheckExact(other))
  2046. items = PyDict_Items(other);
  2047. else
  2048. items = _PyObject_CallMethodId(other, &PyId_items, NULL);
  2049. Py_DECREF(other);
  2050. if (items == NULL)
  2051. return NULL;
  2052. res = mutablemapping_add_pairs(self, items);
  2053. Py_DECREF(items);
  2054. if (res == -1)
  2055. return NULL;
  2056. }
  2057. else {
  2058. res = mutablemapping_add_pairs(self, other);
  2059. Py_DECREF(other);
  2060. if (res != 0)
  2061. return NULL;
  2062. }
  2063. }
  2064. /* now handle kwargs */
  2065. assert(kwargs == NULL || PyDict_Check(kwargs));
  2066. len = (kwargs != NULL) ? PyDict_Size(kwargs) : 0;
  2067. if (len > 0) {
  2068. PyObject *items = PyDict_Items(kwargs);
  2069. if (items == NULL)
  2070. return NULL;
  2071. res = mutablemapping_add_pairs(self, items);
  2072. Py_DECREF(items);
  2073. if (res == -1)
  2074. return NULL;
  2075. }
  2076. Py_RETURN_NONE;
  2077. }