Coverage Report

Created: 2025-11-02 06:30

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