blob: 7df419e0ff67bad63825658719377b988a441792 [file] [log] [blame]
Eric Snow96c6af92015-05-29 22:21:39 -06001/* Ordered Dictionary object implementation.
2
3This implementation is necessarily explicitly equivalent to the pure Python
4OrderedDict class in Lib/collections/__init__.py. The strategy there
5involves using a doubly-linked-list to capture the order. We keep to that
6strategy, using a lower-level linked-list.
7
8About the Linked-List
9=====================
10
11For the linked list we use a basic doubly-linked-list. Using a circularly-
12linked-list does have some benefits, but they don't apply so much here
13since OrderedDict is focused on the ends of the list (for the most part).
14Furthermore, there are some features of generic linked-lists that we simply
15don't need for OrderedDict. Thus a simple custom implementation meets our
16needs. Alternatives to our simple approach include the QCIRCLE_*
17macros from BSD's queue.h, and the linux's list.h.
18
19Getting O(1) Node Lookup
20------------------------
21
22One invariant of Python's OrderedDict is that it preserves time complexity
23of dict's methods, particularly the O(1) operations. Simply adding a
24linked-list on top of dict is not sufficient here; operations for nodes in
25the middle of the linked-list implicitly require finding the node first.
26With a simple linked-list like we're using, that is an O(n) operation.
27Consequently, methods like __delitem__() would change from O(1) to O(n),
28which is unacceptable.
29
30In order to preserve O(1) performance for node removal (finding nodes), we
31must do better than just looping through the linked-list. Here are options
32we've considered:
33
341. use a second dict to map keys to nodes (a la the pure Python version).
352. keep a simple hash table mirroring the order of dict's, mapping each key
36 to the corresponding node in the linked-list.
373. use a version of shared keys (split dict) that allows non-unicode keys.
384. have the value stored for each key be a (value, node) pair, and adjust
39 __getitem__(), get(), etc. accordingly.
40
41The approach with the least performance impact (time and space) is #2,
42mirroring the key order of dict's dk_enties with an array of node pointers.
43While lookdict() and friends (dk_lookup) don't give us the index into the
44array, we make use of pointer arithmetic to get that index. An alternative
45would be to refactor lookdict() to provide the index, explicitly exposing
46the implementation detail. We could even just use a custom lookup function
47for OrderedDict that facilitates our need. However, both approaches are
48significantly more complicated than just using pointer arithmetic.
49
50The catch with mirroring the hash table ordering is that we have to keep
51the ordering in sync through any dict resizes. However, that order only
52matters during node lookup. We can simply defer any potential resizing
53until we need to do a lookup.
54
55Linked-List Nodes
56-----------------
57
58The current implementation stores a pointer to the associated key only.
59One alternative would be to store a pointer to the PyDictKeyEntry instead.
60This would save one pointer de-reference per item, which is nice during
61calls to values() and items(). However, it adds unnecessary overhead
62otherwise, so we stick with just the key.
63
64Linked-List API
65---------------
66
67As noted, the linked-list implemented here does not have all the bells and
68whistles. However, we recognize that the implementation may need to
69change to accommodate performance improvements or extra functionality. To
70that end, We use a simple API to interact with the linked-list. Here's a
71summary of the methods/macros:
72
73Node info:
74
75* _odictnode_KEY(node)
76* _odictnode_VALUE(od, node)
77* _odictnode_PREV(node)
78* _odictnode_NEXT(node)
79
80Linked-List info:
81
82* _odict_FIRST(od)
83* _odict_LAST(od)
84* _odict_EMPTY(od)
85* _odict_FOREACH(od, node) - used in place of `for (node=...)`
86
87For adding nodes:
88
89* _odict_add_head(od, node)
90* _odict_add_tail(od, node)
91* _odict_add_new_node(od, key)
92
93For removing nodes:
94
95* _odict_pop_node(od, node, key)
96* _odict_clear_node(od, node)
97* _odict_clear_nodes(od, clear_each)
98
99Others:
100
Eric Snow96c6af92015-05-29 22:21:39 -0600101* _odict_find_node(od, key)
102* _odict_keys_equal(od1, od2)
103
104Used, but specific to the linked-list implementation:
105
106* _odict_free_fast_nodes(od)
107
108And here's a look at how the linked-list relates to the OrderedDict API:
109
110============ === === ==== ==== ==== === ==== ===== ==== ==== === ==== === ===
111method key val prev next mem 1st last empty iter find add rmv clr keq
112============ === === ==== ==== ==== === ==== ===== ==== ==== === ==== === ===
113__del__ ~ X
114__delitem__ free ~ node
115__eq__ ~ X
116__iter__ X X
117__new__ X X
118__reduce__ X ~ X
119__repr__ X X X
120__reversed__ X X
121__setitem__ key
122__sizeof__ size X
123clear ~ ~ X
124copy X X X
125items X X X
126keys X X
127move_to_end X X X ~ h/t key
128pop free key
129popitem X X free X X node
130setdefault ~ ? ~
131values X X
132============ === === ==== ==== ==== === ==== ===== ==== ==== === ==== === ===
133
134__delitem__ is the only method that directly relies on finding an arbitrary
135node in the linked-list. Everything else is iteration or relates to the
136ends of the linked-list.
137
138Situation that Endangers Consistency
139------------------------------------
140Using a raw linked-list for OrderedDict exposes a key situation that can
141cause problems. If a node is stored in a variable, there is a chance that
142the node may have been deallocated before the variable gets used, thus
143potentially leading to a segmentation fault. A key place where this shows
144up is during iteration through the linked list (via _odict_FOREACH or
145otherwise).
146
147A number of solutions are available to resolve this situation:
148
149* defer looking up the node until as late as possible and certainly after
150 any code that could possibly result in a deletion;
151* if the node is needed both before and after a point where the node might
152 be removed, do a check before using the node at the "after" location to
153 see if the node is still valid;
154* like the last one, but simply pull the node again to ensure it's right;
155* keep the key in the variable instead of the node and then look up the
156 node using the key at the point where the node is needed (this is what
157 we do for the iterators).
158
159Another related problem, preserving consistent ordering during iteration,
160is described below. That one is not exclusive to using linked-lists.
161
162
163Challenges from Subclassing dict
164================================
165
166OrderedDict subclasses dict, which is an unusual relationship between two
167builtin types (other than the base object type). Doing so results in
168some complication and deserves further explanation. There are two things
169to consider here. First, in what circumstances or with what adjustments
170can OrderedDict be used as a drop-in replacement for dict (at the C level)?
171Second, how can the OrderedDict implementation leverage the dict
172implementation effectively without introducing unnecessary coupling or
173inefficiencies?
174
175This second point is reflected here and in the implementation, so the
176further focus is on the first point. It is worth noting that for
177overridden methods, the dict implementation is deferred to as much as
178possible. Furthermore, coupling is limited to as little as is reasonable.
179
180Concrete API Compatibility
181--------------------------
182
183Use of the concrete C-API for dict (PyDict_*) with OrderedDict is
184problematic. (See http://bugs.python.org/issue10977.) The concrete API
185has a number of hard-coded assumptions tied to the dict implementation.
186This is, in part, due to performance reasons, which is understandable
187given the part dict plays in Python.
188
189Any attempt to replace dict with OrderedDict for any role in the
190interpreter (e.g. **kwds) faces a challenge. Such any effort must
191recognize that the instances in affected locations currently interact with
192the concrete API.
193
194Here are some ways to address this challenge:
195
1961. Change the relevant usage of the concrete API in CPython and add
197 PyDict_CheckExact() calls to each of the concrete API funcions.
1982. Adjust the relevant concrete API functions to explicitly accommodate
199 OrderedDict.
2003. As with #1, add the checks, but improve the abstract API with smart fast
201 paths for dict and OrderedDict, and refactor CPython to use the abstract
202 API. Improvements to the abstract API would be valuable regardless.
203
204Adding the checks to the concrete API would help make any interpreter
205switch to OrderedDict less painful for extension modules. However, this
206won't work. The equivalent C API call to `dict.__setitem__(obj, k, v)`
207is 'PyDict_SetItem(obj, k, v)`. This illustrates how subclasses in C call
208the base class's methods, since there is no equivalent of super() in the
209C API. Calling into Python for parent class API would work, but some
210extension modules already rely on this feature of the concrete API.
211
212For reference, here is a breakdown of some of the dict concrete API:
213
214========================== ============= =======================
215concrete API uses abstract API
216========================== ============= =======================
217PyDict_Check PyMapping_Check
218(PyDict_CheckExact) -
219(PyDict_New) -
220(PyDictProxy_New) -
221PyDict_Clear -
222PyDict_Contains PySequence_Contains
223PyDict_Copy -
224PyDict_SetItem PyObject_SetItem
225PyDict_SetItemString PyMapping_SetItemString
226PyDict_DelItem PyMapping_DelItem
227PyDict_DelItemString PyMapping_DelItemString
228PyDict_GetItem -
229PyDict_GetItemWithError PyObject_GetItem
230_PyDict_GetItemIdWithError -
231PyDict_GetItemString PyMapping_GetItemString
232PyDict_Items PyMapping_Items
233PyDict_Keys PyMapping_Keys
234PyDict_Values PyMapping_Values
235PyDict_Size PyMapping_Size
236 PyMapping_Length
237PyDict_Next PyIter_Next
238_PyDict_Next -
239PyDict_Merge -
240PyDict_Update -
241PyDict_MergeFromSeq2 -
242PyDict_ClearFreeList -
243- PyMapping_HasKeyString
244- PyMapping_HasKey
245========================== ============= =======================
246
247
248The dict Interface Relative to OrderedDict
249==========================================
250
251Since OrderedDict subclasses dict, understanding the various methods and
252attributes of dict is important for implementing OrderedDict.
253
254Relevant Type Slots
255-------------------
256
257================= ================ =================== ================
258slot attribute object dict
259================= ================ =================== ================
260tp_dealloc - object_dealloc dict_dealloc
261tp_repr __repr__ object_repr dict_repr
262sq_contains __contains__ - dict_contains
263mp_length __len__ - dict_length
264mp_subscript __getitem__ - dict_subscript
265mp_ass_subscript __setitem__ - dict_ass_sub
266 __delitem__
267tp_hash __hash__ _Py_HashPointer ..._HashNotImpl
268tp_str __str__ object_str -
269tp_getattro __getattribute__ ..._GenericGetAttr (repeated)
270 __getattr__
271tp_setattro __setattr__ ..._GenericSetAttr (disabled)
272tp_doc __doc__ (literal) dictionary_doc
273tp_traverse - - dict_traverse
274tp_clear - - dict_tp_clear
275tp_richcompare __eq__ object_richcompare dict_richcompare
276 __ne__
277tp_weaklistoffset (__weakref__) - -
278tp_iter __iter__ - dict_iter
279tp_dictoffset (__dict__) - -
280tp_init __init__ object_init dict_init
281tp_alloc - PyType_GenericAlloc (repeated)
282tp_new __new__ object_new dict_new
283tp_free - PyObject_Del PyObject_GC_Del
284================= ================ =================== ================
285
286Relevant Methods
287----------------
288
289================ =================== ===============
290method object dict
291================ =================== ===============
292__reduce__ object_reduce -
293__sizeof__ object_sizeof dict_sizeof
294clear - dict_clear
295copy - dict_copy
296fromkeys - dict_fromkeys
297get - dict_get
298items - dictitems_new
299keys - dictkeys_new
300pop - dict_pop
301popitem - dict_popitem
302setdefault - dict_setdefault
303update - dict_update
304values - dictvalues_new
305================ =================== ===============
306
307
308Pure Python OrderedDict
309=======================
310
311As already noted, compatibility with the pure Python OrderedDict
312implementation is a key goal of this C implementation. To further that
313goal, here's a summary of how OrderedDict-specific methods are implemented
314in collections/__init__.py. Also provided is an indication of which
315methods directly mutate or iterate the object, as well as any relationship
316with the underlying linked-list.
317
318============= ============== == ================ === === ====
319method impl used ll uses inq mut iter
320============= ============== == ================ === === ====
321__contains__ dict - - X
322__delitem__ OrderedDict Y dict.__delitem__ X
323__eq__ OrderedDict N OrderedDict ~
324 dict.__eq__
325 __iter__
326__getitem__ dict - - X
327__iter__ OrderedDict Y - X
328__init__ OrderedDict N update
329__len__ dict - - X
330__ne__ MutableMapping - __eq__ ~
331__reduce__ OrderedDict N OrderedDict ~
332 __iter__
333 __getitem__
334__repr__ OrderedDict N __class__ ~
335 items
336__reversed__ OrderedDict Y - X
337__setitem__ OrderedDict Y __contains__ X
338 dict.__setitem__
339__sizeof__ OrderedDict Y __len__ ~
340 __dict__
341clear OrderedDict Y dict.clear X
342copy OrderedDict N __class__
343 __init__
344fromkeys OrderedDict N __setitem__
345get dict - - ~
346items MutableMapping - ItemsView X
347keys MutableMapping - KeysView X
348move_to_end OrderedDict Y - X
349pop OrderedDict N __contains__ X
350 __getitem__
351 __delitem__
352popitem OrderedDict Y dict.pop X
353setdefault OrderedDict N __contains__ ~
354 __getitem__
355 __setitem__
356update MutableMapping - __setitem__ ~
357values MutableMapping - ValuesView X
358============= ============== == ================ === === ====
359
360__reversed__ and move_to_end are both exclusive to OrderedDict.
361
362
363C OrderedDict Implementation
364============================
365
366================= ================
367slot impl
368================= ================
369tp_dealloc odict_dealloc
370tp_repr odict_repr
371mp_ass_subscript odict_ass_sub
372tp_doc odict_doc
373tp_traverse odict_traverse
374tp_clear odict_tp_clear
375tp_richcompare odict_richcompare
376tp_weaklistoffset (offset)
377tp_iter odict_iter
378tp_dictoffset (offset)
379tp_init odict_init
380tp_alloc (repeated)
381tp_new odict_new
382================= ================
383
384================= ================
385method impl
386================= ================
387__reduce__ odict_reduce
388__sizeof__ odict_sizeof
389clear odict_clear
390copy odict_copy
391fromkeys odict_fromkeys
392items odictitems_new
393keys odictkeys_new
394pop odict_pop
395popitem odict_popitem
396setdefault odict_setdefault
397update odict_update
398values odictvalues_new
399================= ================
400
401Inherited unchanged from object/dict:
402
403================ ==========================
404method type field
405================ ==========================
406- tp_free
407__contains__ tp_as_sequence.sq_contains
408__getattr__ tp_getattro
409__getattribute__ tp_getattro
410__getitem__ tp_as_mapping.mp_subscript
411__hash__ tp_hash
412__len__ tp_as_mapping.mp_length
413__setattr__ tp_setattro
414__str__ tp_str
415get -
416================ ==========================
417
418
419Other Challenges
420================
421
422Preserving Ordering During Iteration
423------------------------------------
424During iteration through an OrderedDict, it is possible that items could
425get added, removed, or reordered. For a linked-list implementation, as
426with some other implementations, that situation may lead to undefined
427behavior. The documentation for dict mentions this in the `iter()` section
428of http://docs.python.org/3.4/library/stdtypes.html#dictionary-view-objects.
429In this implementation we follow dict's lead (as does the pure Python
430implementation) for __iter__(), keys(), values(), and items().
431
432For internal iteration (using _odict_FOREACH or not), there is still the
433risk that not all nodes that we expect to be seen in the loop actually get
434seen. Thus, we are careful in each of those places to ensure that they
435are. This comes, of course, at a small price at each location. The
436solutions are much the same as those detailed in the `Situation that
437Endangers Consistency` section above.
438
439
440Potential Optimizations
441=======================
442
443* Allocate the nodes as a block via od_fast_nodes instead of individually.
444 - Set node->key to NULL to indicate the node is not-in-use.
445 - Add _odict_EXISTS()?
446 - How to maintain consistency across resizes? Existing node pointers
447 would be invalidate after a resize, which is particularly problematic
448 for the iterators.
449* Use a more stream-lined implementation of update() and, likely indirectly,
450 __init__().
451
452*/
453
454/* TODO
455
456sooner:
457- reentrancy (make sure everything is at a thread-safe state when calling
458 into Python). I've already checked this multiple times, but want to
459 make one more pass.
460- add unit tests for reentrancy?
461
462later:
463- make the dict views support the full set API (the pure Python impl does)
464- implement a fuller MutableMapping API in C?
465- move the MutableMapping implementation to abstract.c?
466- optimize mutablemapping_update
467- use PyObject_MALLOC (small object allocator) for odict nodes?
468- support subclasses better (e.g. in odict_richcompare)
469
470*/
471
472#include "Python.h"
473#include "structmember.h"
474#include "dict-common.h"
475#include <stddef.h>
476
477
478typedef struct _odictnode _ODictNode;
479
480/* PyODictObject */
481struct _odictobject {
Eric Snow4fabf022015-06-04 00:09:56 -0600482 PyDictObject od_dict; /* the underlying dict */
483 _ODictNode *od_first; /* first node in the linked list, if any */
484 _ODictNode *od_last; /* last node in the linked list, if any */
Eric Snow8c7f9552015-08-07 17:45:12 -0600485 /* od_fast_nodes and od_resize_sentinel are managed by _odict_resize()
486 * Note that we rely on implementation details of dict for both. */
487 _ODictNode **od_fast_nodes; /* hash table that mirrors the dict table */
488 Py_uintptr_t od_resize_sentinel; /* changes if odict should be resized */
489
Eric Snow4fabf022015-06-04 00:09:56 -0600490 size_t od_state; /* incremented whenever the LL changes */
491 PyObject *od_inst_dict; /* OrderedDict().__dict__ */
492 PyObject *od_weakreflist; /* holds weakrefs to the odict */
Eric Snow96c6af92015-05-29 22:21:39 -0600493};
494
495
496/* ----------------------------------------------
497 * odict keys (a simple doubly-linked list)
498 */
499
500struct _odictnode {
501 PyObject *key;
Eric Snow4c729182015-06-03 10:50:37 -0600502 Py_hash_t hash;
Eric Snow96c6af92015-05-29 22:21:39 -0600503 _ODictNode *next;
504 _ODictNode *prev;
505};
506
507#define _odictnode_KEY(node) \
508 (node->key)
Eric Snow4c729182015-06-03 10:50:37 -0600509#define _odictnode_HASH(node) \
510 (node->hash)
Eric Snow96c6af92015-05-29 22:21:39 -0600511/* borrowed reference */
512#define _odictnode_VALUE(node, od) \
Eric Snowa762af72015-06-01 22:59:08 -0600513 PyODict_GetItemWithError((PyObject *)od, _odictnode_KEY(node))
Eric Snow96c6af92015-05-29 22:21:39 -0600514#define _odictnode_PREV(node) (node->prev)
515#define _odictnode_NEXT(node) (node->next)
516
517#define _odict_FIRST(od) (((PyODictObject *)od)->od_first)
518#define _odict_LAST(od) (((PyODictObject *)od)->od_last)
519#define _odict_EMPTY(od) (_odict_FIRST(od) == NULL)
520#define _odict_FOREACH(od, node) \
521 for (node = _odict_FIRST(od); node != NULL; node = _odictnode_NEXT(node))
522
Eric Snow8c7f9552015-08-07 17:45:12 -0600523#define _odict_FAST_SIZE(od) ((PyDictObject *)od)->ma_keys->dk_size
Eric Snow96c6af92015-05-29 22:21:39 -0600524
Eric Snow96c6af92015-05-29 22:21:39 -0600525static void
526_odict_free_fast_nodes(PyODictObject *od) {
527 if (od->od_fast_nodes) {
528 PyMem_FREE(od->od_fast_nodes);
529 }
530}
531
Eric Snow4c729182015-06-03 10:50:37 -0600532/* Return the index into the hash table, regardless of a valid node. */
533static Py_ssize_t
534_odict_get_index_hash(PyODictObject *od, PyObject *key, Py_hash_t hash)
535{
536 PyObject **value_addr = NULL;
537 PyDictKeyEntry *ep;
538 PyDictKeysObject *keys = ((PyDictObject *)od)->ma_keys;
539
540 ep = (keys->dk_lookup)((PyDictObject *)od, key, hash, &value_addr);
541 if (ep == NULL)
542 return -1;
543 /* We use pointer arithmetic to get the entry's index into the table. */
544 return ep - keys->dk_entries;
545}
546
547/* Replace od->od_fast_nodes with a new table matching the size of dict's. */
Eric Snow96c6af92015-05-29 22:21:39 -0600548static int
549_odict_resize(PyODictObject *od) {
Eric Snow4c729182015-06-03 10:50:37 -0600550 Py_ssize_t size, i;
Eric Snow96c6af92015-05-29 22:21:39 -0600551 _ODictNode **fast_nodes, *node;
552
553 /* Initialize a new "fast nodes" table. */
554 size = ((PyDictObject *)od)->ma_keys->dk_size;
555 fast_nodes = PyMem_NEW(_ODictNode *, size);
556 if (fast_nodes == NULL) {
557 PyErr_NoMemory();
558 return -1;
559 }
560 for (i = 0; i < size; i++)
561 fast_nodes[i] = NULL;
562
563 /* Copy the current nodes into the table. */
Eric Snow96c6af92015-05-29 22:21:39 -0600564 _odict_FOREACH(od, node) {
Eric Snow4c729182015-06-03 10:50:37 -0600565 i = _odict_get_index_hash(od, _odictnode_KEY(node),
566 _odictnode_HASH(node));
Eric Snow96c6af92015-05-29 22:21:39 -0600567 if (i < 0) {
Eric Snow96c6af92015-05-29 22:21:39 -0600568 PyMem_FREE(fast_nodes);
569 return -1;
570 }
571 fast_nodes[i] = node;
572 }
Eric Snow96c6af92015-05-29 22:21:39 -0600573
574 /* Replace the old fast nodes table. */
575 _odict_free_fast_nodes(od);
576 od->od_fast_nodes = fast_nodes;
Eric Snow8c7f9552015-08-07 17:45:12 -0600577 od->od_resize_sentinel = (Py_uintptr_t)(((PyDictObject *)od)->ma_keys);
Eric Snow96c6af92015-05-29 22:21:39 -0600578 return 0;
579}
580
581/* Return the index into the hash table, regardless of a valid node. */
582static Py_ssize_t
583_odict_get_index(PyODictObject *od, PyObject *key)
584{
585 Py_hash_t hash;
Eric Snow4c729182015-06-03 10:50:37 -0600586 PyDictKeysObject *keys;
Eric Snow96c6af92015-05-29 22:21:39 -0600587
588 assert(key != NULL);
Eric Snow4c729182015-06-03 10:50:37 -0600589 hash = PyObject_Hash(key);
590 if (hash == -1)
Eric Snow96c6af92015-05-29 22:21:39 -0600591 return -1;
Eric Snow4c729182015-06-03 10:50:37 -0600592 keys = ((PyDictObject *)od)->ma_keys;
593
594 /* Ensure od_fast_nodes and dk_entries are in sync. */
Eric Snow8c7f9552015-08-07 17:45:12 -0600595 if (od->od_resize_sentinel != (Py_uintptr_t)keys) {
Eric Snow4c729182015-06-03 10:50:37 -0600596 int resize_res = _odict_resize(od);
597 if (resize_res < 0)
598 return -1;
599 }
600
601 return _odict_get_index_hash(od, key, hash);
Eric Snow96c6af92015-05-29 22:21:39 -0600602}
603
Eric Snow96c6af92015-05-29 22:21:39 -0600604/* Returns NULL if there was some error or the key was not found. */
605static _ODictNode *
606_odict_find_node(PyODictObject *od, PyObject *key)
607{
608 Py_ssize_t index;
609
610 if (_odict_EMPTY(od))
611 return NULL;
612 index = _odict_get_index(od, key);
613 if (index < 0)
614 return NULL;
615 return od->od_fast_nodes[index];
616}
617
618static void
619_odict_add_head(PyODictObject *od, _ODictNode *node)
620{
621 if (_odict_FIRST(od) == NULL) {
622 _odictnode_PREV(node) = NULL;
623 _odictnode_NEXT(node) = NULL;
624 _odict_FIRST(od) = node;
625 _odict_LAST(od) = node;
626 }
627 else {
628 _odictnode_PREV(node) = NULL;
629 _odictnode_NEXT(node) = _odict_FIRST(od);
630 _odict_FIRST(od) = node;
631 _odictnode_PREV(_odict_FIRST(od)) = node;
632 }
Eric Snow4fabf022015-06-04 00:09:56 -0600633 od->od_state++;
Eric Snow96c6af92015-05-29 22:21:39 -0600634}
635
636static void
637_odict_add_tail(PyODictObject *od, _ODictNode *node)
638{
639 if (_odict_LAST(od) == NULL) {
640 _odictnode_PREV(node) = NULL;
641 _odictnode_NEXT(node) = NULL;
642 _odict_FIRST(od) = node;
643 _odict_LAST(od) = node;
644 }
645 else {
646 _odictnode_PREV(node) = _odict_LAST(od);
647 _odictnode_NEXT(node) = NULL;
648 _odictnode_NEXT(_odict_LAST(od)) = node;
649 _odict_LAST(od) = node;
650 }
Eric Snow8c7f9552015-08-07 17:45:12 -0600651
Eric Snow4fabf022015-06-04 00:09:56 -0600652 od->od_state++;
Eric Snow96c6af92015-05-29 22:21:39 -0600653}
654
655/* adds the node to the end of the list */
656static int
657_odict_add_new_node(PyODictObject *od, PyObject *key)
658{
Eric Snow4c729182015-06-03 10:50:37 -0600659 Py_hash_t hash;
Eric Snow96c6af92015-05-29 22:21:39 -0600660 Py_ssize_t i;
661 _ODictNode *node;
662
663 Py_INCREF(key);
Eric Snow4c729182015-06-03 10:50:37 -0600664 hash = PyObject_Hash(key);
665 if (hash == -1)
666 return -1;
667
Eric Snow96c6af92015-05-29 22:21:39 -0600668 i = _odict_get_index(od, key);
669 if (i < 0) {
670 if (!PyErr_Occurred())
671 PyErr_SetObject(PyExc_KeyError, key);
672 Py_DECREF(key);
673 return -1;
674 }
675 else if (od->od_fast_nodes[i] != NULL) {
676 /* We already have a node for the key so there's no need to add one. */
677 Py_DECREF(key);
678 return 0;
679 }
680
681 /* must not be added yet */
682 node = (_ODictNode *)PyMem_MALLOC(sizeof(_ODictNode));
683 if (node == NULL) {
684 Py_DECREF(key);
685 PyErr_NoMemory();
686 return -1;
687 }
688
689 _odictnode_KEY(node) = key;
Eric Snow4c729182015-06-03 10:50:37 -0600690 _odictnode_HASH(node) = hash;
Eric Snow96c6af92015-05-29 22:21:39 -0600691 _odict_add_tail(od, node);
692 od->od_fast_nodes[i] = node;
693 return 0;
694}
695
696/* Putting the decref after the free causes problems. */
697#define _odictnode_DEALLOC(node) \
698 do { \
699 Py_DECREF(_odictnode_KEY(node)); \
700 PyMem_FREE((void *)node); \
701 } while (0)
702
703/* Repeated calls on the same node are no-ops. */
704static void
705_odict_remove_node(PyODictObject *od, _ODictNode *node)
706{
707 if (_odict_FIRST(od) == node)
708 _odict_FIRST(od) = _odictnode_NEXT(node);
709 else if (_odictnode_PREV(node) != NULL)
710 _odictnode_NEXT(_odictnode_PREV(node)) = _odictnode_NEXT(node);
711
712 if (_odict_LAST(od) == node)
713 _odict_LAST(od) = _odictnode_PREV(node);
714 else if (_odictnode_NEXT(node) != NULL)
715 _odictnode_PREV(_odictnode_NEXT(node)) = _odictnode_PREV(node);
716
717 _odictnode_PREV(node) = NULL;
718 _odictnode_NEXT(node) = NULL;
Eric Snow4fabf022015-06-04 00:09:56 -0600719 od->od_state++;
Eric Snow96c6af92015-05-29 22:21:39 -0600720}
721
722static _ODictNode *
723_odict_pop_node(PyODictObject *od, _ODictNode *node, PyObject *key)
724{
725 if (node == NULL) {
726 node = _odict_find_node(od, key);
727 if (node == NULL)
728 return NULL;
729 }
730 _odict_remove_node(od, node);
731 return node;
732}
733
734/* If someone calls PyDict_DelItem() directly on an OrderedDict, we'll
735 get all sorts of problems here. In PyODict_DelItem we make sure to
736 call _odict_clear_node first.
Victor Stinnerca30b022015-09-03 17:50:04 +0200737
Eric Snow96c6af92015-05-29 22:21:39 -0600738 This matters in the case of colliding keys. Suppose we add 3 keys:
739 [A, B, C], where the hash of C collides with A and the next possible
740 index in the hash table is occupied by B. If we remove B then for C
741 the dict's looknode func will give us the old index of B instead of
742 the index we got before deleting B. However, the node for C in
743 od_fast_nodes is still at the old dict index of C. Thus to be sure
744 things don't get out of sync, we clear the node in od_fast_nodes
745 *before* calling PyDict_DelItem.
746
747 The same must be done for any other OrderedDict operations where
748 we modify od_fast_nodes.
749*/
750static int
751_odict_clear_node(PyODictObject *od, _ODictNode *node, PyObject *key)
752{
753 Py_ssize_t i;
754
755 assert(key != NULL);
756 if (_odict_EMPTY(od)) {
757 /* Let later code decide if this is a KeyError. */
758 return 0;
759 }
760
761 i = _odict_get_index(od, key);
762 if (i < 0)
763 return PyErr_Occurred() ? -1 : 0;
764
765 if (node == NULL)
766 node = od->od_fast_nodes[i];
767 assert(node == od->od_fast_nodes[i]);
768 if (node == NULL) {
769 /* Let later code decide if this is a KeyError. */
770 return 0;
771 }
772
773 // Now clear the node.
774 od->od_fast_nodes[i] = NULL;
775 _odict_remove_node(od, node);
776 _odictnode_DEALLOC(node);
777 return 0;
778}
779
780static void
781_odict_clear_nodes(PyODictObject *od)
782{
783 _ODictNode *node, *next;
784
785 if (!_odict_EMPTY(od)) {
786 node = _odict_FIRST(od);
787 while (node != NULL) {
788 next = _odictnode_NEXT(node);
789 _odictnode_DEALLOC(node);
790 node = next;
791 }
792 _odict_FIRST(od) = NULL;
793 _odict_LAST(od) = NULL;
794 }
795
796 _odict_free_fast_nodes(od);
797 od->od_fast_nodes = NULL;
798}
799
800/* There isn't any memory management of nodes past this point. */
801#undef _odictnode_DEALLOC
802
803static int
804_odict_keys_equal(PyODictObject *a, PyODictObject *b)
805{
806 _ODictNode *node_a, *node_b;
807
808 node_a = _odict_FIRST(a);
809 node_b = _odict_FIRST(b);
810 while (1) {
811 if (node_a == NULL && node_b == NULL)
812 /* success: hit the end of each at the same time */
813 return 1;
814 else if (node_a == NULL || node_b == NULL)
815 /* unequal length */
816 return 0;
817 else {
818 int res = PyObject_RichCompareBool(
819 (PyObject *)_odictnode_KEY(node_a),
820 (PyObject *)_odictnode_KEY(node_b),
821 Py_EQ);
822 if (res < 0)
823 return res;
824 else if (res == 0)
825 return 0;
826
827 /* otherwise it must match, so move on to the next one */
828 node_a = _odictnode_NEXT(node_a);
829 node_b = _odictnode_NEXT(node_b);
830 }
831 }
832}
833
834
835/* ----------------------------------------------
836 * OrderedDict mapping methods
837 */
838
839/* mp_ass_subscript: __setitem__() and __delitem__() */
840
841static int
842odict_mp_ass_sub(PyODictObject *od, PyObject *v, PyObject *w)
843{
844 if (w == NULL)
845 return PyODict_DelItem((PyObject *)od, v);
846 else
847 return PyODict_SetItem((PyObject *)od, v, w);
848}
849
850/* tp_as_mapping */
851
852static PyMappingMethods odict_as_mapping = {
853 0, /*mp_length*/
854 0, /*mp_subscript*/
855 (objobjargproc)odict_mp_ass_sub, /*mp_ass_subscript*/
856};
857
858
859/* ----------------------------------------------
860 * OrderedDict methods
861 */
862
863/* __delitem__() */
864
865PyDoc_STRVAR(odict_delitem__doc__, "od.__delitem__(y) <==> del od[y]");
866
867/* __eq__() */
868
869PyDoc_STRVAR(odict_eq__doc__,
870"od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive \n\
871 while comparison to a regular mapping is order-insensitive.\n\
872 ");
873
874/* forward */
875static PyObject * odict_richcompare(PyObject *v, PyObject *w, int op);
876
877static PyObject *
878odict_eq(PyObject *a, PyObject *b)
879{
880 return odict_richcompare(a, b, Py_EQ);
881}
882
883/* __init__() */
884
885PyDoc_STRVAR(odict_init__doc__,
886"Initialize an ordered dictionary. The signature is the same as\n\
887 regular dictionaries, but keyword arguments are not recommended because\n\
888 their insertion order is arbitrary.\n\
889\n\
890 ");
891
892/* forward */
893static int odict_init(PyObject *self, PyObject *args, PyObject *kwds);
894
895/* __iter__() */
896
897PyDoc_STRVAR(odict_iter__doc__, "od.__iter__() <==> iter(od)");
898
899static PyObject * odict_iter(PyODictObject *self); /* forward */
900
901/* __ne__() */
902
903/* Mapping.__ne__() does not have a docstring. */
904PyDoc_STRVAR(odict_ne__doc__, "");
905
906static PyObject *
907odict_ne(PyObject *a, PyObject *b)
908{
909 return odict_richcompare(a, b, Py_NE);
910}
911
912/* __repr__() */
913
914PyDoc_STRVAR(odict_repr__doc__, "od.__repr__() <==> repr(od)");
915
916static PyObject * odict_repr(PyODictObject *self); /* forward */
917
918/* __setitem__() */
919
920PyDoc_STRVAR(odict_setitem__doc__, "od.__setitem__(i, y) <==> od[i]=y");
921
922/* fromkeys() */
923
924PyDoc_STRVAR(odict_fromkeys__doc__,
925"OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.\n\
926 If not specified, the value defaults to None.\n\
927\n\
928 ");
929
930static PyObject *
Eric Snowac02ef32015-06-02 20:42:14 -0600931odict_fromkeys(PyObject *cls, PyObject *args, PyObject *kwargs)
Eric Snow96c6af92015-05-29 22:21:39 -0600932{
Eric Snowac02ef32015-06-02 20:42:14 -0600933 static char *kwlist[] = {"iterable", "value", 0};
Eric Snow96c6af92015-05-29 22:21:39 -0600934 PyObject *seq;
935 PyObject *value = Py_None;
Eric Snowac02ef32015-06-02 20:42:14 -0600936
937 /* both borrowed */
938 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O:fromkeys", kwlist,
939 &seq, &value)) {
Eric Snow96c6af92015-05-29 22:21:39 -0600940 return NULL;
Eric Snowac02ef32015-06-02 20:42:14 -0600941 }
Eric Snow96c6af92015-05-29 22:21:39 -0600942 return _PyDict_FromKeys(cls, seq, value);
943}
944
945/* __sizeof__() */
946
947/* OrderedDict.__sizeof__() does not have a docstring. */
948PyDoc_STRVAR(odict_sizeof__doc__, "");
949
950static PyObject *
951odict_sizeof(PyODictObject *od)
952{
953 PyObject *pylong;
Eric Snowc5e59602015-05-30 11:28:56 -0600954 Py_ssize_t res, temp;
Eric Snow96c6af92015-05-29 22:21:39 -0600955
956 pylong = _PyDict_SizeOf((PyDictObject *)od);
957 if (pylong == NULL)
958 return NULL;
959 res = PyLong_AsSsize_t(pylong);
960 Py_DECREF(pylong);
961 if (res == -1 && PyErr_Occurred())
962 return NULL;
963
964 res += sizeof(PyODictObject) - sizeof(PyDictObject);
965
966 /* instance dict */
967 pylong = _PyDict_SizeOf((PyDictObject *)od->od_inst_dict);
968 if (pylong == NULL)
969 return NULL;
Eric Snowc5e59602015-05-30 11:28:56 -0600970 temp = PyLong_AsSsize_t(pylong);
Eric Snow96c6af92015-05-29 22:21:39 -0600971 Py_DECREF(pylong);
Eric Snowc5e59602015-05-30 11:28:56 -0600972 if (temp == -1 && PyErr_Occurred())
Eric Snow96c6af92015-05-29 22:21:39 -0600973 return NULL;
Eric Snowc5e59602015-05-30 11:28:56 -0600974 res += temp;
Eric Snow96c6af92015-05-29 22:21:39 -0600975
Eric Snow8c7f9552015-08-07 17:45:12 -0600976 res += sizeof(_ODictNode) * _odict_FAST_SIZE(od); /* od_fast_nodes */
Eric Snow96c6af92015-05-29 22:21:39 -0600977 if (!_odict_EMPTY(od)) {
978 res += sizeof(_ODictNode) * PyODict_SIZE(od); /* linked-list */
979 }
980 return PyLong_FromSsize_t(res);
981}
982
983/* __reduce__() */
984
985PyDoc_STRVAR(odict_reduce__doc__, "Return state information for pickling");
986
987static PyObject *
988odict_reduce(register PyODictObject *od)
989{
990 _Py_IDENTIFIER(__dict__);
991 _Py_IDENTIFIER(__class__);
992 PyObject *vars = NULL, *ns = NULL, *result = NULL, *cls = NULL;
993 PyObject *items_iter = NULL, *items = NULL, *args = NULL;
994
995 /* capture any instance state */
996 vars = _PyObject_GetAttrId((PyObject *)od, &PyId___dict__);
Eric Snowc5e59602015-05-30 11:28:56 -0600997 if (vars == NULL)
998 goto Done;
999 else {
Eric Snow96c6af92015-05-29 22:21:39 -06001000 PyObject *empty, *od_vars, *iterator, *key;
Victor Stinner4a0d1e72015-09-18 13:44:11 +02001001 Py_ssize_t ns_len;
Eric Snow96c6af92015-05-29 22:21:39 -06001002
1003 /* od.__dict__ isn't necessarily a dict... */
1004 ns = PyObject_CallMethod((PyObject *)vars, "copy", NULL);
1005 if (ns == NULL)
1006 goto Done;
1007 empty = PyODict_New();
1008 if (empty == NULL)
1009 goto Done;
1010 od_vars = _PyObject_GetAttrId((PyObject *)empty, &PyId___dict__);
1011 Py_DECREF(empty);
1012 if (od_vars == NULL)
1013 goto Done;
1014 iterator = PyObject_GetIter(od_vars);
1015 Py_DECREF(od_vars);
1016 if (iterator == NULL)
1017 goto Done;
1018
1019 while ( (key = PyIter_Next(iterator)) ) {
1020 if (PyMapping_HasKey(ns, key) && PyMapping_DelItem(ns, key) != 0) {
1021 Py_DECREF(iterator);
1022 Py_DECREF(key);
1023 goto Done;
1024 }
1025 Py_DECREF(key);
1026 }
1027 Py_DECREF(iterator);
1028 if (PyErr_Occurred())
1029 goto Done;
1030
Eric Snowc5e59602015-05-30 11:28:56 -06001031 ns_len = PyObject_Length(ns);
1032 if (ns_len == -1)
1033 goto Done;
1034 if (!ns_len) {
Eric Snow96c6af92015-05-29 22:21:39 -06001035 /* nothing novel to pickle in od.__dict__ */
Eric Snowe3dfa9e2015-05-30 12:51:15 -06001036 Py_CLEAR(ns);
Eric Snow96c6af92015-05-29 22:21:39 -06001037 }
1038 }
1039
1040 /* build the result */
1041 cls = _PyObject_GetAttrId((PyObject *)od, &PyId___class__);
1042 if (cls == NULL)
1043 goto Done;
1044
1045 args = PyTuple_New(0);
1046 if (args == NULL)
1047 goto Done;
1048
1049 items = PyObject_CallMethod((PyObject *)od, "items", NULL);
1050 if (items == NULL)
1051 goto Done;
1052
1053 items_iter = PyObject_GetIter(items);
1054 if (items_iter == NULL)
1055 goto Done;
1056
1057 result = PyTuple_Pack(5, cls, args, ns ? ns : Py_None, Py_None, items_iter);
1058
1059Done:
1060 Py_XDECREF(vars);
1061 Py_XDECREF(ns);
1062 Py_XDECREF(cls);
1063 Py_XDECREF(args);
1064 Py_XDECREF(items);
1065 Py_XDECREF(items_iter);
1066
1067 return result;
1068}
1069
1070/* setdefault() */
1071
1072PyDoc_STRVAR(odict_setdefault__doc__,
1073 "od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od");
1074
1075/* Skips __missing__() calls. */
1076static PyObject *
Eric Snowac02ef32015-06-02 20:42:14 -06001077odict_setdefault(register PyODictObject *od, PyObject *args, PyObject *kwargs)
Eric Snow96c6af92015-05-29 22:21:39 -06001078{
Eric Snowac02ef32015-06-02 20:42:14 -06001079 static char *kwlist[] = {"key", "default", 0};
Eric Snow96c6af92015-05-29 22:21:39 -06001080 PyObject *key, *result = NULL;
1081 PyObject *failobj = Py_None;
1082
1083 /* both borrowed */
Eric Snowac02ef32015-06-02 20:42:14 -06001084 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O:setdefault", kwlist,
1085 &key, &failobj)) {
Eric Snow96c6af92015-05-29 22:21:39 -06001086 return NULL;
Eric Snowac02ef32015-06-02 20:42:14 -06001087 }
Eric Snow96c6af92015-05-29 22:21:39 -06001088
1089 if (PyODict_CheckExact(od)) {
Eric Snowd1719752015-06-01 23:12:13 -06001090 result = PyODict_GetItemWithError(od, key); /* borrowed */
1091 if (result == NULL) {
1092 if (PyErr_Occurred())
1093 return NULL;
1094 assert(_odict_find_node(od, key) == NULL);
1095 if (PyODict_SetItem((PyObject *)od, key, failobj) >= 0) {
Eric Snow96c6af92015-05-29 22:21:39 -06001096 result = failobj;
1097 Py_INCREF(failobj);
1098 }
1099 }
1100 else {
Eric Snowd1719752015-06-01 23:12:13 -06001101 Py_INCREF(result);
Eric Snow96c6af92015-05-29 22:21:39 -06001102 }
1103 }
1104 else {
1105 int exists = PySequence_Contains((PyObject *)od, key);
1106 if (exists < 0) {
Eric Snowd1719752015-06-01 23:12:13 -06001107 return NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06001108 }
1109 else if (exists) {
1110 result = PyObject_GetItem((PyObject *)od, key);
1111 }
1112 else if (PyObject_SetItem((PyObject *)od, key, failobj) >= 0) {
1113 result = failobj;
1114 Py_INCREF(failobj);
1115 }
1116 }
1117
Eric Snow96c6af92015-05-29 22:21:39 -06001118 return result;
1119}
1120
1121/* pop() */
1122
1123PyDoc_STRVAR(odict_pop__doc__,
1124"od.pop(k[,d]) -> v, remove specified key and return the corresponding\n\
1125 value. If key is not found, d is returned if given, otherwise KeyError\n\
1126 is raised.\n\
1127\n\
1128 ");
1129
1130/* forward */
1131static PyObject * _odict_popkey(PyObject *, PyObject *, PyObject *);
1132
1133/* Skips __missing__() calls. */
1134static PyObject *
Eric Snowac02ef32015-06-02 20:42:14 -06001135odict_pop(PyObject *od, PyObject *args, PyObject *kwargs)
Eric Snow96c6af92015-05-29 22:21:39 -06001136{
Eric Snowac02ef32015-06-02 20:42:14 -06001137 static char *kwlist[] = {"key", "default", 0};
Eric Snow96c6af92015-05-29 22:21:39 -06001138 PyObject *key, *failobj = NULL;
1139
Eric Snowac02ef32015-06-02 20:42:14 -06001140 /* borrowed */
1141 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O:pop", kwlist,
1142 &key, &failobj)) {
Eric Snow96c6af92015-05-29 22:21:39 -06001143 return NULL;
1144 }
1145
1146 return _odict_popkey(od, key, failobj);
1147}
1148
1149static PyObject *
1150_odict_popkey(PyObject *od, PyObject *key, PyObject *failobj)
1151{
1152 _ODictNode *node;
1153 PyObject *value = NULL;
1154
Eric Snow96c6af92015-05-29 22:21:39 -06001155 /* Pop the node first to avoid a possible dict resize (due to
1156 eval loop reentrancy) and complications due to hash collision
1157 resolution. */
1158 node = _odict_find_node((PyODictObject *)od, key);
1159 if (node == NULL) {
1160 if (PyErr_Occurred())
Eric Snowd1719752015-06-01 23:12:13 -06001161 return NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06001162 }
1163 else {
1164 int res = _odict_clear_node((PyODictObject *)od, node, key);
1165 if (res < 0) {
Eric Snowd1719752015-06-01 23:12:13 -06001166 return NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06001167 }
1168 }
1169
1170 /* Now delete the value from the dict. */
1171 if (PyODict_CheckExact(od)) {
1172 if (node != NULL) {
1173 /* We could do PyDict_GetItem() and PyDict_DelItem() directly... */
1174 value = _PyDict_Pop((PyDictObject *)od, key, failobj);
1175 }
1176 }
1177 else {
1178 int exists = PySequence_Contains(od, key);
1179 if (exists < 0)
Eric Snowd1719752015-06-01 23:12:13 -06001180 return NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06001181 if (exists) {
1182 value = PyObject_GetItem(od, key);
1183 if (value != NULL) {
1184 if (PyObject_DelItem(od, key) == -1) {
Eric Snowe3dfa9e2015-05-30 12:51:15 -06001185 Py_CLEAR(value);
Eric Snow96c6af92015-05-29 22:21:39 -06001186 }
1187 }
1188 }
1189 }
1190
1191 /* Apply the fallback value, if necessary. */
1192 if (value == NULL && !PyErr_Occurred()) {
1193 if (failobj) {
1194 value = failobj;
1195 Py_INCREF(failobj);
1196 }
1197 else {
1198 PyErr_SetObject(PyExc_KeyError, key);
1199 }
1200 }
1201
Eric Snow96c6af92015-05-29 22:21:39 -06001202 return value;
1203}
1204
1205/* popitem() */
1206
1207PyDoc_STRVAR(odict_popitem__doc__,
1208"od.popitem() -> (k, v), return and remove a (key, value) pair.\n\
1209 Pairs are returned in LIFO order if last is true or FIFO order if false.\n\
1210\n\
1211 ");
1212
1213static PyObject *
Eric Snowac02ef32015-06-02 20:42:14 -06001214odict_popitem(PyObject *od, PyObject *args, PyObject *kwargs)
Eric Snow96c6af92015-05-29 22:21:39 -06001215{
Eric Snowac02ef32015-06-02 20:42:14 -06001216 static char *kwlist[] = {"last", 0};
Eric Snow96c6af92015-05-29 22:21:39 -06001217 PyObject *key, *value, *item = NULL, *last = NULL;
1218 _ODictNode *node;
Eric Snowac02ef32015-06-02 20:42:14 -06001219 int pos = -1;
Eric Snow96c6af92015-05-29 22:21:39 -06001220
1221 if (_odict_EMPTY((PyODictObject *)od)) {
1222 PyErr_SetString(PyExc_KeyError, "dictionary is empty");
1223 return NULL;
1224 }
1225
1226 /* pull the item */
1227
Eric Snowac02ef32015-06-02 20:42:14 -06001228 /* borrowed */
1229 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O:popitem", kwlist,
1230 &last)) {
Eric Snow96c6af92015-05-29 22:21:39 -06001231 return NULL;
Eric Snowac02ef32015-06-02 20:42:14 -06001232 }
Eric Snow96c6af92015-05-29 22:21:39 -06001233
Eric Snowac02ef32015-06-02 20:42:14 -06001234 if (last != NULL) {
1235 int is_true;
1236 is_true = PyObject_IsTrue(last);
1237 if (is_true == -1)
1238 return NULL;
1239 pos = is_true ? -1 : 0;
1240 }
1241 if (pos == 0)
Eric Snow96c6af92015-05-29 22:21:39 -06001242 node = _odict_FIRST((PyODictObject *)od);
Eric Snowac02ef32015-06-02 20:42:14 -06001243 else
1244 node = _odict_LAST((PyODictObject *)od);
Eric Snow96c6af92015-05-29 22:21:39 -06001245
1246 key = _odictnode_KEY(node);
Eric Snowd1719752015-06-01 23:12:13 -06001247 Py_INCREF(key);
Eric Snow96c6af92015-05-29 22:21:39 -06001248 value = _odict_popkey(od, key, NULL);
1249 if (value == NULL)
1250 return NULL;
1251 item = PyTuple_Pack(2, key, value);
Eric Snowd1719752015-06-01 23:12:13 -06001252 Py_DECREF(key);
Eric Snow96c6af92015-05-29 22:21:39 -06001253 Py_DECREF(value);
1254 return item;
1255}
1256
1257/* keys() */
1258
1259/* MutableMapping.keys() does not have a docstring. */
1260PyDoc_STRVAR(odict_keys__doc__, "");
1261
1262static PyObject * odictkeys_new(PyObject *od); /* forward */
1263
1264/* values() */
1265
1266/* MutableMapping.values() does not have a docstring. */
1267PyDoc_STRVAR(odict_values__doc__, "");
1268
1269static PyObject * odictvalues_new(PyObject *od); /* forward */
1270
1271/* items() */
1272
1273/* MutableMapping.items() does not have a docstring. */
1274PyDoc_STRVAR(odict_items__doc__, "");
1275
1276static PyObject * odictitems_new(PyObject *od); /* forward */
1277
1278/* update() */
1279
1280/* MutableMapping.update() does not have a docstring. */
1281PyDoc_STRVAR(odict_update__doc__, "");
1282
1283/* forward */
1284static PyObject * mutablemapping_update(PyObject *, PyObject *, PyObject *);
1285
1286#define odict_update mutablemapping_update
1287
1288/* clear() */
1289
1290PyDoc_STRVAR(odict_clear__doc__,
1291 "od.clear() -> None. Remove all items from od.");
1292
1293static PyObject *
1294odict_clear(register PyODictObject *od)
1295{
1296 PyDict_Clear((PyObject *)od);
1297 _odict_clear_nodes(od);
1298 _odict_FIRST(od) = NULL;
1299 _odict_LAST(od) = NULL;
1300 if (_odict_resize(od) < 0)
1301 return NULL;
1302 Py_RETURN_NONE;
1303}
1304
1305/* copy() */
1306
1307PyDoc_STRVAR(odict_copy__doc__, "od.copy() -> a shallow copy of od");
1308
1309static PyObject *
1310odict_copy(register PyODictObject *od)
1311{
1312 _ODictNode *node;
1313 PyObject *od_copy;
1314
1315 if (PyODict_CheckExact(od))
1316 od_copy = PyODict_New();
1317 else
1318 od_copy = PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(od), NULL);
1319 if (od_copy == NULL)
1320 return NULL;
1321
1322 if (PyODict_CheckExact(od)) {
1323 _odict_FOREACH(od, node) {
Eric Snowa762af72015-06-01 22:59:08 -06001324 PyObject *key = _odictnode_KEY(node);
1325 PyObject *value = _odictnode_VALUE(node, od);
1326 if (value == NULL) {
1327 if (!PyErr_Occurred())
1328 PyErr_SetObject(PyExc_KeyError, key);
1329 goto fail;
1330 }
1331 if (PyODict_SetItem((PyObject *)od_copy, key, value) != 0)
Eric Snow96c6af92015-05-29 22:21:39 -06001332 goto fail;
1333 }
1334 }
1335 else {
1336 _odict_FOREACH(od, node) {
1337 int res;
1338 PyObject *value = PyObject_GetItem((PyObject *)od,
1339 _odictnode_KEY(node));
1340 if (value == NULL)
1341 goto fail;
1342 res = PyObject_SetItem((PyObject *)od_copy,
1343 _odictnode_KEY(node), value);
1344 Py_DECREF(value);
1345 if (res != 0)
1346 goto fail;
1347 }
1348 }
1349 return od_copy;
1350
1351fail:
1352 Py_DECREF(od_copy);
1353 return NULL;
1354}
1355
1356/* __reversed__() */
1357
1358PyDoc_STRVAR(odict_reversed__doc__, "od.__reversed__() <==> reversed(od)");
1359
1360#define _odict_ITER_REVERSED 1
1361#define _odict_ITER_KEYS 2
1362#define _odict_ITER_VALUES 4
1363
1364/* forward */
1365static PyObject * odictiter_new(PyODictObject *, int);
1366
1367static PyObject *
1368odict_reversed(PyODictObject *od)
1369{
Eric Snow96c6af92015-05-29 22:21:39 -06001370 return odictiter_new(od, _odict_ITER_KEYS|_odict_ITER_REVERSED);
1371}
1372
1373/* move_to_end() */
1374
1375PyDoc_STRVAR(odict_move_to_end__doc__,
1376"Move an existing element to the end (or beginning if last==False).\n\
1377\n\
1378 Raises KeyError if the element does not exist.\n\
1379 When last=True, acts like a fast version of self[key]=self.pop(key).\n\
1380\n\
1381 ");
1382
1383static PyObject *
Eric Snowac02ef32015-06-02 20:42:14 -06001384odict_move_to_end(PyODictObject *od, PyObject *args, PyObject *kwargs)
Eric Snow96c6af92015-05-29 22:21:39 -06001385{
Eric Snowac02ef32015-06-02 20:42:14 -06001386 static char *kwlist[] = {"key", "last", 0};
Eric Snow96c6af92015-05-29 22:21:39 -06001387 PyObject *key, *last = NULL;
1388 Py_ssize_t pos = -1;
1389
1390 /* both borrowed */
Eric Snowac02ef32015-06-02 20:42:14 -06001391 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O:move_to_end", kwlist,
1392 &key, &last)) {
Eric Snow96c6af92015-05-29 22:21:39 -06001393 return NULL;
Eric Snowac02ef32015-06-02 20:42:14 -06001394 }
Eric Snow96c6af92015-05-29 22:21:39 -06001395 if (_odict_EMPTY(od)) {
1396 PyErr_SetObject(PyExc_KeyError, key);
Eric Snow96c6af92015-05-29 22:21:39 -06001397 return NULL;
1398 }
1399 if (last != NULL) {
Eric Snowc5e59602015-05-30 11:28:56 -06001400 int is_true;
Eric Snowc5e59602015-05-30 11:28:56 -06001401 is_true = PyObject_IsTrue(last);
Eric Snowc5e59602015-05-30 11:28:56 -06001402 if (is_true == -1)
1403 return NULL;
1404 pos = is_true ? -1 : 0;
Eric Snow96c6af92015-05-29 22:21:39 -06001405 }
1406 if (pos == 0) {
1407 /* Only move if not already the first one. */
1408 PyObject *first_key = _odictnode_KEY(_odict_FIRST(od));
Eric Snowc5e59602015-05-30 11:28:56 -06001409 int not_equal = PyObject_RichCompareBool(key, first_key, Py_NE);
1410 if (not_equal == -1)
1411 return NULL;
1412 if (not_equal) {
Eric Snow96c6af92015-05-29 22:21:39 -06001413 _ODictNode *node = _odict_pop_node(od, NULL, key);
1414 if (node != NULL) {
1415 _odict_add_head(od, node);
1416 }
1417 else {
1418 if (!PyErr_Occurred())
1419 PyErr_SetObject(PyExc_KeyError, key);
Eric Snow96c6af92015-05-29 22:21:39 -06001420 return NULL;
1421 }
1422 }
1423 }
1424 else if (pos == -1) {
1425 /* Only move if not already the last one. */
1426 PyObject *last_key = _odictnode_KEY(_odict_LAST(od));
Eric Snowc5e59602015-05-30 11:28:56 -06001427 int not_equal = PyObject_RichCompareBool(key, last_key, Py_NE);
1428 if (not_equal == -1)
1429 return NULL;
1430 if (not_equal) {
Eric Snow96c6af92015-05-29 22:21:39 -06001431 _ODictNode *node = _odict_pop_node(od, NULL, key);
1432 if (node != NULL) {
1433 _odict_add_tail(od, node);
1434 }
1435 else {
1436 if (!PyErr_Occurred())
1437 PyErr_SetObject(PyExc_KeyError, key);
Eric Snow96c6af92015-05-29 22:21:39 -06001438 return NULL;
1439 }
1440 }
1441 }
Eric Snow96c6af92015-05-29 22:21:39 -06001442 Py_RETURN_NONE;
1443}
1444
1445
1446/* tp_methods */
1447
1448static PyMethodDef odict_methods[] = {
1449
1450 /* explicitly defined so we can align docstrings with
1451 * collections.OrderedDict */
1452 {"__delitem__", (PyCFunction)odict_mp_ass_sub, METH_NOARGS,
1453 odict_delitem__doc__},
1454 {"__eq__", (PyCFunction)odict_eq, METH_NOARGS,
1455 odict_eq__doc__},
1456 {"__init__", (PyCFunction)odict_init, METH_NOARGS,
1457 odict_init__doc__},
1458 {"__iter__", (PyCFunction)odict_iter, METH_NOARGS,
1459 odict_iter__doc__},
1460 {"__ne__", (PyCFunction)odict_ne, METH_NOARGS,
1461 odict_ne__doc__},
1462 {"__repr__", (PyCFunction)odict_repr, METH_NOARGS,
1463 odict_repr__doc__},
1464 {"__setitem__", (PyCFunction)odict_mp_ass_sub, METH_NOARGS,
1465 odict_setitem__doc__},
Eric Snowac02ef32015-06-02 20:42:14 -06001466 {"fromkeys", (PyCFunction)odict_fromkeys,
1467 METH_VARARGS | METH_KEYWORDS | METH_CLASS, odict_fromkeys__doc__},
Eric Snow96c6af92015-05-29 22:21:39 -06001468
1469 /* overridden dict methods */
1470 {"__sizeof__", (PyCFunction)odict_sizeof, METH_NOARGS,
1471 odict_sizeof__doc__},
1472 {"__reduce__", (PyCFunction)odict_reduce, METH_NOARGS,
1473 odict_reduce__doc__},
Eric Snowac02ef32015-06-02 20:42:14 -06001474 {"setdefault", (PyCFunction)odict_setdefault,
1475 METH_VARARGS | METH_KEYWORDS, odict_setdefault__doc__},
1476 {"pop", (PyCFunction)odict_pop,
1477 METH_VARARGS | METH_KEYWORDS, odict_pop__doc__},
1478 {"popitem", (PyCFunction)odict_popitem,
1479 METH_VARARGS | METH_KEYWORDS, odict_popitem__doc__},
Eric Snow96c6af92015-05-29 22:21:39 -06001480 {"keys", (PyCFunction)odictkeys_new, METH_NOARGS,
1481 odict_keys__doc__},
1482 {"values", (PyCFunction)odictvalues_new, METH_NOARGS,
1483 odict_values__doc__},
1484 {"items", (PyCFunction)odictitems_new, METH_NOARGS,
1485 odict_items__doc__},
1486 {"update", (PyCFunction)odict_update, METH_VARARGS | METH_KEYWORDS,
1487 odict_update__doc__},
1488 {"clear", (PyCFunction)odict_clear, METH_NOARGS,
1489 odict_clear__doc__},
1490 {"copy", (PyCFunction)odict_copy, METH_NOARGS,
1491 odict_copy__doc__},
1492
1493 /* new methods */
1494 {"__reversed__", (PyCFunction)odict_reversed, METH_NOARGS,
1495 odict_reversed__doc__},
Eric Snowac02ef32015-06-02 20:42:14 -06001496 {"move_to_end", (PyCFunction)odict_move_to_end,
1497 METH_VARARGS | METH_KEYWORDS, odict_move_to_end__doc__},
Eric Snow96c6af92015-05-29 22:21:39 -06001498
1499 {NULL, NULL} /* sentinel */
1500};
1501
1502
1503/* ----------------------------------------------
1504 * OrderedDict members
1505 */
1506
1507/* tp_members */
1508
1509static PyMemberDef odict_members[] = {
1510 {"__dict__", T_OBJECT, offsetof(PyODictObject, od_inst_dict), READONLY},
1511 {0}
1512};
1513
1514
1515/* ----------------------------------------------
1516 * OrderedDict type slot methods
1517 */
1518
1519/* tp_dealloc */
1520
1521static void
1522odict_dealloc(PyODictObject *self)
1523{
1524 PyObject_GC_UnTrack(self);
1525 Py_TRASHCAN_SAFE_BEGIN(self);
1526 Py_XDECREF(self->od_inst_dict);
1527 if (self->od_weakreflist != NULL)
1528 PyObject_ClearWeakRefs((PyObject *)self);
1529
1530 _odict_clear_nodes(self);
1531 Py_TRASHCAN_SAFE_END(self);
1532
1533 /* must be last */
1534 PyDict_Type.tp_dealloc((PyObject *)self);
1535};
1536
1537/* tp_repr */
1538
1539static PyObject *
1540odict_repr(PyODictObject *self)
1541{
1542 int i;
1543 const char *formatstr;
1544 _Py_IDENTIFIER(__class__);
1545 _Py_IDENTIFIER(__name__);
1546 Py_ssize_t count = -1;
1547 PyObject *pieces = NULL, *result = NULL, *cls = NULL;
1548 PyObject *classname = NULL, *format = NULL, *args = NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06001549
1550 i = Py_ReprEnter((PyObject *)self);
1551 if (i != 0) {
1552 return i > 0 ? PyUnicode_FromString("...") : NULL;
1553 }
1554
1555 if (PyODict_SIZE(self) == 0) {
1556 /* "OrderedDict()" */
1557 goto Finish;
1558 }
1559
1560 if (PyODict_CheckExact(self)) {
Eric Snowa762af72015-06-01 22:59:08 -06001561 _ODictNode *node;
Eric Snow96c6af92015-05-29 22:21:39 -06001562 pieces = PyList_New(PyODict_SIZE(self));
1563 if (pieces == NULL)
1564 goto Done;
1565
1566 _odict_FOREACH(self, node) {
Eric Snowa762af72015-06-01 22:59:08 -06001567 PyObject *pair;
1568 PyObject *key = _odictnode_KEY(node);
1569 PyObject *value = _odictnode_VALUE(node, self);
1570 if (value == NULL) {
1571 if (!PyErr_Occurred())
1572 PyErr_SetObject(PyExc_KeyError, key);
Eric Snowdb4061c2015-06-03 11:09:48 -06001573 goto Done;
Eric Snowa762af72015-06-01 22:59:08 -06001574 }
1575 pair = PyTuple_Pack(2, key, value);
Eric Snow96c6af92015-05-29 22:21:39 -06001576 if (pair == NULL)
1577 goto Done;
1578
1579 PyList_SET_ITEM(pieces, ++count, pair); /* steals reference */
1580 }
1581 }
1582 else {
1583 PyObject *items = PyObject_CallMethod((PyObject *)self, "items", NULL);
1584 if (items == NULL)
1585 goto Done;
1586 pieces = PySequence_List(items);
1587 Py_DECREF(items);
1588 if(pieces == NULL)
1589 goto Done;
1590 }
1591
1592Finish:
1593 cls = _PyObject_GetAttrId((PyObject *)self, &PyId___class__);
1594 if (cls == NULL)
1595 goto Done;
1596 classname = _PyObject_GetAttrId(cls, &PyId___name__);
1597 if (classname == NULL)
1598 goto Done;
1599
1600 if (pieces == NULL) {
1601 formatstr = "%s()";
1602 args = PyTuple_Pack(1, classname);
1603 }
1604 else {
1605 formatstr = "%s(%r)";
1606 args = PyTuple_Pack(2, classname, pieces);
1607 }
1608 if (args == NULL)
1609 goto Done;
1610
1611 format = PyUnicode_InternFromString(formatstr);
1612 if (format == NULL)
1613 goto Done;
1614
1615 result = PyUnicode_Format(format, args);
1616Done:
1617 Py_XDECREF(pieces);
1618 Py_XDECREF(cls);
1619 Py_XDECREF(classname);
1620 Py_XDECREF(format);
1621 Py_XDECREF(args);
1622 Py_ReprLeave((PyObject *)self);
1623 return result;
1624};
1625
1626/* tp_doc */
1627
1628PyDoc_STRVAR(odict_doc,
1629 "Dictionary that remembers insertion order");
1630
1631/* tp_traverse */
1632
1633static int
1634odict_traverse(PyODictObject *od, visitproc visit, void *arg)
1635{
1636 Py_VISIT(od->od_inst_dict);
1637 Py_VISIT(od->od_weakreflist);
1638 return PyDict_Type.tp_traverse((PyObject *)od, visit, arg);
1639}
1640
1641/* tp_clear */
1642
1643static int
1644odict_tp_clear(PyODictObject *od)
1645{
1646 PyObject *res;
1647 Py_CLEAR(od->od_inst_dict);
1648 Py_CLEAR(od->od_weakreflist);
1649 res = odict_clear(od);
1650 if (res == NULL)
1651 return -1;
1652 Py_DECREF(res);
1653 return 0;
1654}
1655
1656/* tp_richcompare */
1657
1658static PyObject *
1659odict_richcompare(PyObject *v, PyObject *w, int op)
1660{
1661 if (!PyODict_Check(v) || !PyDict_Check(w)) {
1662 Py_RETURN_NOTIMPLEMENTED;
1663 }
1664
1665 if (op == Py_EQ || op == Py_NE) {
1666 PyObject *res, *cmp;
1667 int eq;
1668
1669 cmp = PyDict_Type.tp_richcompare(v, w, op);
1670 if (cmp == NULL)
1671 return NULL;
1672 if (!PyODict_Check(w))
1673 return cmp;
1674 if (op == Py_EQ && cmp == Py_False)
1675 return cmp;
1676 if (op == Py_NE && cmp == Py_True)
1677 return cmp;
1678 Py_DECREF(cmp);
1679
1680 /* Try comparing odict keys. */
1681 eq = _odict_keys_equal((PyODictObject *)v, (PyODictObject *)w);
1682 if (eq < 0)
1683 return NULL;
1684
1685 res = (eq == (op == Py_EQ)) ? Py_True : Py_False;
1686 Py_INCREF(res);
1687 return res;
1688 } else {
1689 Py_RETURN_NOTIMPLEMENTED;
1690 }
1691};
1692
1693/* tp_iter */
1694
1695static PyObject *
1696odict_iter(PyODictObject *od)
1697{
1698 return odictiter_new(od, _odict_ITER_KEYS);
1699};
1700
1701/* tp_init */
1702
1703static int
1704odict_init(PyObject *self, PyObject *args, PyObject *kwds)
1705{
1706 PyObject *res;
1707 Py_ssize_t len = PyObject_Length(args);
1708
1709 if (len == -1)
1710 return -1;
1711 if (len > 1) {
1712 char *msg = "expected at most 1 arguments, got %d";
1713 PyErr_Format(PyExc_TypeError, msg, len);
1714 return -1;
1715 }
1716
1717 /* __init__() triggering update() is just the way things are! */
1718 res = odict_update(self, args, kwds);
1719 if (res == NULL) {
1720 return -1;
1721 } else {
1722 Py_DECREF(res);
1723 return 0;
1724 }
1725};
1726
1727/* tp_new */
1728
1729static PyObject *
1730odict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1731{
Victor Stinnerca30b022015-09-03 17:50:04 +02001732 PyObject *dict;
1733 PyODictObject *od;
1734
1735 dict = PyDict_New();
1736 if (dict == NULL)
1737 return NULL;
1738
1739 od = (PyODictObject *)PyDict_Type.tp_new(type, args, kwds);
1740 if (od == NULL) {
1741 Py_DECREF(dict);
1742 return NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06001743 }
Victor Stinnerca30b022015-09-03 17:50:04 +02001744
1745 od->od_inst_dict = dict;
1746 /* type constructor fills the memory with zeros (see
1747 PyType_GenericAlloc()), there is no need to set them to zero again */
1748 if (_odict_resize(od) < 0) {
1749 Py_DECREF(od);
1750 return NULL;
1751 }
1752
1753 return (PyObject*)od;
Eric Snow96c6af92015-05-29 22:21:39 -06001754}
1755
1756/* PyODict_Type */
1757
1758PyTypeObject PyODict_Type = {
1759 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1760 "collections.OrderedDict", /* tp_name */
1761 sizeof(PyODictObject), /* tp_basicsize */
1762 0, /* tp_itemsize */
1763 (destructor)odict_dealloc, /* tp_dealloc */
1764 0, /* tp_print */
1765 0, /* tp_getattr */
1766 0, /* tp_setattr */
1767 0, /* tp_reserved */
1768 (reprfunc)odict_repr, /* tp_repr */
1769 0, /* tp_as_number */
1770 0, /* tp_as_sequence */
1771 &odict_as_mapping, /* tp_as_mapping */
1772 0, /* tp_hash */
1773 0, /* tp_call */
1774 0, /* tp_str */
1775 0, /* tp_getattro */
1776 0, /* tp_setattro */
1777 0, /* tp_as_buffer */
1778 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1779 odict_doc, /* tp_doc */
1780 (traverseproc)odict_traverse, /* tp_traverse */
1781 (inquiry)odict_tp_clear, /* tp_clear */
1782 (richcmpfunc)odict_richcompare, /* tp_richcompare */
1783 offsetof(PyODictObject, od_weakreflist), /* tp_weaklistoffset */
1784 (getiterfunc)odict_iter, /* tp_iter */
1785 0, /* tp_iternext */
1786 odict_methods, /* tp_methods */
1787 odict_members, /* tp_members */
1788 0, /* tp_getset */
1789 &PyDict_Type, /* tp_base */
1790 0, /* tp_dict */
1791 0, /* tp_descr_get */
1792 0, /* tp_descr_set */
1793 offsetof(PyODictObject, od_inst_dict), /* tp_dictoffset */
1794 (initproc)odict_init, /* tp_init */
1795 PyType_GenericAlloc, /* tp_alloc */
1796 (newfunc)odict_new, /* tp_new */
1797 0, /* tp_free */
1798};
1799
1800
1801/* ----------------------------------------------
1802 * the public OrderedDict API
1803 */
1804
1805PyObject *
1806PyODict_New(void) {
1807 return odict_new(&PyODict_Type, NULL, NULL);
1808};
1809
1810int
1811PyODict_SetItem(PyObject *od, PyObject *key, PyObject *value) {
1812 int res = PyDict_SetItem(od, key, value);
1813 if (res == 0) {
1814 res = _odict_add_new_node((PyODictObject *)od, key);
Eric Snowc5e59602015-05-30 11:28:56 -06001815 /* XXX Revert setting the value on the dict? */
Eric Snow96c6af92015-05-29 22:21:39 -06001816 }
1817 return res;
1818};
1819
1820int
1821PyODict_DelItem(PyObject *od, PyObject *key) {
1822 int res = _odict_clear_node((PyODictObject *)od, NULL, key);
1823 if (res < 0)
1824 return -1;
1825 return PyDict_DelItem(od, key);
1826};
1827
1828
1829/* -------------------------------------------
1830 * The OrderedDict views (keys/values/items)
1831 */
1832
1833typedef struct {
1834 PyObject_HEAD
1835 int kind;
1836 PyODictObject *di_odict;
Eric Snowb952ab42015-06-01 23:35:13 -06001837 Py_ssize_t di_size;
Eric Snow4fabf022015-06-04 00:09:56 -06001838 size_t di_state;
Eric Snow96c6af92015-05-29 22:21:39 -06001839 PyObject *di_current;
1840 PyObject *di_result; /* reusable result tuple for iteritems */
1841} odictiterobject;
1842
1843static void
1844odictiter_dealloc(odictiterobject *di)
1845{
1846 _PyObject_GC_UNTRACK(di);
Eric Snowa762af72015-06-01 22:59:08 -06001847 Py_XDECREF(di->di_odict);
Eric Snow96c6af92015-05-29 22:21:39 -06001848 Py_XDECREF(di->di_current);
1849 if (di->kind & (_odict_ITER_KEYS | _odict_ITER_VALUES)) {
1850 Py_DECREF(di->di_result);
1851 }
1852 PyObject_GC_Del(di);
1853}
1854
1855static int
1856odictiter_traverse(odictiterobject *di, visitproc visit, void *arg)
1857{
1858 Py_VISIT(di->di_odict);
1859 Py_VISIT(di->di_current); /* A key could be any type, not just str. */
1860 Py_VISIT(di->di_result);
1861 return 0;
1862}
1863
Eric Snowa762af72015-06-01 22:59:08 -06001864/* In order to protect against modifications during iteration, we track
1865 * the current key instead of the current node. */
Eric Snow96c6af92015-05-29 22:21:39 -06001866static PyObject *
1867odictiter_nextkey(odictiterobject *di)
1868{
Eric Snowa762af72015-06-01 22:59:08 -06001869 PyObject *key = NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06001870 _ODictNode *node;
1871 int reversed = di->kind & _odict_ITER_REVERSED;
1872
Eric Snowa762af72015-06-01 22:59:08 -06001873 if (di->di_odict == NULL)
Eric Snow96c6af92015-05-29 22:21:39 -06001874 return NULL;
Eric Snowa762af72015-06-01 22:59:08 -06001875 if (di->di_current == NULL)
1876 goto done; /* We're already done. */
1877
Eric Snowb952ab42015-06-01 23:35:13 -06001878 /* Check for unsupported changes. */
Eric Snow4fabf022015-06-04 00:09:56 -06001879 if (di->di_odict->od_state != di->di_state) {
1880 PyErr_SetString(PyExc_RuntimeError,
1881 "OrderedDict mutated during iteration");
1882 goto done;
1883 }
Eric Snowb952ab42015-06-01 23:35:13 -06001884 if (di->di_size != PyODict_SIZE(di->di_odict)) {
1885 PyErr_SetString(PyExc_RuntimeError,
1886 "OrderedDict changed size during iteration");
1887 di->di_size = -1; /* Make this state sticky */
1888 return NULL;
1889 }
1890
Eric Snowa762af72015-06-01 22:59:08 -06001891 /* Get the key. */
Eric Snow96c6af92015-05-29 22:21:39 -06001892 node = _odict_find_node(di->di_odict, di->di_current);
1893 if (node == NULL) {
1894 /* Must have been deleted. */
Eric Snowe3dfa9e2015-05-30 12:51:15 -06001895 Py_CLEAR(di->di_current);
Eric Snow96c6af92015-05-29 22:21:39 -06001896 return NULL;
1897 }
1898 key = di->di_current;
1899
1900 /* Advance to the next key. */
1901 node = reversed ? _odictnode_PREV(node) : _odictnode_NEXT(node);
1902 if (node == NULL) {
1903 /* Reached the end. */
1904 di->di_current = NULL;
1905 }
1906 else {
1907 di->di_current = _odictnode_KEY(node);
1908 Py_INCREF(di->di_current);
1909 }
1910
1911 return key;
Eric Snowa762af72015-06-01 22:59:08 -06001912
1913done:
1914 Py_CLEAR(di->di_odict);
1915 return key;
Eric Snow96c6af92015-05-29 22:21:39 -06001916}
1917
1918static PyObject *
1919odictiter_iternext(odictiterobject *di)
1920{
1921 PyObject *value;
1922 PyObject *key = odictiter_nextkey(di); /* new reference */
1923
1924 if (key == NULL)
1925 return NULL;
1926
1927 /* Handle the keys case. */
1928 if (! (di->kind & _odict_ITER_VALUES)) {
1929 return key;
1930 }
1931
1932 /* Handle the items case. */
1933 if (di->kind & _odict_ITER_KEYS) {
1934 PyObject *result = di->di_result;
1935
1936 value = PyODict_GetItem((PyObject *)di->di_odict, key); /* borrowed */
Eric Snowe3dfa9e2015-05-30 12:51:15 -06001937 if (value == NULL) {
Eric Snowa762af72015-06-01 22:59:08 -06001938 if (!PyErr_Occurred())
1939 PyErr_SetObject(PyExc_KeyError, key);
Eric Snowe3dfa9e2015-05-30 12:51:15 -06001940 Py_DECREF(key);
Eric Snowa762af72015-06-01 22:59:08 -06001941 goto done;
Eric Snowe3dfa9e2015-05-30 12:51:15 -06001942 }
1943 Py_INCREF(value);
Eric Snow96c6af92015-05-29 22:21:39 -06001944
1945 if (result->ob_refcnt == 1) {
1946 /* not in use so we can reuse it
1947 * (the common case during iteration) */
1948 Py_INCREF(result);
1949 Py_DECREF(PyTuple_GET_ITEM(result, 0)); /* borrowed */
1950 Py_DECREF(PyTuple_GET_ITEM(result, 1)); /* borrowed */
1951 }
1952 else {
1953 result = PyTuple_New(2);
Eric Snowe3dfa9e2015-05-30 12:51:15 -06001954 if (result == NULL) {
1955 Py_DECREF(key);
1956 Py_DECREF(value);
Eric Snowa762af72015-06-01 22:59:08 -06001957 goto done;
Eric Snowe3dfa9e2015-05-30 12:51:15 -06001958 }
Eric Snow96c6af92015-05-29 22:21:39 -06001959 }
1960
Eric Snow96c6af92015-05-29 22:21:39 -06001961 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
1962 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
1963
1964 return result;
1965 }
1966 /* Handle the values case. */
1967 else {
1968 value = PyODict_GetItem((PyObject *)di->di_odict, key);
Eric Snow96c6af92015-05-29 22:21:39 -06001969 Py_DECREF(key);
Eric Snowa762af72015-06-01 22:59:08 -06001970 if (value == NULL) {
1971 if (!PyErr_Occurred())
1972 PyErr_SetObject(PyExc_KeyError, key);
1973 goto done;
1974 }
1975 Py_INCREF(value);
Eric Snow96c6af92015-05-29 22:21:39 -06001976 return value;
1977 }
Eric Snowa762af72015-06-01 22:59:08 -06001978
1979done:
1980 Py_CLEAR(di->di_current);
1981 Py_CLEAR(di->di_odict);
1982 return NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06001983}
1984
1985/* No need for tp_clear because odictiterobject is not mutable. */
1986
1987PyDoc_STRVAR(reduce_doc, "Return state information for pickling");
1988
1989static PyObject *
1990odictiter_reduce(odictiterobject *di)
1991{
Eric Snowc5e59602015-05-30 11:28:56 -06001992 PyObject *list, *iter;
Eric Snow96c6af92015-05-29 22:21:39 -06001993
1994 list = PyList_New(0);
1995 if (!list)
1996 return NULL;
1997
1998 /* iterate the temporary into a list */
1999 for(;;) {
2000 PyObject *element = odictiter_iternext(di);
2001 if (element) {
2002 if (PyList_Append(list, element)) {
2003 Py_DECREF(element);
2004 Py_DECREF(list);
2005 return NULL;
2006 }
2007 Py_DECREF(element);
2008 }
2009 else {
2010 /* done iterating? */
2011 break;
2012 }
2013 }
2014 if (PyErr_Occurred()) {
2015 Py_DECREF(list);
2016 return NULL;
2017 }
Eric Snowc5e59602015-05-30 11:28:56 -06002018 iter = _PyObject_GetBuiltin("iter");
2019 if (iter == NULL) {
2020 Py_DECREF(list);
2021 return NULL;
2022 }
2023 return Py_BuildValue("N(N)", iter, list);
Eric Snow96c6af92015-05-29 22:21:39 -06002024}
2025
2026static PyMethodDef odictiter_methods[] = {
2027 {"__reduce__", (PyCFunction)odictiter_reduce, METH_NOARGS, reduce_doc},
2028 {NULL, NULL} /* sentinel */
2029};
2030
2031PyTypeObject PyODictIter_Type = {
2032 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2033 "odict_iterator", /* tp_name */
2034 sizeof(odictiterobject), /* tp_basicsize */
2035 0, /* tp_itemsize */
2036 /* methods */
2037 (destructor)odictiter_dealloc, /* tp_dealloc */
2038 0, /* tp_print */
2039 0, /* tp_getattr */
2040 0, /* tp_setattr */
2041 0, /* tp_reserved */
2042 0, /* tp_repr */
2043 0, /* tp_as_number */
2044 0, /* tp_as_sequence */
2045 0, /* tp_as_mapping */
2046 0, /* tp_hash */
2047 0, /* tp_call */
2048 0, /* tp_str */
2049 PyObject_GenericGetAttr, /* tp_getattro */
2050 0, /* tp_setattro */
2051 0, /* tp_as_buffer */
2052 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2053 0, /* tp_doc */
2054 (traverseproc)odictiter_traverse, /* tp_traverse */
2055 0, /* tp_clear */
2056 0, /* tp_richcompare */
2057 0, /* tp_weaklistoffset */
2058 PyObject_SelfIter, /* tp_iter */
2059 (iternextfunc)odictiter_iternext, /* tp_iternext */
2060 odictiter_methods, /* tp_methods */
2061 0,
2062};
2063
2064static PyObject *
2065odictiter_new(PyODictObject *od, int kind)
2066{
2067 odictiterobject *di;
2068 _ODictNode *node;
2069 int reversed = kind & _odict_ITER_REVERSED;
2070
2071 di = PyObject_GC_New(odictiterobject, &PyODictIter_Type);
2072 if (di == NULL)
2073 return NULL;
2074
2075 if (kind & (_odict_ITER_KEYS | _odict_ITER_VALUES)){
2076 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
2077 if (di->di_result == NULL) {
2078 Py_DECREF(di);
2079 return NULL;
2080 }
2081 }
2082 else
2083 di->di_result = NULL;
2084
2085 di->kind = kind;
2086 node = reversed ? _odict_LAST(od) : _odict_FIRST(od);
2087 di->di_current = node ? _odictnode_KEY(node) : NULL;
2088 Py_XINCREF(di->di_current);
Eric Snowb952ab42015-06-01 23:35:13 -06002089 di->di_size = PyODict_SIZE(od);
Eric Snow4fabf022015-06-04 00:09:56 -06002090 di->di_state = od->od_state;
Eric Snow96c6af92015-05-29 22:21:39 -06002091 di->di_odict = od;
2092 Py_INCREF(od);
2093
2094 _PyObject_GC_TRACK(di);
2095 return (PyObject *)di;
2096}
2097
2098/* keys() */
2099
2100static PyObject *
2101odictkeys_iter(_PyDictViewObject *dv)
2102{
2103 if (dv->dv_dict == NULL) {
2104 Py_RETURN_NONE;
2105 }
2106 return odictiter_new((PyODictObject *)dv->dv_dict,
2107 _odict_ITER_KEYS);
2108}
2109
2110static PyObject *
2111odictkeys_reversed(_PyDictViewObject *dv)
2112{
2113 if (dv->dv_dict == NULL) {
2114 Py_RETURN_NONE;
2115 }
2116 return odictiter_new((PyODictObject *)dv->dv_dict,
2117 _odict_ITER_KEYS|_odict_ITER_REVERSED);
2118}
2119
2120static PyMethodDef odictkeys_methods[] = {
2121 {"__reversed__", (PyCFunction)odictkeys_reversed, METH_NOARGS, NULL},
2122 {NULL, NULL} /* sentinel */
2123};
2124
2125PyTypeObject PyODictKeys_Type = {
2126 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2127 "odict_keys", /* tp_name */
2128 0, /* tp_basicsize */
2129 0, /* tp_itemsize */
2130 0, /* tp_dealloc */
2131 0, /* tp_print */
2132 0, /* tp_getattr */
2133 0, /* tp_setattr */
2134 0, /* tp_reserved */
2135 0, /* tp_repr */
2136 0, /* tp_as_number */
2137 0, /* tp_as_sequence */
2138 0, /* tp_as_mapping */
2139 0, /* tp_hash */
2140 0, /* tp_call */
2141 0, /* tp_str */
2142 0, /* tp_getattro */
2143 0, /* tp_setattro */
2144 0, /* tp_as_buffer */
2145 0, /* tp_flags */
2146 0, /* tp_doc */
2147 0, /* tp_traverse */
2148 0, /* tp_clear */
2149 0, /* tp_richcompare */
2150 0, /* tp_weaklistoffset */
2151 (getiterfunc)odictkeys_iter, /* tp_iter */
2152 0, /* tp_iternext */
2153 odictkeys_methods, /* tp_methods */
2154 0, /* tp_members */
2155 0, /* tp_getset */
2156 &PyDictKeys_Type, /* tp_base */
2157};
2158
2159static PyObject *
2160odictkeys_new(PyObject *od)
2161{
2162 return _PyDictView_New(od, &PyODictKeys_Type);
2163}
2164
2165/* items() */
2166
2167static PyObject *
2168odictitems_iter(_PyDictViewObject *dv)
2169{
2170 if (dv->dv_dict == NULL) {
2171 Py_RETURN_NONE;
2172 }
2173 return odictiter_new((PyODictObject *)dv->dv_dict,
2174 _odict_ITER_KEYS|_odict_ITER_VALUES);
2175}
2176
2177static PyObject *
2178odictitems_reversed(_PyDictViewObject *dv)
2179{
2180 if (dv->dv_dict == NULL) {
2181 Py_RETURN_NONE;
2182 }
2183 return odictiter_new((PyODictObject *)dv->dv_dict,
2184 _odict_ITER_KEYS|_odict_ITER_VALUES|_odict_ITER_REVERSED);
2185}
2186
2187static PyMethodDef odictitems_methods[] = {
2188 {"__reversed__", (PyCFunction)odictitems_reversed, METH_NOARGS, NULL},
2189 {NULL, NULL} /* sentinel */
2190};
2191
2192PyTypeObject PyODictItems_Type = {
2193 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2194 "odict_items", /* tp_name */
2195 0, /* tp_basicsize */
2196 0, /* tp_itemsize */
2197 0, /* tp_dealloc */
2198 0, /* tp_print */
2199 0, /* tp_getattr */
2200 0, /* tp_setattr */
2201 0, /* tp_reserved */
2202 0, /* tp_repr */
2203 0, /* tp_as_number */
2204 0, /* tp_as_sequence */
2205 0, /* tp_as_mapping */
2206 0, /* tp_hash */
2207 0, /* tp_call */
2208 0, /* tp_str */
2209 0, /* tp_getattro */
2210 0, /* tp_setattro */
2211 0, /* tp_as_buffer */
2212 0, /* tp_flags */
2213 0, /* tp_doc */
2214 0, /* tp_traverse */
2215 0, /* tp_clear */
2216 0, /* tp_richcompare */
2217 0, /* tp_weaklistoffset */
2218 (getiterfunc)odictitems_iter, /* tp_iter */
2219 0, /* tp_iternext */
2220 odictitems_methods, /* tp_methods */
2221 0, /* tp_members */
2222 0, /* tp_getset */
2223 &PyDictItems_Type, /* tp_base */
2224};
2225
2226static PyObject *
2227odictitems_new(PyObject *od)
2228{
2229 return _PyDictView_New(od, &PyODictItems_Type);
2230}
2231
2232/* values() */
2233
2234static PyObject *
2235odictvalues_iter(_PyDictViewObject *dv)
2236{
2237 if (dv->dv_dict == NULL) {
2238 Py_RETURN_NONE;
2239 }
2240 return odictiter_new((PyODictObject *)dv->dv_dict,
2241 _odict_ITER_VALUES);
2242}
2243
2244static PyObject *
2245odictvalues_reversed(_PyDictViewObject *dv)
2246{
2247 if (dv->dv_dict == NULL) {
2248 Py_RETURN_NONE;
2249 }
2250 return odictiter_new((PyODictObject *)dv->dv_dict,
2251 _odict_ITER_VALUES|_odict_ITER_REVERSED);
2252}
2253
2254static PyMethodDef odictvalues_methods[] = {
2255 {"__reversed__", (PyCFunction)odictvalues_reversed, METH_NOARGS, NULL},
2256 {NULL, NULL} /* sentinel */
2257};
2258
2259PyTypeObject PyODictValues_Type = {
2260 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2261 "odict_values", /* tp_name */
2262 0, /* tp_basicsize */
2263 0, /* tp_itemsize */
2264 0, /* tp_dealloc */
2265 0, /* tp_print */
2266 0, /* tp_getattr */
2267 0, /* tp_setattr */
2268 0, /* tp_reserved */
2269 0, /* tp_repr */
2270 0, /* tp_as_number */
2271 0, /* tp_as_sequence */
2272 0, /* tp_as_mapping */
2273 0, /* tp_hash */
2274 0, /* tp_call */
2275 0, /* tp_str */
2276 0, /* tp_getattro */
2277 0, /* tp_setattro */
2278 0, /* tp_as_buffer */
2279 0, /* tp_flags */
2280 0, /* tp_doc */
2281 0, /* tp_traverse */
2282 0, /* tp_clear */
2283 0, /* tp_richcompare */
2284 0, /* tp_weaklistoffset */
2285 (getiterfunc)odictvalues_iter, /* tp_iter */
2286 0, /* tp_iternext */
2287 odictvalues_methods, /* tp_methods */
2288 0, /* tp_members */
2289 0, /* tp_getset */
2290 &PyDictValues_Type, /* tp_base */
2291};
2292
2293static PyObject *
2294odictvalues_new(PyObject *od)
2295{
2296 return _PyDictView_New(od, &PyODictValues_Type);
2297}
2298
2299
2300/* ----------------------------------------------
2301 MutableMappping implementations
2302
2303Mapping:
2304
2305============ ===========
2306method uses
2307============ ===========
2308__contains__ __getitem__
2309__eq__ items
2310__getitem__ +
2311__iter__ +
2312__len__ +
2313__ne__ __eq__
2314get __getitem__
2315items ItemsView
2316keys KeysView
2317values ValuesView
2318============ ===========
2319
2320ItemsView uses __len__, __iter__, and __getitem__.
2321KeysView uses __len__, __iter__, and __contains__.
2322ValuesView uses __len__, __iter__, and __getitem__.
2323
2324MutableMapping:
2325
2326============ ===========
2327method uses
2328============ ===========
2329__delitem__ +
2330__setitem__ +
2331clear popitem
2332pop __getitem__
2333 __delitem__
2334popitem __iter__
2335 _getitem__
2336 __delitem__
2337setdefault __getitem__
2338 __setitem__
2339update __setitem__
2340============ ===========
2341*/
2342
2343static int
2344mutablemapping_add_pairs(PyObject *self, PyObject *pairs)
2345{
2346 PyObject *pair, *iterator, *unexpected;
2347 int res = 0;
2348
2349 iterator = PyObject_GetIter(pairs);
2350 if (iterator == NULL)
2351 return -1;
2352 PyErr_Clear();
2353
2354 while ((pair = PyIter_Next(iterator)) != NULL) {
2355 /* could be more efficient (see UNPACK_SEQUENCE in ceval.c) */
Eric Snowc5e59602015-05-30 11:28:56 -06002356 PyObject *key = NULL, *value = NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06002357 PyObject *pair_iterator = PyObject_GetIter(pair);
Eric Snowc5e59602015-05-30 11:28:56 -06002358 if (pair_iterator == NULL)
2359 goto Done;
Eric Snow96c6af92015-05-29 22:21:39 -06002360
2361 key = PyIter_Next(pair_iterator);
2362 if (key == NULL) {
2363 if (!PyErr_Occurred())
2364 PyErr_SetString(PyExc_ValueError,
2365 "need more than 0 values to unpack");
2366 goto Done;
2367 }
2368
2369 value = PyIter_Next(pair_iterator);
2370 if (value == NULL) {
2371 if (!PyErr_Occurred())
2372 PyErr_SetString(PyExc_ValueError,
2373 "need more than 1 value to unpack");
2374 goto Done;
2375 }
2376
2377 unexpected = PyIter_Next(pair_iterator);
2378 if (unexpected != NULL) {
2379 Py_DECREF(unexpected);
2380 PyErr_SetString(PyExc_ValueError,
2381 "too many values to unpack (expected 2)");
2382 goto Done;
2383 }
2384 else if (PyErr_Occurred())
2385 goto Done;
2386
2387 res = PyObject_SetItem(self, key, value);
2388
2389Done:
2390 Py_DECREF(pair);
Eric Snowc5e59602015-05-30 11:28:56 -06002391 Py_XDECREF(pair_iterator);
Eric Snow96c6af92015-05-29 22:21:39 -06002392 Py_XDECREF(key);
2393 Py_XDECREF(value);
2394 if (PyErr_Occurred())
2395 break;
2396 }
2397 Py_DECREF(iterator);
2398
2399 if (res < 0 || PyErr_Occurred() != NULL)
2400 return -1;
2401 else
2402 return 0;
2403}
2404
2405static PyObject *
2406mutablemapping_update(PyObject *self, PyObject *args, PyObject *kwargs)
2407{
2408 int res = 0;
2409 Py_ssize_t len = (args != NULL) ? PyObject_Size(args) : 0;
2410
2411 /* first handle args, if any */
Eric Snowc5e59602015-05-30 11:28:56 -06002412 if (len < 0) /* PyObject_Size raised an exception. */
Eric Snow96c6af92015-05-29 22:21:39 -06002413 return NULL;
Benjamin Peterson99e96f22015-06-06 23:20:32 -05002414
2415 if (len > 1) {
Eric Snow96c6af92015-05-29 22:21:39 -06002416 char *msg = "update() takes at most 1 positional argument (%d given)";
2417 PyErr_Format(PyExc_TypeError, msg, len);
2418 return NULL;
2419 }
Eric Snow96c6af92015-05-29 22:21:39 -06002420
Benjamin Peterson0718de92015-06-07 00:00:42 -05002421 if (len == 1) {
2422 PyObject *other = PyTuple_GET_ITEM(args, 0); /* borrowed reference */
2423 if (other == NULL)
2424 return NULL;
2425 Py_INCREF(other);
2426 if (PyObject_HasAttrString(other, "items")) { /* never fails */
2427 PyObject *items = PyMapping_Items(other);
2428 Py_DECREF(other);
2429 if (items == NULL)
2430 return NULL;
2431 res = mutablemapping_add_pairs(self, items);
2432 Py_DECREF(items);
2433 if (res == -1)
2434 return NULL;
2435 }
2436 else if (PyObject_HasAttrString(other, "keys")) { /* never fails */
2437 PyObject *keys, *iterator, *key;
2438 keys = PyObject_CallMethod(other, "keys", NULL);
2439 if (keys == NULL) {
2440 Py_DECREF(other);
2441 return NULL;
2442 }
2443 iterator = PyObject_GetIter(keys);
2444 Py_DECREF(keys);
2445 if (iterator == NULL) {
2446 Py_DECREF(other);
2447 return NULL;
2448 }
2449 while (res == 0 && (key = PyIter_Next(iterator))) {
2450 PyObject *value = PyObject_GetItem(other, key);
2451 if (value != NULL) {
2452 res = PyObject_SetItem(self, key, value);
2453 Py_DECREF(value);
2454 }
2455 else {
2456 res = -1;
2457 }
2458 Py_DECREF(key);
2459 }
2460 Py_DECREF(other);
2461 Py_DECREF(iterator);
2462 if (res != 0 || PyErr_Occurred())
2463 return NULL;
2464 }
2465 else {
2466 res = mutablemapping_add_pairs(self, other);
2467 Py_DECREF(other);
2468 if (res != 0)
2469 return NULL;
2470 }
2471 }
2472
2473 /* now handle kwargs */
2474 len = (kwargs != NULL) ? PyObject_Size(kwargs) : 0;
2475 if (len < 0) /* PyObject_Size raised an exception. */
Eric Snow96c6af92015-05-29 22:21:39 -06002476 return NULL;
Benjamin Peterson0718de92015-06-07 00:00:42 -05002477 if (len > 0) {
2478 PyObject *items;
2479 if (!PyMapping_Check(kwargs)) {
2480 PyErr_SetString(PyExc_TypeError, "expected mapping for kwargs");
2481 return NULL;
2482 }
2483 items = PyMapping_Items(kwargs);
Eric Snow96c6af92015-05-29 22:21:39 -06002484 if (items == NULL)
2485 return NULL;
2486 res = mutablemapping_add_pairs(self, items);
2487 Py_DECREF(items);
2488 if (res == -1)
2489 return NULL;
2490 }
Eric Snow96c6af92015-05-29 22:21:39 -06002491
2492 Py_RETURN_NONE;
2493}