blob: 0cc144375006999f0329e15a399f52febc76fd94 [file] [log] [blame]
Guido van Rossum2bc13791999-03-24 19:06:42 +00001/* Dictionary object implementation using a hash table */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002
Raymond Hettinger930427b2003-05-03 06:51:59 +00003/* The distribution includes a separate file, Objects/dictnotes.txt,
Tim Peters60b29962006-01-01 01:19:23 +00004 describing explorations into dictionary design and optimization.
Raymond Hettinger930427b2003-05-03 06:51:59 +00005 It covers typical dictionary use patterns, the parameters for
6 tuning dictionaries, and several ideas for possible optimizations.
7*/
8
Victor Stinner742da042016-09-07 17:40:12 -07009/* PyDictKeysObject
10
11This implements the dictionary's hashtable.
12
Raymond Hettingerb12785d2016-10-22 09:58:14 -070013As of Python 3.6, this is compact and ordered. Basic idea is described here:
14* https://mail.python.org/pipermail/python-dev/2012-December/123028.html
15* https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html
Victor Stinner742da042016-09-07 17:40:12 -070016
17layout:
18
19+---------------+
20| dk_refcnt |
21| dk_size |
22| dk_lookup |
23| dk_usable |
24| dk_nentries |
25+---------------+
26| dk_indices |
27| |
28+---------------+
29| dk_entries |
30| |
31+---------------+
32
33dk_indices is actual hashtable. It holds index in entries, or DKIX_EMPTY(-1)
34or DKIX_DUMMY(-2).
35Size of indices is dk_size. Type of each index in indices is vary on dk_size:
36
37* int8 for dk_size <= 128
38* int16 for 256 <= dk_size <= 2**15
39* int32 for 2**16 <= dk_size <= 2**31
40* int64 for 2**32 <= dk_size
41
42dk_entries is array of PyDictKeyEntry. It's size is USABLE_FRACTION(dk_size).
43DK_ENTRIES(dk) can be used to get pointer to entries.
44
45NOTE: Since negative value is used for DKIX_EMPTY and DKIX_DUMMY, type of
46dk_indices entry is signed integer and int16 is used for table which
47dk_size == 256.
48*/
49
Benjamin Peterson7d95e402012-04-23 11:24:50 -040050
51/*
Benjamin Peterson7d95e402012-04-23 11:24:50 -040052The DictObject can be in one of two forms.
Victor Stinner742da042016-09-07 17:40:12 -070053
Benjamin Peterson7d95e402012-04-23 11:24:50 -040054Either:
55 A combined table:
56 ma_values == NULL, dk_refcnt == 1.
57 Values are stored in the me_value field of the PyDictKeysObject.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040058Or:
59 A split table:
60 ma_values != NULL, dk_refcnt >= 1
61 Values are stored in the ma_values array.
Victor Stinner742da042016-09-07 17:40:12 -070062 Only string (unicode) keys are allowed.
63 All dicts sharing same key must have same insertion order.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040064
Victor Stinner742da042016-09-07 17:40:12 -070065There are four kinds of slots in the table (slot is index, and
66DK_ENTRIES(keys)[index] if index >= 0):
67
681. Unused. index == DKIX_EMPTY
69 Does not hold an active (key, value) pair now and never did. Unused can
70 transition to Active upon key insertion. This is each slot's initial state.
71
722. Active. index >= 0, me_key != NULL and me_value != NULL
73 Holds an active (key, value) pair. Active can transition to Dummy or
74 Pending upon key deletion (for combined and split tables respectively).
75 This is the only case in which me_value != NULL.
76
773. Dummy. index == DKIX_DUMMY (combined only)
78 Previously held an active (key, value) pair, but that was deleted and an
79 active pair has not yet overwritten the slot. Dummy can transition to
80 Active upon key insertion. Dummy slots cannot be made Unused again
81 else the probe sequence in case of collision would have no way to know
82 they were once active.
83
844. Pending. index >= 0, key != NULL, and value == NULL (split only)
85 Not yet inserted in split-table.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040086*/
87
Victor Stinner742da042016-09-07 17:40:12 -070088/*
89Preserving insertion order
Benjamin Peterson7d95e402012-04-23 11:24:50 -040090
Victor Stinner742da042016-09-07 17:40:12 -070091It's simple for combined table. Since dk_entries is mostly append only, we can
92get insertion order by just iterating dk_entries.
93
94One exception is .popitem(). It removes last item in dk_entries and decrement
95dk_nentries to achieve amortized O(1). Since there are DKIX_DUMMY remains in
96dk_indices, we can't increment dk_usable even though dk_nentries is
97decremented.
98
99In split table, inserting into pending entry is allowed only for dk_entries[ix]
100where ix == mp->ma_used. Inserting into other index and deleting item cause
101converting the dict to the combined table.
102*/
103
104/* PyDict_MINSIZE is the starting size for any new dict.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400105 * 8 allows dicts with no more than 5 active entries; experiments suggested
106 * this suffices for the majority of dicts (consisting mostly of usually-small
107 * dicts created to pass keyword arguments).
108 * Making this 8, rather than 4 reduces the number of resizes for most
109 * dictionaries, without any significant extra memory use.
110 */
Victor Stinner742da042016-09-07 17:40:12 -0700111#define PyDict_MINSIZE 8
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400112
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113#include "Python.h"
Victor Stinnerbcda8f12018-11-21 22:27:47 +0100114#include "pycore_object.h"
Victor Stinner621cebe2018-11-12 16:53:38 +0100115#include "pycore_pystate.h"
Eric Snow96c6af92015-05-29 22:21:39 -0600116#include "dict-common.h"
Victor Stinner990397e2016-09-09 20:22:59 -0700117#include "stringlib/eq.h" /* to get unicode_eq() */
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000118
Larry Hastings61272b72014-01-07 12:41:53 -0800119/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -0800120class dict "PyDictObject *" "&PyDict_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800121[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -0800122/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f157a5a0ce9589d6]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800123
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400124
125/*
126To ensure the lookup algorithm terminates, there must be at least one Unused
127slot (NULL key) in the table.
128To avoid slowing down lookups on a near-full table, we resize the table when
129it's USABLE_FRACTION (currently two-thirds) full.
130*/
Guido van Rossum16e93a81997-01-28 00:00:11 +0000131
Tim Peterseb28ef22001-06-02 05:27:19 +0000132#define PERTURB_SHIFT 5
133
Guido van Rossum16e93a81997-01-28 00:00:11 +0000134/*
Tim Peterseb28ef22001-06-02 05:27:19 +0000135Major subtleties ahead: Most hash schemes depend on having a "good" hash
136function, in the sense of simulating randomness. Python doesn't: its most
R David Murray537ad7a2016-07-10 12:33:18 -0400137important hash functions (for ints) are very regular in common
Tim Peterseb28ef22001-06-02 05:27:19 +0000138cases:
Tim Peters15d49292001-05-27 07:39:22 +0000139
R David Murray537ad7a2016-07-10 12:33:18 -0400140 >>>[hash(i) for i in range(4)]
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000141 [0, 1, 2, 3]
Tim Peters15d49292001-05-27 07:39:22 +0000142
Tim Peterseb28ef22001-06-02 05:27:19 +0000143This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
144the low-order i bits as the initial table index is extremely fast, and there
R David Murray537ad7a2016-07-10 12:33:18 -0400145are no collisions at all for dicts indexed by a contiguous range of ints. So
146this gives better-than-random behavior in common cases, and that's very
147desirable.
Tim Peters15d49292001-05-27 07:39:22 +0000148
Tim Peterseb28ef22001-06-02 05:27:19 +0000149OTOH, when collisions occur, the tendency to fill contiguous slices of the
150hash table makes a good collision resolution strategy crucial. Taking only
151the last i bits of the hash code is also vulnerable: for example, consider
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152the list [i << 16 for i in range(20000)] as a set of keys. Since ints are
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000153their own hash codes, and this fits in a dict of size 2**15, the last 15 bits
154 of every hash code are all 0: they *all* map to the same table index.
Tim Peters15d49292001-05-27 07:39:22 +0000155
Tim Peterseb28ef22001-06-02 05:27:19 +0000156But catering to unusual cases should not slow the usual ones, so we just take
157the last i bits anyway. It's up to collision resolution to do the rest. If
158we *usually* find the key we're looking for on the first try (and, it turns
159out, we usually do -- the table load factor is kept under 2/3, so the odds
160are solidly in our favor), then it makes best sense to keep the initial index
161computation dirt cheap.
Tim Peters15d49292001-05-27 07:39:22 +0000162
Tim Peterseb28ef22001-06-02 05:27:19 +0000163The first half of collision resolution is to visit table indices via this
164recurrence:
Tim Peters15d49292001-05-27 07:39:22 +0000165
Tim Peterseb28ef22001-06-02 05:27:19 +0000166 j = ((5*j) + 1) mod 2**i
Tim Peters15d49292001-05-27 07:39:22 +0000167
Tim Peterseb28ef22001-06-02 05:27:19 +0000168For any initial j in range(2**i), repeating that 2**i times generates each
169int in range(2**i) exactly once (see any text on random-number generation for
170proof). By itself, this doesn't help much: like linear probing (setting
171j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
172order. This would be bad, except that's not the only thing we do, and it's
173actually *good* in the common cases where hash keys are consecutive. In an
174example that's really too small to make this entirely clear, for a table of
175size 2**3 the order of indices is:
Tim Peters15d49292001-05-27 07:39:22 +0000176
Tim Peterseb28ef22001-06-02 05:27:19 +0000177 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
178
179If two things come in at index 5, the first place we look after is index 2,
180not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
181Linear probing is deadly in this case because there the fixed probe order
182is the *same* as the order consecutive keys are likely to arrive. But it's
183extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
184and certain that consecutive hash codes do not.
185
186The other half of the strategy is to get the other bits of the hash code
187into play. This is done by initializing a (unsigned) vrbl "perturb" to the
188full hash code, and changing the recurrence to:
189
Tim Peterseb28ef22001-06-02 05:27:19 +0000190 perturb >>= PERTURB_SHIFT;
INADA Naoki267941c2016-10-06 15:19:07 +0900191 j = (5*j) + 1 + perturb;
Tim Peterseb28ef22001-06-02 05:27:19 +0000192 use j % 2**i as the next table index;
193
194Now the probe sequence depends (eventually) on every bit in the hash code,
195and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
196because it quickly magnifies small differences in the bits that didn't affect
197the initial index. Note that because perturb is unsigned, if the recurrence
198is executed often enough perturb eventually becomes and remains 0. At that
199point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
200that's certain to find an empty slot eventually (since it generates every int
201in range(2**i), and we make sure there's always at least one empty slot).
202
203Selecting a good value for PERTURB_SHIFT is a balancing act. You want it
204small so that the high bits of the hash code continue to affect the probe
205sequence across iterations; but you want it large so that in really bad cases
206the high-order hash bits have an effect on early iterations. 5 was "the
207best" in minimizing total collisions across experiments Tim Peters ran (on
208both normal and pathological cases), but 4 and 6 weren't significantly worse.
209
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000210Historical: Reimer Behrends contributed the idea of using a polynomial-based
Tim Peterseb28ef22001-06-02 05:27:19 +0000211approach, using repeated multiplication by x in GF(2**n) where an irreducible
212polynomial for each table size was chosen such that x was a primitive root.
213Christian Tismer later extended that to use division by x instead, as an
214efficient way to get the high bits of the hash code into play. This scheme
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000215also gave excellent collision statistics, but was more expensive: two
216if-tests were required inside the loop; computing "the next" index took about
217the same number of operations but without as much potential parallelism
218(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
219above, and then shifting perturb can be done while the table index is being
220masked); and the PyDictObject struct required a member to hold the table's
221polynomial. In Tim's experiments the current scheme ran faster, produced
222equally good collision statistics, needed less code & used less memory.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000223
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000224*/
Tim Petersdea48ec2001-05-22 20:40:22 +0000225
Fred Drake1bff34a2000-08-31 19:31:38 +0000226/* forward declarations */
Victor Stinner742da042016-09-07 17:40:12 -0700227static Py_ssize_t lookdict(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900228 Py_hash_t hash, PyObject **value_addr);
Victor Stinner742da042016-09-07 17:40:12 -0700229static Py_ssize_t lookdict_unicode(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900230 Py_hash_t hash, PyObject **value_addr);
Victor Stinner742da042016-09-07 17:40:12 -0700231static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400232lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900233 Py_hash_t hash, PyObject **value_addr);
Victor Stinner742da042016-09-07 17:40:12 -0700234static Py_ssize_t lookdict_split(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900235 Py_hash_t hash, PyObject **value_addr);
Fred Drake1bff34a2000-08-31 19:31:38 +0000236
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400237static int dictresize(PyDictObject *mp, Py_ssize_t minused);
Tim Petersdea48ec2001-05-22 20:40:22 +0000238
INADA Naoki2aaf98c2018-09-26 12:59:00 +0900239static PyObject* dict_iter(PyDictObject *dict);
240
Benjamin Peterson3c569292016-09-08 13:16:41 -0700241/*Global counter used to set ma_version_tag field of dictionary.
Victor Stinner3b6a6b42016-09-08 12:51:24 -0700242 * It is incremented each time that a dictionary is created and each
243 * time that a dictionary is modified. */
244static uint64_t pydict_global_version = 0;
245
246#define DICT_NEXT_VERSION() (++pydict_global_version)
247
Victor Stinner742da042016-09-07 17:40:12 -0700248/* Dictionary reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +0000249#ifndef PyDict_MAXFREELIST
250#define PyDict_MAXFREELIST 80
251#endif
252static PyDictObject *free_list[PyDict_MAXFREELIST];
253static int numfree = 0;
Victor Stinner742da042016-09-07 17:40:12 -0700254static PyDictKeysObject *keys_free_list[PyDict_MAXFREELIST];
255static int numfreekeys = 0;
Raymond Hettinger43442782004-03-17 21:55:03 +0000256
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300257#include "clinic/dictobject.c.h"
258
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100259int
260PyDict_ClearFreeList(void)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 PyDictObject *op;
Victor Stinner742da042016-09-07 17:40:12 -0700263 int ret = numfree + numfreekeys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 while (numfree) {
265 op = free_list[--numfree];
266 assert(PyDict_CheckExact(op));
267 PyObject_GC_Del(op);
268 }
Victor Stinner742da042016-09-07 17:40:12 -0700269 while (numfreekeys) {
270 PyObject_FREE(keys_free_list[--numfreekeys]);
271 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100272 return ret;
273}
274
David Malcolm49526f42012-06-22 14:55:41 -0400275/* Print summary info about the state of the optimized allocator */
276void
277_PyDict_DebugMallocStats(FILE *out)
278{
279 _PyDebugAllocatorStats(out,
280 "free PyDictObject", numfree, sizeof(PyDictObject));
281}
282
283
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100284void
285PyDict_Fini(void)
286{
287 PyDict_ClearFreeList();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000288}
289
Victor Stinner742da042016-09-07 17:40:12 -0700290#define DK_SIZE(dk) ((dk)->dk_size)
291#if SIZEOF_VOID_P > 4
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700292#define DK_IXSIZE(dk) \
293 (DK_SIZE(dk) <= 0xff ? \
294 1 : DK_SIZE(dk) <= 0xffff ? \
295 2 : DK_SIZE(dk) <= 0xffffffff ? \
Benjamin Peterson3c569292016-09-08 13:16:41 -0700296 4 : sizeof(int64_t))
Victor Stinner742da042016-09-07 17:40:12 -0700297#else
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700298#define DK_IXSIZE(dk) \
299 (DK_SIZE(dk) <= 0xff ? \
300 1 : DK_SIZE(dk) <= 0xffff ? \
Benjamin Peterson3c569292016-09-08 13:16:41 -0700301 2 : sizeof(int32_t))
Victor Stinner742da042016-09-07 17:40:12 -0700302#endif
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700303#define DK_ENTRIES(dk) \
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700304 ((PyDictKeyEntry*)(&((int8_t*)((dk)->dk_indices))[DK_SIZE(dk) * DK_IXSIZE(dk)]))
Victor Stinner742da042016-09-07 17:40:12 -0700305
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400306#define DK_MASK(dk) (((dk)->dk_size)-1)
307#define IS_POWER_OF_2(x) (((x) & (x-1)) == 0)
308
INADA Naokia7576492018-11-14 18:39:27 +0900309static void free_keys_object(PyDictKeysObject *keys);
310
311static inline void
312dictkeys_incref(PyDictKeysObject *dk)
313{
314 _Py_INC_REFTOTAL;
315 dk->dk_refcnt++;
316}
317
318static inline void
319dictkeys_decref(PyDictKeysObject *dk)
320{
321 assert(dk->dk_refcnt > 0);
322 _Py_DEC_REFTOTAL;
323 if (--dk->dk_refcnt == 0) {
324 free_keys_object(dk);
325 }
326}
327
Victor Stinner742da042016-09-07 17:40:12 -0700328/* lookup indices. returns DKIX_EMPTY, DKIX_DUMMY, or ix >=0 */
Benjamin Peterson73222252016-09-08 09:58:47 -0700329static inline Py_ssize_t
INADA Naokia7576492018-11-14 18:39:27 +0900330dictkeys_get_index(PyDictKeysObject *keys, Py_ssize_t i)
Victor Stinner742da042016-09-07 17:40:12 -0700331{
332 Py_ssize_t s = DK_SIZE(keys);
Victor Stinner71211e32016-09-08 10:52:46 -0700333 Py_ssize_t ix;
334
Victor Stinner742da042016-09-07 17:40:12 -0700335 if (s <= 0xff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700336 int8_t *indices = (int8_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700337 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700338 }
339 else if (s <= 0xffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700340 int16_t *indices = (int16_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700341 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700342 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700343#if SIZEOF_VOID_P > 4
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300344 else if (s > 0xffffffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700345 int64_t *indices = (int64_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700346 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700347 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700348#endif
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300349 else {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700350 int32_t *indices = (int32_t*)(keys->dk_indices);
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300351 ix = indices[i];
352 }
Victor Stinner71211e32016-09-08 10:52:46 -0700353 assert(ix >= DKIX_DUMMY);
354 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700355}
356
357/* write to indices. */
Benjamin Peterson73222252016-09-08 09:58:47 -0700358static inline void
INADA Naokia7576492018-11-14 18:39:27 +0900359dictkeys_set_index(PyDictKeysObject *keys, Py_ssize_t i, Py_ssize_t ix)
Victor Stinner742da042016-09-07 17:40:12 -0700360{
361 Py_ssize_t s = DK_SIZE(keys);
Victor Stinner71211e32016-09-08 10:52:46 -0700362
363 assert(ix >= DKIX_DUMMY);
364
Victor Stinner742da042016-09-07 17:40:12 -0700365 if (s <= 0xff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700366 int8_t *indices = (int8_t*)(keys->dk_indices);
Victor Stinner71211e32016-09-08 10:52:46 -0700367 assert(ix <= 0x7f);
Victor Stinner208857e2016-09-08 11:35:46 -0700368 indices[i] = (char)ix;
Victor Stinner742da042016-09-07 17:40:12 -0700369 }
370 else if (s <= 0xffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700371 int16_t *indices = (int16_t*)(keys->dk_indices);
Victor Stinner71211e32016-09-08 10:52:46 -0700372 assert(ix <= 0x7fff);
Victor Stinner208857e2016-09-08 11:35:46 -0700373 indices[i] = (int16_t)ix;
Victor Stinner742da042016-09-07 17:40:12 -0700374 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700375#if SIZEOF_VOID_P > 4
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300376 else if (s > 0xffffffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700377 int64_t *indices = (int64_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700378 indices[i] = ix;
Victor Stinner742da042016-09-07 17:40:12 -0700379 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700380#endif
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300381 else {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700382 int32_t *indices = (int32_t*)(keys->dk_indices);
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300383 assert(ix <= 0x7fffffff);
384 indices[i] = (int32_t)ix;
385 }
Victor Stinner742da042016-09-07 17:40:12 -0700386}
387
388
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200389/* USABLE_FRACTION is the maximum dictionary load.
Victor Stinner742da042016-09-07 17:40:12 -0700390 * Increasing this ratio makes dictionaries more dense resulting in more
391 * collisions. Decreasing it improves sparseness at the expense of spreading
392 * indices over more cache lines and at the cost of total memory consumed.
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200393 *
394 * USABLE_FRACTION must obey the following:
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400395 * (0 < USABLE_FRACTION(n) < n) for all n >= 2
396 *
Victor Stinner742da042016-09-07 17:40:12 -0700397 * USABLE_FRACTION should be quick to calculate.
398 * Fractions around 1/2 to 2/3 seem to work well in practice.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400399 */
Victor Stinner742da042016-09-07 17:40:12 -0700400#define USABLE_FRACTION(n) (((n) << 1)/3)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400401
Victor Stinner742da042016-09-07 17:40:12 -0700402/* ESTIMATE_SIZE is reverse function of USABLE_FRACTION.
403 * This can be used to reserve enough size to insert n entries without
404 * resizing.
405 */
INADA Naoki92c50ee2016-11-22 00:57:02 +0900406#define ESTIMATE_SIZE(n) (((n)*3+1) >> 1)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400407
Victor Stinner742da042016-09-07 17:40:12 -0700408/* Alternative fraction that is otherwise close enough to 2n/3 to make
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400409 * little difference. 8 * 2/3 == 8 * 5/8 == 5. 16 * 2/3 == 16 * 5/8 == 10.
410 * 32 * 2/3 = 21, 32 * 5/8 = 20.
411 * Its advantage is that it is faster to compute on machines with slow division.
412 * #define USABLE_FRACTION(n) (((n) >> 1) + ((n) >> 2) - ((n) >> 3))
Victor Stinner742da042016-09-07 17:40:12 -0700413 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400414
Victor Stinnera9f61a52013-07-16 22:17:26 +0200415/* GROWTH_RATE. Growth rate upon hitting maximum load.
INADA Naoki5fbc5112018-04-17 15:53:34 +0900416 * Currently set to used*3.
Victor Stinnera9f61a52013-07-16 22:17:26 +0200417 * This means that dicts double in size when growing without deletions,
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700418 * but have more head room when the number of deletions is on a par with the
INADA Naoki5fbc5112018-04-17 15:53:34 +0900419 * number of insertions. See also bpo-17563 and bpo-33205.
420 *
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700421 * GROWTH_RATE was set to used*4 up to version 3.2.
422 * GROWTH_RATE was set to used*2 in version 3.3.0
INADA Naoki5fbc5112018-04-17 15:53:34 +0900423 * GROWTH_RATE was set to used*2 + capacity/2 in 3.4.0-3.6.0.
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200424 */
INADA Naoki5fbc5112018-04-17 15:53:34 +0900425#define GROWTH_RATE(d) ((d)->ma_used*3)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400426
427#define ENSURE_ALLOWS_DELETIONS(d) \
428 if ((d)->ma_keys->dk_lookup == lookdict_unicode_nodummy) { \
429 (d)->ma_keys->dk_lookup = lookdict_unicode; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400431
432/* This immutable, empty PyDictKeysObject is used for PyDict_Clear()
433 * (which cannot fail and thus can do no allocation).
434 */
435static PyDictKeysObject empty_keys_struct = {
Serhiy Storchaka97932e42016-09-26 23:01:23 +0300436 1, /* dk_refcnt */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400437 1, /* dk_size */
438 lookdict_split, /* dk_lookup */
439 0, /* dk_usable (immutable) */
Victor Stinner742da042016-09-07 17:40:12 -0700440 0, /* dk_nentries */
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700441 {DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY,
442 DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY}, /* dk_indices */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400443};
444
445static PyObject *empty_values[1] = { NULL };
446
447#define Py_EMPTY_KEYS &empty_keys_struct
448
Victor Stinner611b0fa2016-09-14 15:02:01 +0200449/* Uncomment to check the dict content in _PyDict_CheckConsistency() */
450/* #define DEBUG_PYDICT */
451
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200452#ifdef DEBUG_PYDICT
453# define ASSERT_CONSISTENT(op) assert(_PyDict_CheckConsistency((PyObject *)(op), 1))
454#else
455# define ASSERT_CONSISTENT(op) assert(_PyDict_CheckConsistency((PyObject *)(op), 0))
456#endif
Victor Stinner611b0fa2016-09-14 15:02:01 +0200457
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200458
459int
460_PyDict_CheckConsistency(PyObject *op, int check_content)
Victor Stinner611b0fa2016-09-14 15:02:01 +0200461{
Emmanuel Ariasa2fedd82019-05-10 07:08:08 -0300462#ifndef NDEBUG
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200463 _PyObject_ASSERT(op, PyDict_Check(op));
464 PyDictObject *mp = (PyDictObject *)op;
Victor Stinner50fe3f82018-10-26 18:47:15 +0200465
Victor Stinner611b0fa2016-09-14 15:02:01 +0200466 PyDictKeysObject *keys = mp->ma_keys;
467 int splitted = _PyDict_HasSplitTable(mp);
468 Py_ssize_t usable = USABLE_FRACTION(keys->dk_size);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200469
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200470 _PyObject_ASSERT(op, 0 <= mp->ma_used && mp->ma_used <= usable);
471 _PyObject_ASSERT(op, IS_POWER_OF_2(keys->dk_size));
472 _PyObject_ASSERT(op, 0 <= keys->dk_usable && keys->dk_usable <= usable);
473 _PyObject_ASSERT(op, 0 <= keys->dk_nentries && keys->dk_nentries <= usable);
474 _PyObject_ASSERT(op, keys->dk_usable + keys->dk_nentries <= usable);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200475
476 if (!splitted) {
477 /* combined table */
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200478 _PyObject_ASSERT(op, keys->dk_refcnt == 1);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200479 }
480
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200481 if (check_content) {
482 PyDictKeyEntry *entries = DK_ENTRIES(keys);
483 Py_ssize_t i;
Victor Stinner611b0fa2016-09-14 15:02:01 +0200484
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200485 for (i=0; i < keys->dk_size; i++) {
486 Py_ssize_t ix = dictkeys_get_index(keys, i);
487 _PyObject_ASSERT(op, DKIX_DUMMY <= ix && ix <= usable);
488 }
Victor Stinner611b0fa2016-09-14 15:02:01 +0200489
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200490 for (i=0; i < usable; i++) {
491 PyDictKeyEntry *entry = &entries[i];
492 PyObject *key = entry->me_key;
493
494 if (key != NULL) {
495 if (PyUnicode_CheckExact(key)) {
496 Py_hash_t hash = ((PyASCIIObject *)key)->hash;
497 _PyObject_ASSERT(op, hash != -1);
498 _PyObject_ASSERT(op, entry->me_hash == hash);
499 }
500 else {
501 /* test_dict fails if PyObject_Hash() is called again */
502 _PyObject_ASSERT(op, entry->me_hash != -1);
503 }
504 if (!splitted) {
505 _PyObject_ASSERT(op, entry->me_value != NULL);
506 }
Victor Stinner611b0fa2016-09-14 15:02:01 +0200507 }
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200508
509 if (splitted) {
510 _PyObject_ASSERT(op, entry->me_value == NULL);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200511 }
512 }
513
514 if (splitted) {
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200515 /* splitted table */
516 for (i=0; i < mp->ma_used; i++) {
517 _PyObject_ASSERT(op, mp->ma_values[i] != NULL);
518 }
Victor Stinner611b0fa2016-09-14 15:02:01 +0200519 }
520 }
Emmanuel Ariasa2fedd82019-05-10 07:08:08 -0300521#endif
Victor Stinner611b0fa2016-09-14 15:02:01 +0200522 return 1;
523}
Victor Stinner611b0fa2016-09-14 15:02:01 +0200524
525
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400526static PyDictKeysObject *new_keys_object(Py_ssize_t size)
527{
528 PyDictKeysObject *dk;
Victor Stinner742da042016-09-07 17:40:12 -0700529 Py_ssize_t es, usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400530
Victor Stinner742da042016-09-07 17:40:12 -0700531 assert(size >= PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400532 assert(IS_POWER_OF_2(size));
Victor Stinner742da042016-09-07 17:40:12 -0700533
534 usable = USABLE_FRACTION(size);
535 if (size <= 0xff) {
536 es = 1;
537 }
538 else if (size <= 0xffff) {
539 es = 2;
540 }
541#if SIZEOF_VOID_P > 4
542 else if (size <= 0xffffffff) {
543 es = 4;
544 }
545#endif
546 else {
547 es = sizeof(Py_ssize_t);
548 }
549
550 if (size == PyDict_MINSIZE && numfreekeys > 0) {
551 dk = keys_free_list[--numfreekeys];
552 }
553 else {
Victor Stinner98ee9d52016-09-08 09:33:56 -0700554 dk = PyObject_MALLOC(sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -0700555 + es * size
556 + sizeof(PyDictKeyEntry) * usable);
Victor Stinner742da042016-09-07 17:40:12 -0700557 if (dk == NULL) {
558 PyErr_NoMemory();
559 return NULL;
560 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400561 }
INADA Naokia7576492018-11-14 18:39:27 +0900562 _Py_INC_REFTOTAL;
563 dk->dk_refcnt = 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400564 dk->dk_size = size;
Victor Stinner742da042016-09-07 17:40:12 -0700565 dk->dk_usable = usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400566 dk->dk_lookup = lookdict_unicode_nodummy;
Victor Stinner742da042016-09-07 17:40:12 -0700567 dk->dk_nentries = 0;
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700568 memset(&dk->dk_indices[0], 0xff, es * size);
Victor Stinner742da042016-09-07 17:40:12 -0700569 memset(DK_ENTRIES(dk), 0, sizeof(PyDictKeyEntry) * usable);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400570 return dk;
571}
572
573static void
574free_keys_object(PyDictKeysObject *keys)
575{
Victor Stinner742da042016-09-07 17:40:12 -0700576 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400577 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -0700578 for (i = 0, n = keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400579 Py_XDECREF(entries[i].me_key);
580 Py_XDECREF(entries[i].me_value);
581 }
Victor Stinner742da042016-09-07 17:40:12 -0700582 if (keys->dk_size == PyDict_MINSIZE && numfreekeys < PyDict_MAXFREELIST) {
583 keys_free_list[numfreekeys++] = keys;
584 return;
585 }
Raymond Hettingerce5179f2016-01-31 08:56:21 -0800586 PyObject_FREE(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400587}
588
589#define new_values(size) PyMem_NEW(PyObject *, size)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400590#define free_values(values) PyMem_FREE(values)
591
592/* Consumes a reference to the keys object */
593static PyObject *
594new_dict(PyDictKeysObject *keys, PyObject **values)
595{
596 PyDictObject *mp;
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200597 assert(keys != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 if (numfree) {
599 mp = free_list[--numfree];
600 assert (mp != NULL);
601 assert (Py_TYPE(mp) == &PyDict_Type);
602 _Py_NewReference((PyObject *)mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400604 else {
605 mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
606 if (mp == NULL) {
INADA Naokia7576492018-11-14 18:39:27 +0900607 dictkeys_decref(keys);
Zackery Spytz3d07c1e2019-03-23 20:23:29 -0600608 if (values != empty_values) {
609 free_values(values);
610 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400611 return NULL;
612 }
613 }
614 mp->ma_keys = keys;
615 mp->ma_values = values;
616 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -0700617 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200618 ASSERT_CONSISTENT(mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000620}
621
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400622/* Consumes a reference to the keys object */
623static PyObject *
624new_dict_with_shared_keys(PyDictKeysObject *keys)
625{
626 PyObject **values;
627 Py_ssize_t i, size;
628
Victor Stinner742da042016-09-07 17:40:12 -0700629 size = USABLE_FRACTION(DK_SIZE(keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400630 values = new_values(size);
631 if (values == NULL) {
INADA Naokia7576492018-11-14 18:39:27 +0900632 dictkeys_decref(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400633 return PyErr_NoMemory();
634 }
635 for (i = 0; i < size; i++) {
636 values[i] = NULL;
637 }
638 return new_dict(keys, values);
639}
640
Yury Selivanovb0a7a032018-01-22 11:54:41 -0500641
642static PyObject *
643clone_combined_dict(PyDictObject *orig)
644{
645 assert(PyDict_CheckExact(orig));
646 assert(orig->ma_values == NULL);
647 assert(orig->ma_keys->dk_refcnt == 1);
648
649 Py_ssize_t keys_size = _PyDict_KeysSize(orig->ma_keys);
650 PyDictKeysObject *keys = PyObject_Malloc(keys_size);
651 if (keys == NULL) {
652 PyErr_NoMemory();
653 return NULL;
654 }
655
656 memcpy(keys, orig->ma_keys, keys_size);
657
658 /* After copying key/value pairs, we need to incref all
659 keys and values and they are about to be co-owned by a
660 new dict object. */
661 PyDictKeyEntry *ep0 = DK_ENTRIES(keys);
662 Py_ssize_t n = keys->dk_nentries;
663 for (Py_ssize_t i = 0; i < n; i++) {
664 PyDictKeyEntry *entry = &ep0[i];
665 PyObject *value = entry->me_value;
666 if (value != NULL) {
667 Py_INCREF(value);
668 Py_INCREF(entry->me_key);
669 }
670 }
671
672 PyDictObject *new = (PyDictObject *)new_dict(keys, NULL);
673 if (new == NULL) {
674 /* In case of an error, `new_dict()` takes care of
675 cleaning up `keys`. */
676 return NULL;
677 }
678 new->ma_used = orig->ma_used;
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200679 ASSERT_CONSISTENT(new);
Yury Selivanovb0a7a032018-01-22 11:54:41 -0500680 if (_PyObject_GC_IS_TRACKED(orig)) {
681 /* Maintain tracking. */
682 _PyObject_GC_TRACK(new);
683 }
Yury Selivanov0b752282018-07-06 12:20:07 -0400684
685 /* Since we copied the keys table we now have an extra reference
686 in the system. Manually call _Py_INC_REFTOTAL to signal that
INADA Naokia7576492018-11-14 18:39:27 +0900687 we have it now; calling dictkeys_incref would be an error as
Yury Selivanov0b752282018-07-06 12:20:07 -0400688 keys->dk_refcnt is already set to 1 (after memcpy). */
689 _Py_INC_REFTOTAL;
690
Yury Selivanovb0a7a032018-01-22 11:54:41 -0500691 return (PyObject *)new;
692}
693
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400694PyObject *
695PyDict_New(void)
696{
Inada Naokif2a18672019-03-12 17:25:44 +0900697 dictkeys_incref(Py_EMPTY_KEYS);
698 return new_dict(Py_EMPTY_KEYS, empty_values);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400699}
700
Victor Stinner742da042016-09-07 17:40:12 -0700701/* Search index of hash table from offset of entry table */
702static Py_ssize_t
703lookdict_index(PyDictKeysObject *k, Py_hash_t hash, Py_ssize_t index)
704{
Victor Stinner742da042016-09-07 17:40:12 -0700705 size_t mask = DK_MASK(k);
INADA Naoki073ae482017-06-23 15:22:50 +0900706 size_t perturb = (size_t)hash;
707 size_t i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700708
INADA Naoki073ae482017-06-23 15:22:50 +0900709 for (;;) {
INADA Naokia7576492018-11-14 18:39:27 +0900710 Py_ssize_t ix = dictkeys_get_index(k, i);
Victor Stinner742da042016-09-07 17:40:12 -0700711 if (ix == index) {
712 return i;
713 }
714 if (ix == DKIX_EMPTY) {
715 return DKIX_EMPTY;
716 }
INADA Naoki073ae482017-06-23 15:22:50 +0900717 perturb >>= PERTURB_SHIFT;
718 i = mask & (i*5 + perturb + 1);
Victor Stinner742da042016-09-07 17:40:12 -0700719 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700720 Py_UNREACHABLE();
Victor Stinner742da042016-09-07 17:40:12 -0700721}
722
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000723/*
724The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000725This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000726Open addressing is preferred over chaining since the link overhead for
727chaining would be substantial (100% with typical malloc overhead).
728
Tim Peterseb28ef22001-06-02 05:27:19 +0000729The initial probe index is computed as hash mod the table size. Subsequent
730probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000731
732All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000733
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000734The details in this version are due to Tim Peters, building on many past
Tim Peterseb28ef22001-06-02 05:27:19 +0000735contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000736Christian Tismer.
Fred Drake1bff34a2000-08-31 19:31:38 +0000737
Victor Stinner742da042016-09-07 17:40:12 -0700738lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a
Victor Stinnera4348cc2016-09-08 12:01:25 -0700739comparison raises an exception.
Guido van Rossum89d8c602007-09-18 17:26:56 +0000740lookdict_unicode() below is specialized to string keys, comparison of which can
INADA Naoki1b8df102017-02-20 22:48:10 +0900741never raise an exception; that function can never return DKIX_ERROR when key
742is string. Otherwise, it falls back to lookdict().
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400743lookdict_unicode_nodummy is further specialized for string keys that cannot be
744the <dummy> value.
INADA Naoki778928b2017-08-03 23:45:15 +0900745For both, when the key isn't found a DKIX_EMPTY is returned.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000746*/
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100747static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400748lookdict(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900749 Py_hash_t hash, PyObject **value_addr)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000750{
INADA Naoki778928b2017-08-03 23:45:15 +0900751 size_t i, mask, perturb;
Victor Stinner742da042016-09-07 17:40:12 -0700752 PyDictKeysObject *dk;
INADA Naoki778928b2017-08-03 23:45:15 +0900753 PyDictKeyEntry *ep0;
Tim Peterseb28ef22001-06-02 05:27:19 +0000754
Antoine Pitrou9a234902012-05-13 20:48:01 +0200755top:
Victor Stinner742da042016-09-07 17:40:12 -0700756 dk = mp->ma_keys;
Victor Stinner742da042016-09-07 17:40:12 -0700757 ep0 = DK_ENTRIES(dk);
INADA Naoki778928b2017-08-03 23:45:15 +0900758 mask = DK_MASK(dk);
759 perturb = hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700761
INADA Naoki778928b2017-08-03 23:45:15 +0900762 for (;;) {
INADA Naokia7576492018-11-14 18:39:27 +0900763 Py_ssize_t ix = dictkeys_get_index(dk, i);
Victor Stinner742da042016-09-07 17:40:12 -0700764 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700765 *value_addr = NULL;
766 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400767 }
INADA Naoki778928b2017-08-03 23:45:15 +0900768 if (ix >= 0) {
769 PyDictKeyEntry *ep = &ep0[ix];
770 assert(ep->me_key != NULL);
771 if (ep->me_key == key) {
772 *value_addr = ep->me_value;
773 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700774 }
INADA Naoki778928b2017-08-03 23:45:15 +0900775 if (ep->me_hash == hash) {
776 PyObject *startkey = ep->me_key;
777 Py_INCREF(startkey);
778 int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
779 Py_DECREF(startkey);
780 if (cmp < 0) {
781 *value_addr = NULL;
782 return DKIX_ERROR;
783 }
784 if (dk == mp->ma_keys && ep->me_key == startkey) {
785 if (cmp > 0) {
786 *value_addr = ep->me_value;
787 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700788 }
INADA Naoki778928b2017-08-03 23:45:15 +0900789 }
790 else {
791 /* The dict was mutated, restart */
792 goto top;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400793 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 }
INADA Naoki778928b2017-08-03 23:45:15 +0900796 perturb >>= PERTURB_SHIFT;
797 i = (i*5 + perturb + 1) & mask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700799 Py_UNREACHABLE();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000800}
801
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400802/* Specialized version for string-only keys */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100803static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400804lookdict_unicode(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900805 Py_hash_t hash, PyObject **value_addr)
Fred Drake1bff34a2000-08-31 19:31:38 +0000806{
Victor Stinner742da042016-09-07 17:40:12 -0700807 assert(mp->ma_values == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 /* Make sure this function doesn't have to handle non-unicode keys,
809 including subclasses of str; e.g., one reason to subclass
810 unicodes is to override __eq__, and for speed we don't cater to
811 that here. */
812 if (!PyUnicode_CheckExact(key)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400813 mp->ma_keys->dk_lookup = lookdict;
INADA Naoki778928b2017-08-03 23:45:15 +0900814 return lookdict(mp, key, hash, value_addr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 }
Tim Peters15d49292001-05-27 07:39:22 +0000816
INADA Naoki778928b2017-08-03 23:45:15 +0900817 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
818 size_t mask = DK_MASK(mp->ma_keys);
819 size_t perturb = (size_t)hash;
820 size_t i = (size_t)hash & mask;
821
822 for (;;) {
INADA Naokia7576492018-11-14 18:39:27 +0900823 Py_ssize_t ix = dictkeys_get_index(mp->ma_keys, i);
Victor Stinner742da042016-09-07 17:40:12 -0700824 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700825 *value_addr = NULL;
826 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400827 }
INADA Naoki778928b2017-08-03 23:45:15 +0900828 if (ix >= 0) {
829 PyDictKeyEntry *ep = &ep0[ix];
830 assert(ep->me_key != NULL);
831 assert(PyUnicode_CheckExact(ep->me_key));
832 if (ep->me_key == key ||
833 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
834 *value_addr = ep->me_value;
835 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700836 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400837 }
INADA Naoki778928b2017-08-03 23:45:15 +0900838 perturb >>= PERTURB_SHIFT;
839 i = mask & (i*5 + perturb + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700841 Py_UNREACHABLE();
Fred Drake1bff34a2000-08-31 19:31:38 +0000842}
843
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400844/* Faster version of lookdict_unicode when it is known that no <dummy> keys
845 * will be present. */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100846static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400847lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900848 Py_hash_t hash, PyObject **value_addr)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400849{
Victor Stinner742da042016-09-07 17:40:12 -0700850 assert(mp->ma_values == NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400851 /* Make sure this function doesn't have to handle non-unicode keys,
852 including subclasses of str; e.g., one reason to subclass
853 unicodes is to override __eq__, and for speed we don't cater to
854 that here. */
855 if (!PyUnicode_CheckExact(key)) {
856 mp->ma_keys->dk_lookup = lookdict;
INADA Naoki778928b2017-08-03 23:45:15 +0900857 return lookdict(mp, key, hash, value_addr);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400858 }
INADA Naoki778928b2017-08-03 23:45:15 +0900859
860 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
861 size_t mask = DK_MASK(mp->ma_keys);
862 size_t perturb = (size_t)hash;
863 size_t i = (size_t)hash & mask;
864
865 for (;;) {
INADA Naokia7576492018-11-14 18:39:27 +0900866 Py_ssize_t ix = dictkeys_get_index(mp->ma_keys, i);
Victor Stinner742da042016-09-07 17:40:12 -0700867 assert (ix != DKIX_DUMMY);
868 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700869 *value_addr = NULL;
870 return DKIX_EMPTY;
871 }
INADA Naoki778928b2017-08-03 23:45:15 +0900872 PyDictKeyEntry *ep = &ep0[ix];
873 assert(ep->me_key != NULL);
874 assert(PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700875 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400876 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
INADA Naokiba609772016-12-07 20:41:42 +0900877 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700878 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400879 }
INADA Naoki778928b2017-08-03 23:45:15 +0900880 perturb >>= PERTURB_SHIFT;
881 i = mask & (i*5 + perturb + 1);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400882 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700883 Py_UNREACHABLE();
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400884}
885
886/* Version of lookdict for split tables.
887 * All split tables and only split tables use this lookup function.
888 * Split tables only contain unicode keys and no dummy keys,
889 * so algorithm is the same as lookdict_unicode_nodummy.
890 */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100891static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400892lookdict_split(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900893 Py_hash_t hash, PyObject **value_addr)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400894{
Victor Stinner742da042016-09-07 17:40:12 -0700895 /* mp must split table */
896 assert(mp->ma_values != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400897 if (!PyUnicode_CheckExact(key)) {
INADA Naoki778928b2017-08-03 23:45:15 +0900898 Py_ssize_t ix = lookdict(mp, key, hash, value_addr);
Victor Stinner742da042016-09-07 17:40:12 -0700899 if (ix >= 0) {
INADA Naokiba609772016-12-07 20:41:42 +0900900 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700901 }
902 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400903 }
Victor Stinner742da042016-09-07 17:40:12 -0700904
INADA Naoki778928b2017-08-03 23:45:15 +0900905 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
906 size_t mask = DK_MASK(mp->ma_keys);
907 size_t perturb = (size_t)hash;
908 size_t i = (size_t)hash & mask;
909
910 for (;;) {
INADA Naokia7576492018-11-14 18:39:27 +0900911 Py_ssize_t ix = dictkeys_get_index(mp->ma_keys, i);
INADA Naoki778928b2017-08-03 23:45:15 +0900912 assert (ix != DKIX_DUMMY);
Victor Stinner742da042016-09-07 17:40:12 -0700913 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700914 *value_addr = NULL;
915 return DKIX_EMPTY;
916 }
INADA Naoki778928b2017-08-03 23:45:15 +0900917 PyDictKeyEntry *ep = &ep0[ix];
918 assert(ep->me_key != NULL);
919 assert(PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700920 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400921 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
INADA Naokiba609772016-12-07 20:41:42 +0900922 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700923 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400924 }
INADA Naoki778928b2017-08-03 23:45:15 +0900925 perturb >>= PERTURB_SHIFT;
926 i = mask & (i*5 + perturb + 1);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400927 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700928 Py_UNREACHABLE();
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400929}
930
Benjamin Petersonfb886362010-04-24 18:21:17 +0000931int
932_PyDict_HasOnlyStringKeys(PyObject *dict)
933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 Py_ssize_t pos = 0;
935 PyObject *key, *value;
Benjamin Petersonf6096542010-11-17 22:33:12 +0000936 assert(PyDict_Check(dict));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 /* Shortcut */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400938 if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 return 1;
940 while (PyDict_Next(dict, &pos, &key, &value))
941 if (!PyUnicode_Check(key))
942 return 0;
943 return 1;
Benjamin Petersonfb886362010-04-24 18:21:17 +0000944}
945
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000946#define MAINTAIN_TRACKING(mp, key, value) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 do { \
948 if (!_PyObject_GC_IS_TRACKED(mp)) { \
949 if (_PyObject_GC_MAY_BE_TRACKED(key) || \
950 _PyObject_GC_MAY_BE_TRACKED(value)) { \
951 _PyObject_GC_TRACK(mp); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 } \
953 } \
954 } while(0)
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000955
956void
957_PyDict_MaybeUntrack(PyObject *op)
958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 PyDictObject *mp;
960 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -0700961 Py_ssize_t i, numentries;
962 PyDictKeyEntry *ep0;
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
965 return;
966
967 mp = (PyDictObject *) op;
Victor Stinner742da042016-09-07 17:40:12 -0700968 ep0 = DK_ENTRIES(mp->ma_keys);
969 numentries = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400970 if (_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -0700971 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400972 if ((value = mp->ma_values[i]) == NULL)
973 continue;
974 if (_PyObject_GC_MAY_BE_TRACKED(value)) {
Victor Stinner742da042016-09-07 17:40:12 -0700975 assert(!_PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400976 return;
977 }
978 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400980 else {
Victor Stinner742da042016-09-07 17:40:12 -0700981 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400982 if ((value = ep0[i].me_value) == NULL)
983 continue;
984 if (_PyObject_GC_MAY_BE_TRACKED(value) ||
985 _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
986 return;
987 }
988 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 _PyObject_GC_UNTRACK(op);
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000990}
991
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400992/* Internal function to find slot for an item from its hash
Victor Stinner3c336c52016-09-12 14:17:40 +0200993 when it is known that the key is not present in the dict.
994
995 The dict must be combined. */
INADA Naokiba609772016-12-07 20:41:42 +0900996static Py_ssize_t
INADA Naoki778928b2017-08-03 23:45:15 +0900997find_empty_slot(PyDictKeysObject *keys, Py_hash_t hash)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000998{
INADA Naoki778928b2017-08-03 23:45:15 +0900999 assert(keys != NULL);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001000
INADA Naoki778928b2017-08-03 23:45:15 +09001001 const size_t mask = DK_MASK(keys);
1002 size_t i = hash & mask;
INADA Naokia7576492018-11-14 18:39:27 +09001003 Py_ssize_t ix = dictkeys_get_index(keys, i);
INADA Naoki778928b2017-08-03 23:45:15 +09001004 for (size_t perturb = hash; ix >= 0;) {
INADA Naoki267941c2016-10-06 15:19:07 +09001005 perturb >>= PERTURB_SHIFT;
INADA Naoki778928b2017-08-03 23:45:15 +09001006 i = (i*5 + perturb + 1) & mask;
INADA Naokia7576492018-11-14 18:39:27 +09001007 ix = dictkeys_get_index(keys, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 }
INADA Naoki778928b2017-08-03 23:45:15 +09001009 return i;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001010}
1011
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001012static int
1013insertion_resize(PyDictObject *mp)
1014{
Raymond Hettinger36f74aa2013-05-17 03:01:13 -07001015 return dictresize(mp, GROWTH_RATE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001016}
Antoine Pitroue965d972012-02-27 00:45:12 +01001017
1018/*
1019Internal routine to insert a new item into the table.
1020Used both by the internal resize routine and by the public insert routine.
Antoine Pitroue965d972012-02-27 00:45:12 +01001021Returns -1 if an error occurred, or 0 on success.
1022*/
1023static int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001024insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001025{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001026 PyObject *old_value;
INADA Naokiba609772016-12-07 20:41:42 +09001027 PyDictKeyEntry *ep;
Antoine Pitroue965d972012-02-27 00:45:12 +01001028
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001029 Py_INCREF(key);
1030 Py_INCREF(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001031 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
1032 if (insertion_resize(mp) < 0)
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001033 goto Fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001034 }
1035
INADA Naoki778928b2017-08-03 23:45:15 +09001036 Py_ssize_t ix = mp->ma_keys->dk_lookup(mp, key, hash, &old_value);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001037 if (ix == DKIX_ERROR)
1038 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001039
Antoine Pitroud6967322014-10-18 00:35:00 +02001040 assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001041 MAINTAIN_TRACKING(mp, key, value);
Victor Stinner742da042016-09-07 17:40:12 -07001042
1043 /* When insertion order is different from shared key, we can't share
1044 * the key anymore. Convert this instance to combine table.
1045 */
1046 if (_PyDict_HasSplitTable(mp) &&
INADA Naokiba609772016-12-07 20:41:42 +09001047 ((ix >= 0 && old_value == NULL && mp->ma_used != ix) ||
Victor Stinner742da042016-09-07 17:40:12 -07001048 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001049 if (insertion_resize(mp) < 0)
1050 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001051 ix = DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001052 }
Victor Stinner742da042016-09-07 17:40:12 -07001053
1054 if (ix == DKIX_EMPTY) {
1055 /* Insert into new slot. */
INADA Naokiba609772016-12-07 20:41:42 +09001056 assert(old_value == NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001057 if (mp->ma_keys->dk_usable <= 0) {
1058 /* Need to resize. */
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001059 if (insertion_resize(mp) < 0)
1060 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001061 }
INADA Naoki778928b2017-08-03 23:45:15 +09001062 Py_ssize_t hashpos = find_empty_slot(mp->ma_keys, hash);
INADA Naokiba609772016-12-07 20:41:42 +09001063 ep = &DK_ENTRIES(mp->ma_keys)[mp->ma_keys->dk_nentries];
INADA Naokia7576492018-11-14 18:39:27 +09001064 dictkeys_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
Victor Stinner742da042016-09-07 17:40:12 -07001065 ep->me_key = key;
1066 ep->me_hash = hash;
1067 if (mp->ma_values) {
1068 assert (mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
1069 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001070 }
1071 else {
Victor Stinner742da042016-09-07 17:40:12 -07001072 ep->me_value = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001073 }
1074 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001075 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07001076 mp->ma_keys->dk_usable--;
1077 mp->ma_keys->dk_nentries++;
1078 assert(mp->ma_keys->dk_usable >= 0);
Victor Stinner0fc91ee2019-04-12 21:51:34 +02001079 ASSERT_CONSISTENT(mp);
Victor Stinner742da042016-09-07 17:40:12 -07001080 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001081 }
Victor Stinner742da042016-09-07 17:40:12 -07001082
Inada Naoki91234a12019-06-03 21:30:58 +09001083 if (old_value != value) {
1084 if (_PyDict_HasSplitTable(mp)) {
1085 mp->ma_values[ix] = value;
1086 if (old_value == NULL) {
1087 /* pending state */
1088 assert(ix == mp->ma_used);
1089 mp->ma_used++;
1090 }
INADA Naokiba609772016-12-07 20:41:42 +09001091 }
Inada Naoki91234a12019-06-03 21:30:58 +09001092 else {
1093 assert(old_value != NULL);
1094 DK_ENTRIES(mp->ma_keys)[ix].me_value = value;
1095 }
1096 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naokiba609772016-12-07 20:41:42 +09001097 }
INADA Naokiba609772016-12-07 20:41:42 +09001098 Py_XDECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
Victor Stinner0fc91ee2019-04-12 21:51:34 +02001099 ASSERT_CONSISTENT(mp);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001100 Py_DECREF(key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001101 return 0;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001102
1103Fail:
1104 Py_DECREF(value);
1105 Py_DECREF(key);
1106 return -1;
Antoine Pitroue965d972012-02-27 00:45:12 +01001107}
1108
Inada Naoki2ddc7f62019-03-18 20:38:33 +09001109// Same to insertdict but specialized for ma_keys = Py_EMPTY_KEYS.
1110static int
1111insert_to_emptydict(PyDictObject *mp, PyObject *key, Py_hash_t hash,
1112 PyObject *value)
1113{
1114 assert(mp->ma_keys == Py_EMPTY_KEYS);
1115
1116 PyDictKeysObject *newkeys = new_keys_object(PyDict_MINSIZE);
1117 if (newkeys == NULL) {
1118 return -1;
1119 }
1120 if (!PyUnicode_CheckExact(key)) {
1121 newkeys->dk_lookup = lookdict;
1122 }
1123 dictkeys_decref(Py_EMPTY_KEYS);
1124 mp->ma_keys = newkeys;
1125 mp->ma_values = NULL;
1126
1127 Py_INCREF(key);
1128 Py_INCREF(value);
1129 MAINTAIN_TRACKING(mp, key, value);
1130
1131 size_t hashpos = (size_t)hash & (PyDict_MINSIZE-1);
1132 PyDictKeyEntry *ep = &DK_ENTRIES(mp->ma_keys)[0];
1133 dictkeys_set_index(mp->ma_keys, hashpos, 0);
1134 ep->me_key = key;
1135 ep->me_hash = hash;
1136 ep->me_value = value;
1137 mp->ma_used++;
1138 mp->ma_version_tag = DICT_NEXT_VERSION();
1139 mp->ma_keys->dk_usable--;
1140 mp->ma_keys->dk_nentries++;
1141 return 0;
1142}
1143
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001144/*
luzpaza5293b42017-11-05 07:37:50 -06001145Internal routine used by dictresize() to build a hashtable of entries.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001146*/
1147static void
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001148build_indices(PyDictKeysObject *keys, PyDictKeyEntry *ep, Py_ssize_t n)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001149{
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001150 size_t mask = (size_t)DK_SIZE(keys) - 1;
1151 for (Py_ssize_t ix = 0; ix != n; ix++, ep++) {
1152 Py_hash_t hash = ep->me_hash;
1153 size_t i = hash & mask;
INADA Naokia7576492018-11-14 18:39:27 +09001154 for (size_t perturb = hash; dictkeys_get_index(keys, i) != DKIX_EMPTY;) {
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001155 perturb >>= PERTURB_SHIFT;
INADA Naoki870c2862017-06-24 09:03:19 +09001156 i = mask & (i*5 + perturb + 1);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001157 }
INADA Naokia7576492018-11-14 18:39:27 +09001158 dictkeys_set_index(keys, i, ix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001160}
1161
1162/*
1163Restructure the table by allocating a new table and reinserting all
1164items again. When entries have been deleted, the new table may
1165actually be smaller than the old one.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001166If a table is split (its keys and hashes are shared, its values are not),
1167then the values are temporarily copied into the table, it is resized as
1168a combined table, then the me_value slots in the old table are NULLed out.
1169After resizing a table is always combined,
1170but can be resplit by make_keys_shared().
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001171*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001172static int
Victor Stinner3d3f2642016-12-15 17:21:23 +01001173dictresize(PyDictObject *mp, Py_ssize_t minsize)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001174{
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001175 Py_ssize_t newsize, numentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001176 PyDictKeysObject *oldkeys;
1177 PyObject **oldvalues;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001178 PyDictKeyEntry *oldentries, *newentries;
Tim Peters91a364d2001-05-19 07:04:38 +00001179
Victor Stinner742da042016-09-07 17:40:12 -07001180 /* Find the smallest table size > minused. */
1181 for (newsize = PyDict_MINSIZE;
Victor Stinner3d3f2642016-12-15 17:21:23 +01001182 newsize < minsize && newsize > 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 newsize <<= 1)
1184 ;
1185 if (newsize <= 0) {
1186 PyErr_NoMemory();
1187 return -1;
1188 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001189
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001190 oldkeys = mp->ma_keys;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001191
1192 /* NOTE: Current odict checks mp->ma_keys to detect resize happen.
1193 * So we can't reuse oldkeys even if oldkeys->dk_size == newsize.
1194 * TODO: Try reusing oldkeys when reimplement odict.
1195 */
1196
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001197 /* Allocate a new table. */
1198 mp->ma_keys = new_keys_object(newsize);
1199 if (mp->ma_keys == NULL) {
1200 mp->ma_keys = oldkeys;
1201 return -1;
1202 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01001203 // New table must be large enough.
1204 assert(mp->ma_keys->dk_usable >= mp->ma_used);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001205 if (oldkeys->dk_lookup == lookdict)
1206 mp->ma_keys->dk_lookup = lookdict;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001207
1208 numentries = mp->ma_used;
1209 oldentries = DK_ENTRIES(oldkeys);
1210 newentries = DK_ENTRIES(mp->ma_keys);
1211 oldvalues = mp->ma_values;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001212 if (oldvalues != NULL) {
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001213 /* Convert split table into new combined table.
1214 * We must incref keys; we can transfer values.
1215 * Note that values of split table is always dense.
1216 */
1217 for (Py_ssize_t i = 0; i < numentries; i++) {
1218 assert(oldvalues[i] != NULL);
1219 PyDictKeyEntry *ep = &oldentries[i];
1220 PyObject *key = ep->me_key;
1221 Py_INCREF(key);
1222 newentries[i].me_key = key;
1223 newentries[i].me_hash = ep->me_hash;
1224 newentries[i].me_value = oldvalues[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001226
INADA Naokia7576492018-11-14 18:39:27 +09001227 dictkeys_decref(oldkeys);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001228 mp->ma_values = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001229 if (oldvalues != empty_values) {
1230 free_values(oldvalues);
1231 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001232 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001233 else { // combined table.
1234 if (oldkeys->dk_nentries == numentries) {
1235 memcpy(newentries, oldentries, numentries * sizeof(PyDictKeyEntry));
1236 }
1237 else {
1238 PyDictKeyEntry *ep = oldentries;
1239 for (Py_ssize_t i = 0; i < numentries; i++) {
1240 while (ep->me_value == NULL)
1241 ep++;
1242 newentries[i] = *ep++;
1243 }
1244 }
1245
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001246 assert(oldkeys->dk_lookup != lookdict_split);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001247 assert(oldkeys->dk_refcnt == 1);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001248 if (oldkeys->dk_size == PyDict_MINSIZE &&
1249 numfreekeys < PyDict_MAXFREELIST) {
INADA Naokia7576492018-11-14 18:39:27 +09001250 _Py_DEC_REFTOTAL;
1251 keys_free_list[numfreekeys++] = oldkeys;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001252 }
1253 else {
INADA Naokia7576492018-11-14 18:39:27 +09001254 _Py_DEC_REFTOTAL;
1255 PyObject_FREE(oldkeys);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001256 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001257 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001258
1259 build_indices(mp->ma_keys, newentries, numentries);
1260 mp->ma_keys->dk_usable -= numentries;
1261 mp->ma_keys->dk_nentries = numentries;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001263}
1264
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001265/* Returns NULL if unable to split table.
1266 * A NULL return does not necessarily indicate an error */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001267static PyDictKeysObject *
1268make_keys_shared(PyObject *op)
1269{
1270 Py_ssize_t i;
1271 Py_ssize_t size;
1272 PyDictObject *mp = (PyDictObject *)op;
1273
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001274 if (!PyDict_CheckExact(op))
1275 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001276 if (!_PyDict_HasSplitTable(mp)) {
1277 PyDictKeyEntry *ep0;
1278 PyObject **values;
1279 assert(mp->ma_keys->dk_refcnt == 1);
1280 if (mp->ma_keys->dk_lookup == lookdict) {
1281 return NULL;
1282 }
1283 else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
1284 /* Remove dummy keys */
1285 if (dictresize(mp, DK_SIZE(mp->ma_keys)))
1286 return NULL;
1287 }
1288 assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
1289 /* Copy values into a new array */
Victor Stinner742da042016-09-07 17:40:12 -07001290 ep0 = DK_ENTRIES(mp->ma_keys);
1291 size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001292 values = new_values(size);
1293 if (values == NULL) {
1294 PyErr_SetString(PyExc_MemoryError,
1295 "Not enough memory to allocate new values array");
1296 return NULL;
1297 }
1298 for (i = 0; i < size; i++) {
1299 values[i] = ep0[i].me_value;
1300 ep0[i].me_value = NULL;
1301 }
1302 mp->ma_keys->dk_lookup = lookdict_split;
1303 mp->ma_values = values;
1304 }
INADA Naokia7576492018-11-14 18:39:27 +09001305 dictkeys_incref(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001306 return mp->ma_keys;
1307}
Christian Heimes99170a52007-12-19 02:07:34 +00001308
1309PyObject *
1310_PyDict_NewPresized(Py_ssize_t minused)
1311{
INADA Naoki92c50ee2016-11-22 00:57:02 +09001312 const Py_ssize_t max_presize = 128 * 1024;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001313 Py_ssize_t newsize;
1314 PyDictKeysObject *new_keys;
INADA Naoki92c50ee2016-11-22 00:57:02 +09001315
Inada Naoki2ddc7f62019-03-18 20:38:33 +09001316 if (minused <= USABLE_FRACTION(PyDict_MINSIZE)) {
Inada Naokif2a18672019-03-12 17:25:44 +09001317 return PyDict_New();
1318 }
INADA Naoki92c50ee2016-11-22 00:57:02 +09001319 /* There are no strict guarantee that returned dict can contain minused
1320 * items without resize. So we create medium size dict instead of very
1321 * large dict or MemoryError.
1322 */
1323 if (minused > USABLE_FRACTION(max_presize)) {
1324 newsize = max_presize;
1325 }
1326 else {
1327 Py_ssize_t minsize = ESTIMATE_SIZE(minused);
Inada Naoki2ddc7f62019-03-18 20:38:33 +09001328 newsize = PyDict_MINSIZE*2;
INADA Naoki92c50ee2016-11-22 00:57:02 +09001329 while (newsize < minsize) {
1330 newsize <<= 1;
1331 }
1332 }
1333 assert(IS_POWER_OF_2(newsize));
1334
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001335 new_keys = new_keys_object(newsize);
1336 if (new_keys == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001338 return new_dict(new_keys, NULL);
Christian Heimes99170a52007-12-19 02:07:34 +00001339}
1340
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001341/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
1342 * that may occur (originally dicts supported only string keys, and exceptions
1343 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001344 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001345 * (suppressed) occurred while computing the key's hash, or that some error
1346 * (suppressed) occurred when comparing keys in the dict's internal probe
1347 * sequence. A nasty example of the latter is when a Python-coded comparison
1348 * function hits a stack-depth error, which can cause this to return NULL
1349 * even if the key is present.
1350 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001351PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001352PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001353{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001354 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001355 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 PyDictObject *mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 PyThreadState *tstate;
INADA Naokiba609772016-12-07 20:41:42 +09001358 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 if (!PyDict_Check(op))
1361 return NULL;
1362 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001363 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 {
1365 hash = PyObject_Hash(key);
1366 if (hash == -1) {
1367 PyErr_Clear();
1368 return NULL;
1369 }
1370 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 /* We can arrive here with a NULL tstate during initialization: try
1373 running "python -Wi" for an example related to string interning.
1374 Let's just hope that no exception occurs then... This must be
Victor Stinner50b48572018-11-01 01:51:40 +01001375 _PyThreadState_GET() and not PyThreadState_Get() because the latter
Victor Stinner9204fb82018-10-30 15:13:17 +01001376 abort Python if tstate is NULL. */
Victor Stinner50b48572018-11-01 01:51:40 +01001377 tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 if (tstate != NULL && tstate->curexc_type != NULL) {
1379 /* preserve the existing exception */
1380 PyObject *err_type, *err_value, *err_tb;
1381 PyErr_Fetch(&err_type, &err_value, &err_tb);
INADA Naoki778928b2017-08-03 23:45:15 +09001382 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 /* ignore errors */
1384 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001385 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 return NULL;
1387 }
1388 else {
INADA Naoki778928b2017-08-03 23:45:15 +09001389 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001390 if (ix < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 PyErr_Clear();
1392 return NULL;
1393 }
1394 }
INADA Naokiba609772016-12-07 20:41:42 +09001395 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001396}
1397
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001398/* Same as PyDict_GetItemWithError() but with hash supplied by caller.
1399 This returns NULL *with* an exception set if an exception occurred.
1400 It returns NULL *without* an exception set if the key wasn't present.
1401*/
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001402PyObject *
1403_PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1404{
Victor Stinner742da042016-09-07 17:40:12 -07001405 Py_ssize_t ix;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001406 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001407 PyObject *value;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001408
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001409 if (!PyDict_Check(op)) {
1410 PyErr_BadInternalCall();
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001411 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001412 }
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001413
INADA Naoki778928b2017-08-03 23:45:15 +09001414 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001415 if (ix < 0) {
1416 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001417 }
INADA Naokiba609772016-12-07 20:41:42 +09001418 return value;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001419}
1420
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001421/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
1422 This returns NULL *with* an exception set if an exception occurred.
1423 It returns NULL *without* an exception set if the key wasn't present.
1424*/
1425PyObject *
1426PyDict_GetItemWithError(PyObject *op, PyObject *key)
1427{
Victor Stinner742da042016-09-07 17:40:12 -07001428 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001429 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 PyDictObject*mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001431 PyObject *value;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 if (!PyDict_Check(op)) {
1434 PyErr_BadInternalCall();
1435 return NULL;
1436 }
1437 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001438 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 {
1440 hash = PyObject_Hash(key);
1441 if (hash == -1) {
1442 return NULL;
1443 }
1444 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001445
INADA Naoki778928b2017-08-03 23:45:15 +09001446 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001447 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001449 return value;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001450}
1451
Brett Cannonfd074152012-04-14 14:10:13 -04001452PyObject *
1453_PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
1454{
1455 PyObject *kv;
1456 kv = _PyUnicode_FromId(key); /* borrowed */
1457 if (kv == NULL)
1458 return NULL;
1459 return PyDict_GetItemWithError(dp, kv);
1460}
1461
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001462PyObject *
1463_PyDict_GetItemStringWithError(PyObject *v, const char *key)
1464{
1465 PyObject *kv, *rv;
1466 kv = PyUnicode_FromString(key);
1467 if (kv == NULL) {
1468 return NULL;
1469 }
1470 rv = PyDict_GetItemWithError(v, kv);
1471 Py_DECREF(kv);
1472 return rv;
1473}
1474
Victor Stinnerb4efc962015-11-20 09:24:02 +01001475/* Fast version of global value lookup (LOAD_GLOBAL).
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001476 * Lookup in globals, then builtins.
Victor Stinnerb4efc962015-11-20 09:24:02 +01001477 *
1478 * Raise an exception and return NULL if an error occurred (ex: computing the
1479 * key hash failed, key comparison failed, ...). Return NULL if the key doesn't
1480 * exist. Return the value if the key exists.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001481 */
1482PyObject *
1483_PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001484{
Victor Stinner742da042016-09-07 17:40:12 -07001485 Py_ssize_t ix;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001486 Py_hash_t hash;
INADA Naokiba609772016-12-07 20:41:42 +09001487 PyObject *value;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001488
1489 if (!PyUnicode_CheckExact(key) ||
1490 (hash = ((PyASCIIObject *) key)->hash) == -1)
1491 {
1492 hash = PyObject_Hash(key);
1493 if (hash == -1)
1494 return NULL;
Antoine Pitroue965d972012-02-27 00:45:12 +01001495 }
Victor Stinnerb4efc962015-11-20 09:24:02 +01001496
1497 /* namespace 1: globals */
INADA Naoki778928b2017-08-03 23:45:15 +09001498 ix = globals->ma_keys->dk_lookup(globals, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001499 if (ix == DKIX_ERROR)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001500 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001501 if (ix != DKIX_EMPTY && value != NULL)
1502 return value;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001503
1504 /* namespace 2: builtins */
INADA Naoki778928b2017-08-03 23:45:15 +09001505 ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001506 if (ix < 0)
Victor Stinnerb4efc962015-11-20 09:24:02 +01001507 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001508 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001509}
1510
Antoine Pitroue965d972012-02-27 00:45:12 +01001511/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
1512 * dictionary if it's merely replacing the value for an existing key.
1513 * This means that it's safe to loop over a dictionary with PyDict_Next()
1514 * and occasionally replace a value -- but you can't insert new keys or
1515 * remove them.
1516 */
1517int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001518PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001519{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001520 PyDictObject *mp;
1521 Py_hash_t hash;
Antoine Pitroue965d972012-02-27 00:45:12 +01001522 if (!PyDict_Check(op)) {
1523 PyErr_BadInternalCall();
1524 return -1;
1525 }
1526 assert(key);
1527 assert(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001528 mp = (PyDictObject *)op;
1529 if (!PyUnicode_CheckExact(key) ||
1530 (hash = ((PyASCIIObject *) key)->hash) == -1)
1531 {
Antoine Pitroue965d972012-02-27 00:45:12 +01001532 hash = PyObject_Hash(key);
1533 if (hash == -1)
1534 return -1;
1535 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001536
Inada Naoki2ddc7f62019-03-18 20:38:33 +09001537 if (mp->ma_keys == Py_EMPTY_KEYS) {
1538 return insert_to_emptydict(mp, key, hash, value);
1539 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001540 /* insertdict() handles any resizing that might be necessary */
1541 return insertdict(mp, key, hash, value);
Antoine Pitroue965d972012-02-27 00:45:12 +01001542}
1543
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001544int
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001545_PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
1546 Py_hash_t hash)
1547{
1548 PyDictObject *mp;
1549
1550 if (!PyDict_Check(op)) {
1551 PyErr_BadInternalCall();
1552 return -1;
1553 }
1554 assert(key);
1555 assert(value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001556 assert(hash != -1);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001557 mp = (PyDictObject *)op;
1558
Inada Naoki2ddc7f62019-03-18 20:38:33 +09001559 if (mp->ma_keys == Py_EMPTY_KEYS) {
1560 return insert_to_emptydict(mp, key, hash, value);
1561 }
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001562 /* insertdict() handles any resizing that might be necessary */
1563 return insertdict(mp, key, hash, value);
1564}
1565
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001566static int
INADA Naoki778928b2017-08-03 23:45:15 +09001567delitem_common(PyDictObject *mp, Py_hash_t hash, Py_ssize_t ix,
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001568 PyObject *old_value)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001569{
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001570 PyObject *old_key;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001571 PyDictKeyEntry *ep;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001572
INADA Naoki778928b2017-08-03 23:45:15 +09001573 Py_ssize_t hashpos = lookdict_index(mp->ma_keys, hash, ix);
1574 assert(hashpos >= 0);
1575
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001576 mp->ma_used--;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001577 mp->ma_version_tag = DICT_NEXT_VERSION();
1578 ep = &DK_ENTRIES(mp->ma_keys)[ix];
INADA Naokia7576492018-11-14 18:39:27 +09001579 dictkeys_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001580 ENSURE_ALLOWS_DELETIONS(mp);
1581 old_key = ep->me_key;
1582 ep->me_key = NULL;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001583 ep->me_value = NULL;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001584 Py_DECREF(old_key);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001585 Py_DECREF(old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001586
Victor Stinner0fc91ee2019-04-12 21:51:34 +02001587 ASSERT_CONSISTENT(mp);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001588 return 0;
1589}
1590
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001591int
Tim Peters1f5871e2000-07-04 17:44:48 +00001592PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001593{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001594 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 assert(key);
1596 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001597 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 hash = PyObject_Hash(key);
1599 if (hash == -1)
1600 return -1;
1601 }
Victor Stinner742da042016-09-07 17:40:12 -07001602
1603 return _PyDict_DelItem_KnownHash(op, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001604}
1605
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001606int
1607_PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1608{
INADA Naoki778928b2017-08-03 23:45:15 +09001609 Py_ssize_t ix;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001610 PyDictObject *mp;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001611 PyObject *old_value;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001612
1613 if (!PyDict_Check(op)) {
1614 PyErr_BadInternalCall();
1615 return -1;
1616 }
1617 assert(key);
1618 assert(hash != -1);
1619 mp = (PyDictObject *)op;
INADA Naoki778928b2017-08-03 23:45:15 +09001620 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner742da042016-09-07 17:40:12 -07001621 if (ix == DKIX_ERROR)
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001622 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09001623 if (ix == DKIX_EMPTY || old_value == NULL) {
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001624 _PyErr_SetKeyError(key);
1625 return -1;
1626 }
Victor Stinner78601a32016-09-09 19:28:36 -07001627
1628 // Split table doesn't allow deletion. Combine it.
1629 if (_PyDict_HasSplitTable(mp)) {
1630 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1631 return -1;
1632 }
INADA Naoki778928b2017-08-03 23:45:15 +09001633 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner78601a32016-09-09 19:28:36 -07001634 assert(ix >= 0);
1635 }
1636
INADA Naoki778928b2017-08-03 23:45:15 +09001637 return delitem_common(mp, hash, ix, old_value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001638}
1639
Antoine Pitroud741ed42016-12-27 14:23:43 +01001640/* This function promises that the predicate -> deletion sequence is atomic
1641 * (i.e. protected by the GIL), assuming the predicate itself doesn't
1642 * release the GIL.
1643 */
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001644int
1645_PyDict_DelItemIf(PyObject *op, PyObject *key,
1646 int (*predicate)(PyObject *value))
1647{
Antoine Pitroud741ed42016-12-27 14:23:43 +01001648 Py_ssize_t hashpos, ix;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001649 PyDictObject *mp;
1650 Py_hash_t hash;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001651 PyObject *old_value;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001652 int res;
1653
1654 if (!PyDict_Check(op)) {
1655 PyErr_BadInternalCall();
1656 return -1;
1657 }
1658 assert(key);
1659 hash = PyObject_Hash(key);
1660 if (hash == -1)
1661 return -1;
1662 mp = (PyDictObject *)op;
INADA Naoki778928b2017-08-03 23:45:15 +09001663 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001664 if (ix == DKIX_ERROR)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001665 return -1;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001666 if (ix == DKIX_EMPTY || old_value == NULL) {
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001667 _PyErr_SetKeyError(key);
1668 return -1;
1669 }
Antoine Pitroud741ed42016-12-27 14:23:43 +01001670
1671 // Split table doesn't allow deletion. Combine it.
1672 if (_PyDict_HasSplitTable(mp)) {
1673 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1674 return -1;
1675 }
INADA Naoki778928b2017-08-03 23:45:15 +09001676 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001677 assert(ix >= 0);
1678 }
1679
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001680 res = predicate(old_value);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001681 if (res == -1)
1682 return -1;
INADA Naoki778928b2017-08-03 23:45:15 +09001683
1684 hashpos = lookdict_index(mp->ma_keys, hash, ix);
1685 assert(hashpos >= 0);
1686
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001687 if (res > 0)
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001688 return delitem_common(mp, hashpos, ix, old_value);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001689 else
1690 return 0;
1691}
1692
1693
Guido van Rossum25831651993-05-19 14:50:45 +00001694void
Tim Peters1f5871e2000-07-04 17:44:48 +00001695PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 PyDictObject *mp;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001698 PyDictKeysObject *oldkeys;
1699 PyObject **oldvalues;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 if (!PyDict_Check(op))
1703 return;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001704 mp = ((PyDictObject *)op);
1705 oldkeys = mp->ma_keys;
1706 oldvalues = mp->ma_values;
1707 if (oldvalues == empty_values)
1708 return;
1709 /* Empty the dict... */
INADA Naokia7576492018-11-14 18:39:27 +09001710 dictkeys_incref(Py_EMPTY_KEYS);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001711 mp->ma_keys = Py_EMPTY_KEYS;
1712 mp->ma_values = empty_values;
1713 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001714 mp->ma_version_tag = DICT_NEXT_VERSION();
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001715 /* ...then clear the keys and values */
1716 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001717 n = oldkeys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001718 for (i = 0; i < n; i++)
1719 Py_CLEAR(oldvalues[i]);
1720 free_values(oldvalues);
INADA Naokia7576492018-11-14 18:39:27 +09001721 dictkeys_decref(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001722 }
1723 else {
1724 assert(oldkeys->dk_refcnt == 1);
INADA Naokia7576492018-11-14 18:39:27 +09001725 dictkeys_decref(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001726 }
Victor Stinner0fc91ee2019-04-12 21:51:34 +02001727 ASSERT_CONSISTENT(mp);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001728}
1729
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001730/* Internal version of PyDict_Next that returns a hash value in addition
1731 * to the key and value.
1732 * Return 1 on success, return 0 when the reached the end of the dictionary
1733 * (or if op is not a dictionary)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001734 */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001735int
1736_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
1737 PyObject **pvalue, Py_hash_t *phash)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001738{
INADA Naokica2d8be2016-11-04 16:59:10 +09001739 Py_ssize_t i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001740 PyDictObject *mp;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001741 PyDictKeyEntry *entry_ptr;
1742 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001743
1744 if (!PyDict_Check(op))
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001745 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 mp = (PyDictObject *)op;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001747 i = *ppos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001748 if (mp->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09001749 if (i < 0 || i >= mp->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001750 return 0;
INADA Naokica2d8be2016-11-04 16:59:10 +09001751 /* values of split table is always dense */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001752 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
INADA Naokica2d8be2016-11-04 16:59:10 +09001753 value = mp->ma_values[i];
1754 assert(value != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001756 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09001757 Py_ssize_t n = mp->ma_keys->dk_nentries;
1758 if (i < 0 || i >= n)
1759 return 0;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001760 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
1761 while (i < n && entry_ptr->me_value == NULL) {
1762 entry_ptr++;
1763 i++;
Victor Stinner742da042016-09-07 17:40:12 -07001764 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001765 if (i >= n)
1766 return 0;
1767 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001769 *ppos = i+1;
1770 if (pkey)
1771 *pkey = entry_ptr->me_key;
1772 if (phash)
1773 *phash = entry_ptr->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001774 if (pvalue)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001775 *pvalue = value;
1776 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001777}
1778
Tim Peters080c88b2003-02-15 03:01:11 +00001779/*
1780 * Iterate over a dict. Use like so:
1781 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001782 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +00001783 * PyObject *key, *value;
1784 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +00001785 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001786 * Refer to borrowed references in key and value.
Tim Peters080c88b2003-02-15 03:01:11 +00001787 * }
1788 *
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001789 * Return 1 on success, return 0 when the reached the end of the dictionary
1790 * (or if op is not a dictionary)
1791 *
Tim Peters080c88b2003-02-15 03:01:11 +00001792 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +00001793 * mutates the dict. One exception: it is safe if the loop merely changes
1794 * the values associated with the keys (but doesn't insert new keys or
1795 * delete keys), via PyDict_SetItem().
1796 */
Guido van Rossum25831651993-05-19 14:50:45 +00001797int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001798PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001799{
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001800 return _PyDict_Next(op, ppos, pkey, pvalue, NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00001801}
1802
Eric Snow96c6af92015-05-29 22:21:39 -06001803/* Internal version of dict.pop(). */
1804PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001805_PyDict_Pop_KnownHash(PyObject *dict, PyObject *key, Py_hash_t hash, PyObject *deflt)
Eric Snow96c6af92015-05-29 22:21:39 -06001806{
Victor Stinner742da042016-09-07 17:40:12 -07001807 Py_ssize_t ix, hashpos;
Eric Snow96c6af92015-05-29 22:21:39 -06001808 PyObject *old_value, *old_key;
1809 PyDictKeyEntry *ep;
Yury Selivanov684ef2c2016-10-28 19:01:21 -04001810 PyDictObject *mp;
1811
1812 assert(PyDict_Check(dict));
1813 mp = (PyDictObject *)dict;
Eric Snow96c6af92015-05-29 22:21:39 -06001814
1815 if (mp->ma_used == 0) {
1816 if (deflt) {
1817 Py_INCREF(deflt);
1818 return deflt;
1819 }
1820 _PyErr_SetKeyError(key);
1821 return NULL;
1822 }
INADA Naoki778928b2017-08-03 23:45:15 +09001823 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner742da042016-09-07 17:40:12 -07001824 if (ix == DKIX_ERROR)
Eric Snow96c6af92015-05-29 22:21:39 -06001825 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001826 if (ix == DKIX_EMPTY || old_value == NULL) {
Eric Snow96c6af92015-05-29 22:21:39 -06001827 if (deflt) {
1828 Py_INCREF(deflt);
1829 return deflt;
1830 }
1831 _PyErr_SetKeyError(key);
1832 return NULL;
1833 }
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001834
Victor Stinner78601a32016-09-09 19:28:36 -07001835 // Split table doesn't allow deletion. Combine it.
1836 if (_PyDict_HasSplitTable(mp)) {
1837 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1838 return NULL;
1839 }
INADA Naoki778928b2017-08-03 23:45:15 +09001840 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner78601a32016-09-09 19:28:36 -07001841 assert(ix >= 0);
1842 }
1843
INADA Naoki778928b2017-08-03 23:45:15 +09001844 hashpos = lookdict_index(mp->ma_keys, hash, ix);
1845 assert(hashpos >= 0);
Victor Stinner78601a32016-09-09 19:28:36 -07001846 assert(old_value != NULL);
Eric Snow96c6af92015-05-29 22:21:39 -06001847 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001848 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naokia7576492018-11-14 18:39:27 +09001849 dictkeys_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
Victor Stinner78601a32016-09-09 19:28:36 -07001850 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1851 ENSURE_ALLOWS_DELETIONS(mp);
1852 old_key = ep->me_key;
1853 ep->me_key = NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001854 ep->me_value = NULL;
Victor Stinner78601a32016-09-09 19:28:36 -07001855 Py_DECREF(old_key);
Victor Stinner611b0fa2016-09-14 15:02:01 +02001856
Victor Stinner0fc91ee2019-04-12 21:51:34 +02001857 ASSERT_CONSISTENT(mp);
Eric Snow96c6af92015-05-29 22:21:39 -06001858 return old_value;
1859}
1860
Serhiy Storchaka67796522017-01-12 18:34:33 +02001861PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001862_PyDict_Pop(PyObject *dict, PyObject *key, PyObject *deflt)
Serhiy Storchaka67796522017-01-12 18:34:33 +02001863{
1864 Py_hash_t hash;
1865
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001866 if (((PyDictObject *)dict)->ma_used == 0) {
Serhiy Storchaka67796522017-01-12 18:34:33 +02001867 if (deflt) {
1868 Py_INCREF(deflt);
1869 return deflt;
1870 }
1871 _PyErr_SetKeyError(key);
1872 return NULL;
1873 }
1874 if (!PyUnicode_CheckExact(key) ||
1875 (hash = ((PyASCIIObject *) key)->hash) == -1) {
1876 hash = PyObject_Hash(key);
1877 if (hash == -1)
1878 return NULL;
1879 }
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001880 return _PyDict_Pop_KnownHash(dict, key, hash, deflt);
Serhiy Storchaka67796522017-01-12 18:34:33 +02001881}
1882
Eric Snow96c6af92015-05-29 22:21:39 -06001883/* Internal version of dict.from_keys(). It is subclass-friendly. */
1884PyObject *
1885_PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
1886{
1887 PyObject *it; /* iter(iterable) */
1888 PyObject *key;
1889 PyObject *d;
1890 int status;
1891
Victor Stinnera5ed5f02016-12-06 18:45:50 +01001892 d = _PyObject_CallNoArg(cls);
Eric Snow96c6af92015-05-29 22:21:39 -06001893 if (d == NULL)
1894 return NULL;
1895
1896 if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
1897 if (PyDict_CheckExact(iterable)) {
1898 PyDictObject *mp = (PyDictObject *)d;
1899 PyObject *oldvalue;
1900 Py_ssize_t pos = 0;
1901 PyObject *key;
1902 Py_hash_t hash;
1903
Serhiy Storchakac61ac162017-03-21 08:52:38 +02001904 if (dictresize(mp, ESTIMATE_SIZE(PyDict_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001905 Py_DECREF(d);
1906 return NULL;
1907 }
1908
1909 while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
1910 if (insertdict(mp, key, hash, value)) {
1911 Py_DECREF(d);
1912 return NULL;
1913 }
1914 }
1915 return d;
1916 }
1917 if (PyAnySet_CheckExact(iterable)) {
1918 PyDictObject *mp = (PyDictObject *)d;
1919 Py_ssize_t pos = 0;
1920 PyObject *key;
1921 Py_hash_t hash;
1922
Victor Stinner742da042016-09-07 17:40:12 -07001923 if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001924 Py_DECREF(d);
1925 return NULL;
1926 }
1927
1928 while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
1929 if (insertdict(mp, key, hash, value)) {
1930 Py_DECREF(d);
1931 return NULL;
1932 }
1933 }
1934 return d;
1935 }
1936 }
1937
1938 it = PyObject_GetIter(iterable);
1939 if (it == NULL){
1940 Py_DECREF(d);
1941 return NULL;
1942 }
1943
1944 if (PyDict_CheckExact(d)) {
1945 while ((key = PyIter_Next(it)) != NULL) {
1946 status = PyDict_SetItem(d, key, value);
1947 Py_DECREF(key);
1948 if (status < 0)
1949 goto Fail;
1950 }
1951 } else {
1952 while ((key = PyIter_Next(it)) != NULL) {
1953 status = PyObject_SetItem(d, key, value);
1954 Py_DECREF(key);
1955 if (status < 0)
1956 goto Fail;
1957 }
1958 }
1959
1960 if (PyErr_Occurred())
1961 goto Fail;
1962 Py_DECREF(it);
1963 return d;
1964
1965Fail:
1966 Py_DECREF(it);
1967 Py_DECREF(d);
1968 return NULL;
1969}
1970
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001971/* Methods */
1972
1973static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001974dict_dealloc(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001975{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001976 PyObject **values = mp->ma_values;
1977 PyDictKeysObject *keys = mp->ma_keys;
1978 Py_ssize_t i, n;
INADA Naokia6296d32017-08-24 14:55:17 +09001979
1980 /* bpo-31095: UnTrack is needed before calling any callbacks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 PyObject_GC_UnTrack(mp);
Jeroen Demeyer351c6742019-05-10 19:21:11 +02001982 Py_TRASHCAN_BEGIN(mp, dict_dealloc)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001983 if (values != NULL) {
1984 if (values != empty_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001985 for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001986 Py_XDECREF(values[i]);
1987 }
1988 free_values(values);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 }
INADA Naokia7576492018-11-14 18:39:27 +09001990 dictkeys_decref(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 }
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02001992 else if (keys != NULL) {
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001993 assert(keys->dk_refcnt == 1);
INADA Naokia7576492018-11-14 18:39:27 +09001994 dictkeys_decref(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001995 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
1997 free_list[numfree++] = mp;
1998 else
1999 Py_TYPE(mp)->tp_free((PyObject *)mp);
Jeroen Demeyer351c6742019-05-10 19:21:11 +02002000 Py_TRASHCAN_END
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002001}
2002
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002004static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002005dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 Py_ssize_t i;
Victor Stinnerf91929b2013-11-19 13:07:38 +01002008 PyObject *key = NULL, *value = NULL;
2009 _PyUnicodeWriter writer;
2010 int first;
Guido van Rossum255443b1998-04-10 22:47:14 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 i = Py_ReprEnter((PyObject *)mp);
2013 if (i != 0) {
2014 return i > 0 ? PyUnicode_FromString("{...}") : NULL;
2015 }
Guido van Rossum255443b1998-04-10 22:47:14 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 if (mp->ma_used == 0) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01002018 Py_ReprLeave((PyObject *)mp);
2019 return PyUnicode_FromString("{}");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 }
Tim Petersa7259592001-06-16 05:11:17 +00002021
Victor Stinnerf91929b2013-11-19 13:07:38 +01002022 _PyUnicodeWriter_Init(&writer);
2023 writer.overallocate = 1;
2024 /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
2025 writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +00002026
Victor Stinnerf91929b2013-11-19 13:07:38 +01002027 if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
2028 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 /* Do repr() on each key+value pair, and insert ": " between them.
2031 Note that repr may mutate the dict. */
2032 i = 0;
Victor Stinnerf91929b2013-11-19 13:07:38 +01002033 first = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01002035 PyObject *s;
2036 int res;
2037
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002038 /* Prevent repr from deleting key or value during key format. */
2039 Py_INCREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 Py_INCREF(value);
Victor Stinnerf97dfd72013-07-18 01:00:45 +02002041
Victor Stinnerf91929b2013-11-19 13:07:38 +01002042 if (!first) {
2043 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
2044 goto error;
2045 }
2046 first = 0;
2047
2048 s = PyObject_Repr(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 if (s == NULL)
Victor Stinnerf91929b2013-11-19 13:07:38 +01002050 goto error;
2051 res = _PyUnicodeWriter_WriteStr(&writer, s);
2052 Py_DECREF(s);
2053 if (res < 0)
2054 goto error;
2055
2056 if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
2057 goto error;
2058
2059 s = PyObject_Repr(value);
2060 if (s == NULL)
2061 goto error;
2062 res = _PyUnicodeWriter_WriteStr(&writer, s);
2063 Py_DECREF(s);
2064 if (res < 0)
2065 goto error;
2066
2067 Py_CLEAR(key);
2068 Py_CLEAR(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 }
Tim Petersa7259592001-06-16 05:11:17 +00002070
Victor Stinnerf91929b2013-11-19 13:07:38 +01002071 writer.overallocate = 0;
2072 if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
2073 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 Py_ReprLeave((PyObject *)mp);
Victor Stinnerf91929b2013-11-19 13:07:38 +01002076
2077 return _PyUnicodeWriter_Finish(&writer);
2078
2079error:
2080 Py_ReprLeave((PyObject *)mp);
2081 _PyUnicodeWriter_Dealloc(&writer);
2082 Py_XDECREF(key);
2083 Py_XDECREF(value);
2084 return NULL;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002085}
2086
Martin v. Löwis18e16552006-02-15 17:27:45 +00002087static Py_ssize_t
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002088dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 return mp->ma_used;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002091}
2092
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002093static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002094dict_subscript(PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002095{
Victor Stinner742da042016-09-07 17:40:12 -07002096 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002097 Py_hash_t hash;
INADA Naokiba609772016-12-07 20:41:42 +09002098 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002101 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 hash = PyObject_Hash(key);
2103 if (hash == -1)
2104 return NULL;
2105 }
INADA Naoki778928b2017-08-03 23:45:15 +09002106 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002107 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002109 if (ix == DKIX_EMPTY || value == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 if (!PyDict_CheckExact(mp)) {
2111 /* Look up __missing__ method if we're a subclass. */
2112 PyObject *missing, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05002113 _Py_IDENTIFIER(__missing__);
2114 missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 if (missing != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002116 res = PyObject_CallFunctionObjArgs(missing,
2117 key, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 Py_DECREF(missing);
2119 return res;
2120 }
2121 else if (PyErr_Occurred())
2122 return NULL;
2123 }
Raymond Hettinger69492da2013-09-02 15:59:26 -07002124 _PyErr_SetKeyError(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 return NULL;
2126 }
INADA Naokiba609772016-12-07 20:41:42 +09002127 Py_INCREF(value);
2128 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002129}
2130
2131static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002132dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 if (w == NULL)
2135 return PyDict_DelItem((PyObject *)mp, v);
2136 else
2137 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002138}
2139
Guido van Rossuma9e7a811997-05-13 21:02:11 +00002140static PyMappingMethods dict_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 (lenfunc)dict_length, /*mp_length*/
2142 (binaryfunc)dict_subscript, /*mp_subscript*/
2143 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002144};
2145
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002146static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002147dict_keys(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002148{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002149 PyObject *v;
2150 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002151 PyDictKeyEntry *ep;
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002152 Py_ssize_t n, offset;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002153 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002154
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002155 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 n = mp->ma_used;
2157 v = PyList_New(n);
2158 if (v == NULL)
2159 return NULL;
2160 if (n != mp->ma_used) {
2161 /* Durnit. The allocations caused the dict to resize.
2162 * Just start over, this shouldn't normally happen.
2163 */
2164 Py_DECREF(v);
2165 goto again;
2166 }
Victor Stinner742da042016-09-07 17:40:12 -07002167 ep = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002168 if (mp->ma_values) {
2169 value_ptr = mp->ma_values;
2170 offset = sizeof(PyObject *);
2171 }
2172 else {
2173 value_ptr = &ep[0].me_value;
2174 offset = sizeof(PyDictKeyEntry);
2175 }
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002176 for (i = 0, j = 0; j < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002177 if (*value_ptr != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 PyObject *key = ep[i].me_key;
2179 Py_INCREF(key);
2180 PyList_SET_ITEM(v, j, key);
2181 j++;
2182 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002183 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 }
2185 assert(j == n);
2186 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002187}
2188
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002189static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002190dict_values(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002191{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002192 PyObject *v;
2193 Py_ssize_t i, j;
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002194 PyDictKeyEntry *ep;
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002195 Py_ssize_t n, offset;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002196 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002197
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002198 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 n = mp->ma_used;
2200 v = PyList_New(n);
2201 if (v == NULL)
2202 return NULL;
2203 if (n != mp->ma_used) {
2204 /* Durnit. The allocations caused the dict to resize.
2205 * Just start over, this shouldn't normally happen.
2206 */
2207 Py_DECREF(v);
2208 goto again;
2209 }
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002210 ep = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002211 if (mp->ma_values) {
2212 value_ptr = mp->ma_values;
2213 offset = sizeof(PyObject *);
2214 }
2215 else {
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002216 value_ptr = &ep[0].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002217 offset = sizeof(PyDictKeyEntry);
2218 }
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002219 for (i = 0, j = 0; j < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002220 PyObject *value = *value_ptr;
2221 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2222 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 Py_INCREF(value);
2224 PyList_SET_ITEM(v, j, value);
2225 j++;
2226 }
2227 }
2228 assert(j == n);
2229 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002230}
2231
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002232static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002233dict_items(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002234{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002235 PyObject *v;
2236 Py_ssize_t i, j, n;
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002237 Py_ssize_t offset;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002238 PyObject *item, *key;
2239 PyDictKeyEntry *ep;
2240 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 /* Preallocate the list of tuples, to avoid allocations during
2243 * the loop over the items, which could trigger GC, which
2244 * could resize the dict. :-(
2245 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002246 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 n = mp->ma_used;
2248 v = PyList_New(n);
2249 if (v == NULL)
2250 return NULL;
2251 for (i = 0; i < n; i++) {
2252 item = PyTuple_New(2);
2253 if (item == NULL) {
2254 Py_DECREF(v);
2255 return NULL;
2256 }
2257 PyList_SET_ITEM(v, i, item);
2258 }
2259 if (n != mp->ma_used) {
2260 /* Durnit. The allocations caused the dict to resize.
2261 * Just start over, this shouldn't normally happen.
2262 */
2263 Py_DECREF(v);
2264 goto again;
2265 }
2266 /* Nothing we do below makes any function calls. */
Victor Stinner742da042016-09-07 17:40:12 -07002267 ep = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002268 if (mp->ma_values) {
2269 value_ptr = mp->ma_values;
2270 offset = sizeof(PyObject *);
2271 }
2272 else {
2273 value_ptr = &ep[0].me_value;
2274 offset = sizeof(PyDictKeyEntry);
2275 }
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002276 for (i = 0, j = 0; j < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002277 PyObject *value = *value_ptr;
2278 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2279 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 key = ep[i].me_key;
2281 item = PyList_GET_ITEM(v, j);
2282 Py_INCREF(key);
2283 PyTuple_SET_ITEM(item, 0, key);
2284 Py_INCREF(value);
2285 PyTuple_SET_ITEM(item, 1, value);
2286 j++;
2287 }
2288 }
2289 assert(j == n);
2290 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002291}
2292
Larry Hastings5c661892014-01-24 06:17:25 -08002293/*[clinic input]
2294@classmethod
2295dict.fromkeys
Larry Hastings5c661892014-01-24 06:17:25 -08002296 iterable: object
2297 value: object=None
2298 /
2299
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002300Create a new dictionary with keys from iterable and values set to value.
Larry Hastings5c661892014-01-24 06:17:25 -08002301[clinic start generated code]*/
2302
Larry Hastings5c661892014-01-24 06:17:25 -08002303static PyObject *
2304dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002305/*[clinic end generated code: output=8fb98e4b10384999 input=382ba4855d0f74c3]*/
Larry Hastings5c661892014-01-24 06:17:25 -08002306{
Eric Snow96c6af92015-05-29 22:21:39 -06002307 return _PyDict_FromKeys((PyObject *)type, iterable, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002308}
2309
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002310static int
Victor Stinner742da042016-09-07 17:40:12 -07002311dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
2312 const char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 PyObject *arg = NULL;
2315 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002316
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002317 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 result = -1;
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002319 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 else if (arg != NULL) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02002321 _Py_IDENTIFIER(keys);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002322 PyObject *func;
2323 if (_PyObject_LookupAttrId(arg, &PyId_keys, &func) < 0) {
2324 result = -1;
2325 }
2326 else if (func != NULL) {
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002327 Py_DECREF(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 result = PyDict_Merge(self, arg, 1);
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002329 }
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002330 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002331 result = PyDict_MergeFromSeq2(self, arg, 1);
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002332 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 }
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 if (result == 0 && kwds != NULL) {
2336 if (PyArg_ValidateKeywordArguments(kwds))
2337 result = PyDict_Merge(self, kwds, 1);
2338 else
2339 result = -1;
2340 }
2341 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002342}
2343
Victor Stinner91f0d4a2017-01-19 12:45:06 +01002344/* Note: dict.update() uses the METH_VARARGS|METH_KEYWORDS calling convention.
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002345 Using METH_FASTCALL|METH_KEYWORDS would make dict.update(**dict2) calls
2346 slower, see the issue #29312. */
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002347static PyObject *
2348dict_update(PyObject *self, PyObject *args, PyObject *kwds)
2349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 if (dict_update_common(self, args, kwds, "update") != -1)
2351 Py_RETURN_NONE;
2352 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002353}
2354
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002355/* Update unconditionally replaces existing items.
2356 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00002357 otherwise it leaves existing items unchanged.
2358
2359 PyDict_{Update,Merge} update/merge from a mapping object.
2360
Tim Petersf582b822001-12-11 18:51:08 +00002361 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00002362 producing iterable objects of length 2.
2363*/
2364
Tim Petersf582b822001-12-11 18:51:08 +00002365int
Tim Peters1fc240e2001-10-26 05:06:50 +00002366PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
2367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 PyObject *it; /* iter(seq2) */
2369 Py_ssize_t i; /* index into seq2 of current element */
2370 PyObject *item; /* seq2[i] */
2371 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 assert(d != NULL);
2374 assert(PyDict_Check(d));
2375 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 it = PyObject_GetIter(seq2);
2378 if (it == NULL)
2379 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 for (i = 0; ; ++i) {
2382 PyObject *key, *value;
2383 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 fast = NULL;
2386 item = PyIter_Next(it);
2387 if (item == NULL) {
2388 if (PyErr_Occurred())
2389 goto Fail;
2390 break;
2391 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 /* Convert item to sequence, and verify length 2. */
2394 fast = PySequence_Fast(item, "");
2395 if (fast == NULL) {
2396 if (PyErr_ExceptionMatches(PyExc_TypeError))
2397 PyErr_Format(PyExc_TypeError,
2398 "cannot convert dictionary update "
2399 "sequence element #%zd to a sequence",
2400 i);
2401 goto Fail;
2402 }
2403 n = PySequence_Fast_GET_SIZE(fast);
2404 if (n != 2) {
2405 PyErr_Format(PyExc_ValueError,
2406 "dictionary update sequence element #%zd "
2407 "has length %zd; 2 is required",
2408 i, n);
2409 goto Fail;
2410 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 /* Update/merge with this (key, value) pair. */
2413 key = PySequence_Fast_GET_ITEM(fast, 0);
2414 value = PySequence_Fast_GET_ITEM(fast, 1);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002415 Py_INCREF(key);
2416 Py_INCREF(value);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002417 if (override) {
2418 if (PyDict_SetItem(d, key, value) < 0) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002419 Py_DECREF(key);
2420 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 goto Fail;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002422 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002424 else if (PyDict_GetItemWithError(d, key) == NULL) {
2425 if (PyErr_Occurred() || PyDict_SetItem(d, key, value) < 0) {
2426 Py_DECREF(key);
2427 Py_DECREF(value);
2428 goto Fail;
2429 }
2430 }
2431
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002432 Py_DECREF(key);
2433 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 Py_DECREF(fast);
2435 Py_DECREF(item);
2436 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 i = 0;
Victor Stinner0fc91ee2019-04-12 21:51:34 +02002439 ASSERT_CONSISTENT(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00002441Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 Py_XDECREF(item);
2443 Py_XDECREF(fast);
2444 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002445Return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 Py_DECREF(it);
2447 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00002448}
2449
doko@ubuntu.comc96df682016-10-11 08:04:02 +02002450static int
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002451dict_merge(PyObject *a, PyObject *b, int override)
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002452{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002453 PyDictObject *mp, *other;
2454 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -07002455 PyDictKeyEntry *entry, *ep0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002456
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002457 assert(0 <= override && override <= 2);
2458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 /* We accept for the argument either a concrete dictionary object,
2460 * or an abstract "mapping" object. For the former, we can do
2461 * things quite efficiently. For the latter, we only require that
2462 * PyMapping_Keys() and PyObject_GetItem() be supported.
2463 */
2464 if (a == NULL || !PyDict_Check(a) || b == NULL) {
2465 PyErr_BadInternalCall();
2466 return -1;
2467 }
2468 mp = (PyDictObject*)a;
INADA Naoki2aaf98c2018-09-26 12:59:00 +09002469 if (PyDict_Check(b) && (Py_TYPE(b)->tp_iter == (getiterfunc)dict_iter)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 other = (PyDictObject*)b;
2471 if (other == mp || other->ma_used == 0)
2472 /* a.update(a) or a.update({}); nothing to do */
2473 return 0;
2474 if (mp->ma_used == 0)
2475 /* Since the target dict is empty, PyDict_GetItem()
2476 * always returns NULL. Setting override to 1
2477 * skips the unnecessary test.
2478 */
2479 override = 1;
2480 /* Do one big resize at the start, rather than
2481 * incrementally resizing as we insert new items. Expect
2482 * that there will be no (or few) overlapping keys.
2483 */
INADA Naokib1152be2016-10-27 19:26:50 +09002484 if (USABLE_FRACTION(mp->ma_keys->dk_size) < other->ma_used) {
2485 if (dictresize(mp, ESTIMATE_SIZE(mp->ma_used + other->ma_used))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 return -1;
INADA Naokib1152be2016-10-27 19:26:50 +09002487 }
2488 }
Victor Stinner742da042016-09-07 17:40:12 -07002489 ep0 = DK_ENTRIES(other->ma_keys);
2490 for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002491 PyObject *key, *value;
2492 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002493 entry = &ep0[i];
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002494 key = entry->me_key;
2495 hash = entry->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002496 if (other->ma_values)
2497 value = other->ma_values[i];
2498 else
2499 value = entry->me_value;
2500
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002501 if (value != NULL) {
2502 int err = 0;
2503 Py_INCREF(key);
2504 Py_INCREF(value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002505 if (override == 1)
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002506 err = insertdict(mp, key, hash, value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002507 else if (_PyDict_GetItem_KnownHash(a, key, hash) == NULL) {
2508 if (PyErr_Occurred()) {
2509 Py_DECREF(value);
2510 Py_DECREF(key);
2511 return -1;
2512 }
2513 err = insertdict(mp, key, hash, value);
2514 }
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002515 else if (override != 0) {
2516 _PyErr_SetKeyError(key);
2517 Py_DECREF(value);
2518 Py_DECREF(key);
2519 return -1;
2520 }
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002521 Py_DECREF(value);
2522 Py_DECREF(key);
2523 if (err != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 return -1;
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002525
Victor Stinner742da042016-09-07 17:40:12 -07002526 if (n != other->ma_keys->dk_nentries) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002527 PyErr_SetString(PyExc_RuntimeError,
2528 "dict mutated during update");
2529 return -1;
2530 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 }
2532 }
2533 }
2534 else {
2535 /* Do it the generic, slower way */
2536 PyObject *keys = PyMapping_Keys(b);
2537 PyObject *iter;
2538 PyObject *key, *value;
2539 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 if (keys == NULL)
2542 /* Docstring says this is equivalent to E.keys() so
2543 * if E doesn't have a .keys() method we want
2544 * AttributeError to percolate up. Might as well
2545 * do the same for any other error.
2546 */
2547 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 iter = PyObject_GetIter(keys);
2550 Py_DECREF(keys);
2551 if (iter == NULL)
2552 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002555 if (override != 1) {
2556 if (PyDict_GetItemWithError(a, key) != NULL) {
2557 if (override != 0) {
2558 _PyErr_SetKeyError(key);
2559 Py_DECREF(key);
2560 Py_DECREF(iter);
2561 return -1;
2562 }
2563 Py_DECREF(key);
2564 continue;
2565 }
2566 else if (PyErr_Occurred()) {
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002567 Py_DECREF(key);
2568 Py_DECREF(iter);
2569 return -1;
2570 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 }
2572 value = PyObject_GetItem(b, key);
2573 if (value == NULL) {
2574 Py_DECREF(iter);
2575 Py_DECREF(key);
2576 return -1;
2577 }
2578 status = PyDict_SetItem(a, key, value);
2579 Py_DECREF(key);
2580 Py_DECREF(value);
2581 if (status < 0) {
2582 Py_DECREF(iter);
2583 return -1;
2584 }
2585 }
2586 Py_DECREF(iter);
2587 if (PyErr_Occurred())
2588 /* Iterator completed, via error */
2589 return -1;
2590 }
Victor Stinner0fc91ee2019-04-12 21:51:34 +02002591 ASSERT_CONSISTENT(a);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002593}
2594
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002595int
2596PyDict_Update(PyObject *a, PyObject *b)
2597{
2598 return dict_merge(a, b, 1);
2599}
2600
2601int
2602PyDict_Merge(PyObject *a, PyObject *b, int override)
2603{
2604 /* XXX Deprecate override not in (0, 1). */
2605 return dict_merge(a, b, override != 0);
2606}
2607
2608int
2609_PyDict_MergeEx(PyObject *a, PyObject *b, int override)
2610{
2611 return dict_merge(a, b, override);
2612}
2613
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002614static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302615dict_copy(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002618}
2619
2620PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002621PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 PyObject *copy;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002624 PyDictObject *mp;
2625 Py_ssize_t i, n;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 if (o == NULL || !PyDict_Check(o)) {
2628 PyErr_BadInternalCall();
2629 return NULL;
2630 }
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002631
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002632 mp = (PyDictObject *)o;
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002633 if (mp->ma_used == 0) {
2634 /* The dict is empty; just return a new dict. */
2635 return PyDict_New();
2636 }
2637
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002638 if (_PyDict_HasSplitTable(mp)) {
2639 PyDictObject *split_copy;
Victor Stinner742da042016-09-07 17:40:12 -07002640 Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
2641 PyObject **newvalues;
2642 newvalues = new_values(size);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002643 if (newvalues == NULL)
2644 return PyErr_NoMemory();
2645 split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
2646 if (split_copy == NULL) {
2647 free_values(newvalues);
2648 return NULL;
2649 }
2650 split_copy->ma_values = newvalues;
2651 split_copy->ma_keys = mp->ma_keys;
2652 split_copy->ma_used = mp->ma_used;
INADA Naokid1c82c52018-04-03 11:43:53 +09002653 split_copy->ma_version_tag = DICT_NEXT_VERSION();
INADA Naokia7576492018-11-14 18:39:27 +09002654 dictkeys_incref(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002655 for (i = 0, n = size; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002656 PyObject *value = mp->ma_values[i];
2657 Py_XINCREF(value);
2658 split_copy->ma_values[i] = value;
2659 }
Benjamin Peterson7ce67e42012-04-24 10:32:57 -04002660 if (_PyObject_GC_IS_TRACKED(mp))
2661 _PyObject_GC_TRACK(split_copy);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002662 return (PyObject *)split_copy;
2663 }
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002664
2665 if (PyDict_CheckExact(mp) && mp->ma_values == NULL &&
2666 (mp->ma_used >= (mp->ma_keys->dk_nentries * 2) / 3))
2667 {
2668 /* Use fast-copy if:
2669
2670 (1) 'mp' is an instance of a subclassed dict; and
2671
2672 (2) 'mp' is not a split-dict; and
2673
2674 (3) if 'mp' is non-compact ('del' operation does not resize dicts),
2675 do fast-copy only if it has at most 1/3 non-used keys.
2676
Ville Skyttä61f82e02018-04-20 23:08:45 +03002677 The last condition (3) is important to guard against a pathological
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002678 case when a large dict is almost emptied with multiple del/pop
2679 operations and copied after that. In cases like this, we defer to
2680 PyDict_Merge, which produces a compacted copy.
2681 */
2682 return clone_combined_dict(mp);
2683 }
2684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 copy = PyDict_New();
2686 if (copy == NULL)
2687 return NULL;
2688 if (PyDict_Merge(copy, o, 1) == 0)
2689 return copy;
2690 Py_DECREF(copy);
2691 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002692}
2693
Martin v. Löwis18e16552006-02-15 17:27:45 +00002694Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00002695PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00002696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 if (mp == NULL || !PyDict_Check(mp)) {
2698 PyErr_BadInternalCall();
2699 return -1;
2700 }
2701 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00002702}
2703
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002704PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002705PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 if (mp == NULL || !PyDict_Check(mp)) {
2708 PyErr_BadInternalCall();
2709 return NULL;
2710 }
2711 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002712}
2713
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002714PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002715PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 if (mp == NULL || !PyDict_Check(mp)) {
2718 PyErr_BadInternalCall();
2719 return NULL;
2720 }
2721 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002722}
2723
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002724PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002725PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 if (mp == NULL || !PyDict_Check(mp)) {
2728 PyErr_BadInternalCall();
2729 return NULL;
2730 }
2731 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002732}
2733
Tim Peterse63415e2001-05-08 04:38:29 +00002734/* Return 1 if dicts equal, 0 if not, -1 if error.
2735 * Gets out as soon as any difference is detected.
2736 * Uses only Py_EQ comparison.
2737 */
2738static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002739dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00002740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00002742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 if (a->ma_used != b->ma_used)
2744 /* can't be equal if # of entries differ */
2745 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Victor Stinner742da042016-09-07 17:40:12 -07002747 for (i = 0; i < a->ma_keys->dk_nentries; i++) {
2748 PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002749 PyObject *aval;
2750 if (a->ma_values)
2751 aval = a->ma_values[i];
2752 else
2753 aval = ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 if (aval != NULL) {
2755 int cmp;
2756 PyObject *bval;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002757 PyObject *key = ep->me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 /* temporarily bump aval's refcount to ensure it stays
2759 alive until we're done with it */
2760 Py_INCREF(aval);
2761 /* ditto for key */
2762 Py_INCREF(key);
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002763 /* reuse the known hash value */
INADA Naoki778928b2017-08-03 23:45:15 +09002764 b->ma_keys->dk_lookup(b, key, ep->me_hash, &bval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 if (bval == NULL) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002766 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 Py_DECREF(aval);
2768 if (PyErr_Occurred())
2769 return -1;
2770 return 0;
2771 }
2772 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002773 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 Py_DECREF(aval);
2775 if (cmp <= 0) /* error or not equal */
2776 return cmp;
2777 }
2778 }
2779 return 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002780}
Tim Peterse63415e2001-05-08 04:38:29 +00002781
2782static PyObject *
2783dict_richcompare(PyObject *v, PyObject *w, int op)
2784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 int cmp;
2786 PyObject *res;
Tim Peterse63415e2001-05-08 04:38:29 +00002787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 if (!PyDict_Check(v) || !PyDict_Check(w)) {
2789 res = Py_NotImplemented;
2790 }
2791 else if (op == Py_EQ || op == Py_NE) {
2792 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
2793 if (cmp < 0)
2794 return NULL;
2795 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
2796 }
2797 else
2798 res = Py_NotImplemented;
2799 Py_INCREF(res);
2800 return res;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002801}
Tim Peterse63415e2001-05-08 04:38:29 +00002802
Larry Hastings61272b72014-01-07 12:41:53 -08002803/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002804
2805@coexist
2806dict.__contains__
2807
2808 key: object
2809 /
2810
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002811True if the dictionary has the specified key, else False.
Larry Hastings61272b72014-01-07 12:41:53 -08002812[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002813
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002814static PyObject *
Larry Hastingsc2047262014-01-25 20:43:29 -08002815dict___contains__(PyDictObject *self, PyObject *key)
Serhiy Storchaka19d25972017-02-04 08:05:07 +02002816/*[clinic end generated code: output=a3d03db709ed6e6b input=fe1cb42ad831e820]*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002817{
Larry Hastingsc2047262014-01-25 20:43:29 -08002818 register PyDictObject *mp = self;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002819 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002820 Py_ssize_t ix;
INADA Naokiba609772016-12-07 20:41:42 +09002821 PyObject *value;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002824 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 hash = PyObject_Hash(key);
2826 if (hash == -1)
2827 return NULL;
2828 }
INADA Naoki778928b2017-08-03 23:45:15 +09002829 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002830 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002832 if (ix == DKIX_EMPTY || value == NULL)
Victor Stinner742da042016-09-07 17:40:12 -07002833 Py_RETURN_FALSE;
2834 Py_RETURN_TRUE;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002835}
2836
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002837/*[clinic input]
2838dict.get
2839
2840 key: object
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002841 default: object = None
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002842 /
2843
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002844Return the value for key if key is in the dictionary, else default.
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002845[clinic start generated code]*/
2846
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002847static PyObject *
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002848dict_get_impl(PyDictObject *self, PyObject *key, PyObject *default_value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002849/*[clinic end generated code: output=bba707729dee05bf input=279ddb5790b6b107]*/
Barry Warsawc38c5da1997-10-06 17:49:20 +00002850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002852 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002853 Py_ssize_t ix;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002856 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 hash = PyObject_Hash(key);
2858 if (hash == -1)
2859 return NULL;
2860 }
INADA Naoki778928b2017-08-03 23:45:15 +09002861 ix = (self->ma_keys->dk_lookup) (self, key, hash, &val);
Victor Stinner742da042016-09-07 17:40:12 -07002862 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002864 if (ix == DKIX_EMPTY || val == NULL) {
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002865 val = default_value;
INADA Naokiba609772016-12-07 20:41:42 +09002866 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 Py_INCREF(val);
2868 return val;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002869}
2870
Benjamin Peterson00e98862013-03-07 22:16:29 -05002871PyObject *
2872PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
Guido van Rossum164452c2000-08-08 16:12:54 +00002873{
Benjamin Peterson00e98862013-03-07 22:16:29 -05002874 PyDictObject *mp = (PyDictObject *)d;
INADA Naoki93f26f72016-11-02 18:45:16 +09002875 PyObject *value;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002876 Py_hash_t hash;
Guido van Rossum164452c2000-08-08 16:12:54 +00002877
Benjamin Peterson00e98862013-03-07 22:16:29 -05002878 if (!PyDict_Check(d)) {
2879 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 return NULL;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002881 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002884 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 hash = PyObject_Hash(key);
2886 if (hash == -1)
2887 return NULL;
2888 }
Inada Naoki2ddc7f62019-03-18 20:38:33 +09002889 if (mp->ma_keys == Py_EMPTY_KEYS) {
2890 if (insert_to_emptydict(mp, key, hash, defaultobj) < 0) {
2891 return NULL;
2892 }
2893 return defaultobj;
2894 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002895
2896 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
2897 if (insertion_resize(mp) < 0)
2898 return NULL;
2899 }
2900
INADA Naoki778928b2017-08-03 23:45:15 +09002901 Py_ssize_t ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002902 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 return NULL;
INADA Naoki93f26f72016-11-02 18:45:16 +09002904
2905 if (_PyDict_HasSplitTable(mp) &&
INADA Naokiba609772016-12-07 20:41:42 +09002906 ((ix >= 0 && value == NULL && mp->ma_used != ix) ||
INADA Naoki93f26f72016-11-02 18:45:16 +09002907 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
2908 if (insertion_resize(mp) < 0) {
2909 return NULL;
2910 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002911 ix = DKIX_EMPTY;
2912 }
2913
2914 if (ix == DKIX_EMPTY) {
2915 PyDictKeyEntry *ep, *ep0;
2916 value = defaultobj;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002917 if (mp->ma_keys->dk_usable <= 0) {
Victor Stinner3c336c52016-09-12 14:17:40 +02002918 if (insertion_resize(mp) < 0) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002919 return NULL;
Victor Stinner3c336c52016-09-12 14:17:40 +02002920 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002921 }
INADA Naoki778928b2017-08-03 23:45:15 +09002922 Py_ssize_t hashpos = find_empty_slot(mp->ma_keys, hash);
INADA Naoki93f26f72016-11-02 18:45:16 +09002923 ep0 = DK_ENTRIES(mp->ma_keys);
2924 ep = &ep0[mp->ma_keys->dk_nentries];
INADA Naokia7576492018-11-14 18:39:27 +09002925 dictkeys_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
Benjamin Petersonb1efa532013-03-04 09:47:50 -05002926 Py_INCREF(key);
INADA Naoki93f26f72016-11-02 18:45:16 +09002927 Py_INCREF(value);
2928 MAINTAIN_TRACKING(mp, key, value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002929 ep->me_key = key;
2930 ep->me_hash = hash;
INADA Naokiba609772016-12-07 20:41:42 +09002931 if (_PyDict_HasSplitTable(mp)) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002932 assert(mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
2933 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Victor Stinner742da042016-09-07 17:40:12 -07002934 }
2935 else {
INADA Naoki93f26f72016-11-02 18:45:16 +09002936 ep->me_value = value;
Victor Stinner742da042016-09-07 17:40:12 -07002937 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002938 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07002939 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naoki93f26f72016-11-02 18:45:16 +09002940 mp->ma_keys->dk_usable--;
2941 mp->ma_keys->dk_nentries++;
2942 assert(mp->ma_keys->dk_usable >= 0);
2943 }
INADA Naokiba609772016-12-07 20:41:42 +09002944 else if (value == NULL) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002945 value = defaultobj;
2946 assert(_PyDict_HasSplitTable(mp));
2947 assert(ix == mp->ma_used);
2948 Py_INCREF(value);
2949 MAINTAIN_TRACKING(mp, key, value);
INADA Naokiba609772016-12-07 20:41:42 +09002950 mp->ma_values[ix] = value;
INADA Naoki93f26f72016-11-02 18:45:16 +09002951 mp->ma_used++;
2952 mp->ma_version_tag = DICT_NEXT_VERSION();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002954
Victor Stinner0fc91ee2019-04-12 21:51:34 +02002955 ASSERT_CONSISTENT(mp);
INADA Naoki93f26f72016-11-02 18:45:16 +09002956 return value;
Guido van Rossum164452c2000-08-08 16:12:54 +00002957}
2958
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002959/*[clinic input]
2960dict.setdefault
2961
2962 key: object
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002963 default: object = None
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002964 /
2965
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002966Insert key with a value of default if key is not in the dictionary.
2967
2968Return the value for key if key is in the dictionary, else default.
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002969[clinic start generated code]*/
2970
Benjamin Peterson00e98862013-03-07 22:16:29 -05002971static PyObject *
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002972dict_setdefault_impl(PyDictObject *self, PyObject *key,
2973 PyObject *default_value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002974/*[clinic end generated code: output=f8c1101ebf69e220 input=0f063756e815fd9d]*/
Benjamin Peterson00e98862013-03-07 22:16:29 -05002975{
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002976 PyObject *val;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002977
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002978 val = PyDict_SetDefault((PyObject *)self, key, default_value);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002979 Py_XINCREF(val);
2980 return val;
2981}
Guido van Rossum164452c2000-08-08 16:12:54 +00002982
2983static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302984dict_clear(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 PyDict_Clear((PyObject *)mp);
2987 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002988}
2989
Inada Naoki9e4f2f32019-04-12 16:11:28 +09002990/*[clinic input]
2991dict.pop
2992
2993 key: object
2994 default: object = NULL
2995 /
2996
2997Remove specified key and return the corresponding value.
2998
2999If key is not found, default is returned if given, otherwise KeyError is raised
3000[clinic start generated code]*/
3001
Guido van Rossumba6ab842000-12-12 22:02:18 +00003002static PyObject *
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003003dict_pop_impl(PyDictObject *self, PyObject *key, PyObject *default_value)
3004/*[clinic end generated code: output=3abb47b89f24c21c input=016f6a000e4e633b]*/
Guido van Rossume027d982002-04-12 15:11:59 +00003005{
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003006 return _PyDict_Pop((PyObject*)self, key, default_value);
Guido van Rossume027d982002-04-12 15:11:59 +00003007}
3008
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003009/*[clinic input]
3010dict.popitem
3011
3012Remove and return a (key, value) pair as a 2-tuple.
3013
3014Pairs are returned in LIFO (last-in, first-out) order.
3015Raises KeyError if the dict is empty.
3016[clinic start generated code]*/
3017
Guido van Rossume027d982002-04-12 15:11:59 +00003018static PyObject *
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003019dict_popitem_impl(PyDictObject *self)
3020/*[clinic end generated code: output=e65fcb04420d230d input=1c38a49f21f64941]*/
Guido van Rossumba6ab842000-12-12 22:02:18 +00003021{
Victor Stinner742da042016-09-07 17:40:12 -07003022 Py_ssize_t i, j;
3023 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 PyObject *res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00003025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 /* Allocate the result tuple before checking the size. Believe it
3027 * or not, this allocation could trigger a garbage collection which
3028 * could empty the dict, so if we checked the size first and that
3029 * happened, the result would be an infinite loop (searching for an
3030 * entry that no longer exists). Note that the usual popitem()
3031 * idiom is "while d: k, v = d.popitem()". so needing to throw the
3032 * tuple away if the dict *is* empty isn't a significant
3033 * inefficiency -- possible, but unlikely in practice.
3034 */
3035 res = PyTuple_New(2);
3036 if (res == NULL)
3037 return NULL;
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003038 if (self->ma_used == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 Py_DECREF(res);
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003040 PyErr_SetString(PyExc_KeyError, "popitem(): dictionary is empty");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 return NULL;
3042 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003043 /* Convert split table to combined table */
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003044 if (self->ma_keys->dk_lookup == lookdict_split) {
3045 if (dictresize(self, DK_SIZE(self->ma_keys))) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003046 Py_DECREF(res);
3047 return NULL;
3048 }
3049 }
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003050 ENSURE_ALLOWS_DELETIONS(self);
Victor Stinner742da042016-09-07 17:40:12 -07003051
3052 /* Pop last item */
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003053 ep0 = DK_ENTRIES(self->ma_keys);
3054 i = self->ma_keys->dk_nentries - 1;
Victor Stinner742da042016-09-07 17:40:12 -07003055 while (i >= 0 && ep0[i].me_value == NULL) {
3056 i--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 }
Victor Stinner742da042016-09-07 17:40:12 -07003058 assert(i >= 0);
3059
3060 ep = &ep0[i];
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003061 j = lookdict_index(self->ma_keys, ep->me_hash, i);
Victor Stinner742da042016-09-07 17:40:12 -07003062 assert(j >= 0);
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003063 assert(dictkeys_get_index(self->ma_keys, j) == i);
3064 dictkeys_set_index(self->ma_keys, j, DKIX_DUMMY);
Victor Stinner742da042016-09-07 17:40:12 -07003065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 PyTuple_SET_ITEM(res, 0, ep->me_key);
3067 PyTuple_SET_ITEM(res, 1, ep->me_value);
Victor Stinner742da042016-09-07 17:40:12 -07003068 ep->me_key = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 ep->me_value = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07003070 /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003071 self->ma_keys->dk_nentries = i;
3072 self->ma_used--;
3073 self->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner0fc91ee2019-04-12 21:51:34 +02003074 ASSERT_CONSISTENT(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 return res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00003076}
3077
Jeremy Hylton8caad492000-06-23 14:18:11 +00003078static int
3079dict_traverse(PyObject *op, visitproc visit, void *arg)
3080{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003081 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson55f44522016-09-05 12:12:59 -07003082 PyDictKeysObject *keys = mp->ma_keys;
Serhiy Storchaka46825d22016-09-26 21:29:34 +03003083 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Victor Stinner742da042016-09-07 17:40:12 -07003084 Py_ssize_t i, n = keys->dk_nentries;
3085
Benjamin Peterson55f44522016-09-05 12:12:59 -07003086 if (keys->dk_lookup == lookdict) {
3087 for (i = 0; i < n; i++) {
3088 if (entries[i].me_value != NULL) {
3089 Py_VISIT(entries[i].me_value);
3090 Py_VISIT(entries[i].me_key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003091 }
3092 }
Victor Stinner742da042016-09-07 17:40:12 -07003093 }
3094 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003095 if (mp->ma_values != NULL) {
Benjamin Peterson55f44522016-09-05 12:12:59 -07003096 for (i = 0; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003097 Py_VISIT(mp->ma_values[i]);
3098 }
3099 }
3100 else {
Benjamin Peterson55f44522016-09-05 12:12:59 -07003101 for (i = 0; i < n; i++) {
3102 Py_VISIT(entries[i].me_value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003103 }
3104 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 }
3106 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00003107}
3108
3109static int
3110dict_tp_clear(PyObject *op)
3111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 PyDict_Clear(op);
3113 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00003114}
3115
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003116static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003117
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003118Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003119_PyDict_SizeOf(PyDictObject *mp)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003120{
Victor Stinner742da042016-09-07 17:40:12 -07003121 Py_ssize_t size, usable, res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003122
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003123 size = DK_SIZE(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07003124 usable = USABLE_FRACTION(size);
3125
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02003126 res = _PyObject_SIZE(Py_TYPE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003127 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07003128 res += usable * sizeof(PyObject*);
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003129 /* If the dictionary is split, the keys portion is accounted-for
3130 in the type object. */
3131 if (mp->ma_keys->dk_refcnt == 1)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003132 res += (sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003133 + DK_IXSIZE(mp->ma_keys) * size
3134 + sizeof(PyDictKeyEntry) * usable);
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003135 return res;
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003136}
3137
3138Py_ssize_t
3139_PyDict_KeysSize(PyDictKeysObject *keys)
3140{
Victor Stinner98ee9d52016-09-08 09:33:56 -07003141 return (sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003142 + DK_IXSIZE(keys) * DK_SIZE(keys)
3143 + USABLE_FRACTION(DK_SIZE(keys)) * sizeof(PyDictKeyEntry));
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003144}
3145
doko@ubuntu.com17210f52016-01-14 14:04:59 +01003146static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303147dict_sizeof(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003148{
3149 return PyLong_FromSsize_t(_PyDict_SizeOf(mp));
3150}
3151
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003152PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
3153
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003154PyDoc_STRVAR(sizeof__doc__,
3155"D.__sizeof__() -> size of D in memory, in bytes");
3156
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003157PyDoc_STRVAR(update__doc__,
Brett Cannonf2754162013-05-11 14:46:48 -04003158"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n\
3159If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]\n\
3160If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n\
3161In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00003162
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003163PyDoc_STRVAR(clear__doc__,
3164"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00003165
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003166PyDoc_STRVAR(copy__doc__,
3167"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00003168
Guido van Rossumb90c8482007-02-10 01:11:45 +00003169/* Forward */
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303170static PyObject *dictkeys_new(PyObject *, PyObject *);
3171static PyObject *dictitems_new(PyObject *, PyObject *);
3172static PyObject *dictvalues_new(PyObject *, PyObject *);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003173
Guido van Rossum45c85d12007-07-27 16:31:40 +00003174PyDoc_STRVAR(keys__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 "D.keys() -> a set-like object providing a view on D's keys");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003176PyDoc_STRVAR(items__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 "D.items() -> a set-like object providing a view on D's items");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003178PyDoc_STRVAR(values__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 "D.values() -> an object providing a view on D's values");
Guido van Rossumb90c8482007-02-10 01:11:45 +00003180
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003181static PyMethodDef mapp_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -07003182 DICT___CONTAINS___METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003183 {"__getitem__", (PyCFunction)(void(*)(void))dict_subscript, METH_O | METH_COEXIST,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 getitem__doc__},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003185 {"__sizeof__", (PyCFunction)(void(*)(void))dict_sizeof, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 sizeof__doc__},
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01003187 DICT_GET_METHODDEF
3188 DICT_SETDEFAULT_METHODDEF
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003189 DICT_POP_METHODDEF
3190 DICT_POPITEM_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303191 {"keys", dictkeys_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 keys__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303193 {"items", dictitems_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 items__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303195 {"values", dictvalues_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 values__doc__},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003197 {"update", (PyCFunction)(void(*)(void))dict_update, METH_VARARGS | METH_KEYWORDS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 update__doc__},
Larry Hastings5c661892014-01-24 06:17:25 -08003199 DICT_FROMKEYS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
3201 clear__doc__},
3202 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
3203 copy__doc__},
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003204 DICT___REVERSED___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003206};
3207
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00003208/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00003209int
3210PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003211{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003212 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07003213 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09003215 PyObject *value;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003218 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 hash = PyObject_Hash(key);
3220 if (hash == -1)
3221 return -1;
3222 }
INADA Naoki778928b2017-08-03 23:45:15 +09003223 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07003224 if (ix == DKIX_ERROR)
3225 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09003226 return (ix != DKIX_EMPTY && value != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003227}
3228
Thomas Wouterscf297e42007-02-23 15:07:44 +00003229/* Internal version of PyDict_Contains used when the hash value is already known */
3230int
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003231_PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00003232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09003234 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -07003235 Py_ssize_t ix;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003236
INADA Naoki778928b2017-08-03 23:45:15 +09003237 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07003238 if (ix == DKIX_ERROR)
3239 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09003240 return (ix != DKIX_EMPTY && value != NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00003241}
3242
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003243/* Hack to implement "key in dict" */
3244static PySequenceMethods dict_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 0, /* sq_length */
3246 0, /* sq_concat */
3247 0, /* sq_repeat */
3248 0, /* sq_item */
3249 0, /* sq_slice */
3250 0, /* sq_ass_item */
3251 0, /* sq_ass_slice */
3252 PyDict_Contains, /* sq_contains */
3253 0, /* sq_inplace_concat */
3254 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003255};
3256
Guido van Rossum09e563a2001-05-01 12:10:21 +00003257static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003258dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003260 PyObject *self;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003261 PyDictObject *d;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 assert(type != NULL && type->tp_alloc != NULL);
3264 self = type->tp_alloc(type, 0);
Victor Stinnera9f61a52013-07-16 22:17:26 +02003265 if (self == NULL)
3266 return NULL;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003267 d = (PyDictObject *)self;
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003268
Victor Stinnera9f61a52013-07-16 22:17:26 +02003269 /* The object has been implicitly tracked by tp_alloc */
3270 if (type == &PyDict_Type)
3271 _PyObject_GC_UNTRACK(d);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003272
3273 d->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07003274 d->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07003275 d->ma_keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003276 if (d->ma_keys == NULL) {
3277 Py_DECREF(self);
3278 return NULL;
3279 }
Victor Stinner0fc91ee2019-04-12 21:51:34 +02003280 ASSERT_CONSISTENT(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 return self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003282}
3283
Tim Peters25786c02001-09-02 08:22:48 +00003284static int
3285dict_init(PyObject *self, PyObject *args, PyObject *kwds)
3286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00003288}
3289
Tim Peters6d6c1a32001-08-02 04:15:00 +00003290static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003291dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00003292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003293 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003294}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003295
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003296PyDoc_STRVAR(dictionary_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00003297"dict() -> new empty dictionary\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00003298"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003299" (key, value) pairs\n"
3300"dict(iterable) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00003301" d = {}\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003302" for k, v in iterable:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00003303" d[k] = v\n"
3304"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
3305" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00003306
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003307PyTypeObject PyDict_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3309 "dict",
3310 sizeof(PyDictObject),
3311 0,
3312 (destructor)dict_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003313 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 0, /* tp_getattr */
3315 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003316 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 (reprfunc)dict_repr, /* tp_repr */
3318 0, /* tp_as_number */
3319 &dict_as_sequence, /* tp_as_sequence */
3320 &dict_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003321 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 0, /* tp_call */
3323 0, /* tp_str */
3324 PyObject_GenericGetAttr, /* tp_getattro */
3325 0, /* tp_setattro */
3326 0, /* tp_as_buffer */
3327 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3328 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
3329 dictionary_doc, /* tp_doc */
3330 dict_traverse, /* tp_traverse */
3331 dict_tp_clear, /* tp_clear */
3332 dict_richcompare, /* tp_richcompare */
3333 0, /* tp_weaklistoffset */
3334 (getiterfunc)dict_iter, /* tp_iter */
3335 0, /* tp_iternext */
3336 mapp_methods, /* tp_methods */
3337 0, /* tp_members */
3338 0, /* tp_getset */
3339 0, /* tp_base */
3340 0, /* tp_dict */
3341 0, /* tp_descr_get */
3342 0, /* tp_descr_set */
3343 0, /* tp_dictoffset */
3344 dict_init, /* tp_init */
3345 PyType_GenericAlloc, /* tp_alloc */
3346 dict_new, /* tp_new */
3347 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003348};
3349
Victor Stinner3c1e4812012-03-26 22:10:51 +02003350PyObject *
3351_PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
3352{
3353 PyObject *kv;
3354 kv = _PyUnicode_FromId(key); /* borrowed */
Victor Stinner5b3b1002013-07-22 23:50:57 +02003355 if (kv == NULL) {
3356 PyErr_Clear();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003357 return NULL;
Victor Stinner5b3b1002013-07-22 23:50:57 +02003358 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003359 return PyDict_GetItem(dp, kv);
3360}
3361
Guido van Rossum3cca2451997-05-16 14:23:33 +00003362/* For backward compatibility with old dictionary interface */
3363
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003364PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003365PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 PyObject *kv, *rv;
3368 kv = PyUnicode_FromString(key);
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003369 if (kv == NULL) {
3370 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 return NULL;
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003372 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 rv = PyDict_GetItem(v, kv);
3374 Py_DECREF(kv);
3375 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003376}
3377
3378int
Victor Stinner3c1e4812012-03-26 22:10:51 +02003379_PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
3380{
3381 PyObject *kv;
3382 kv = _PyUnicode_FromId(key); /* borrowed */
3383 if (kv == NULL)
3384 return -1;
3385 return PyDict_SetItem(v, kv, item);
3386}
3387
3388int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003389PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 PyObject *kv;
3392 int err;
3393 kv = PyUnicode_FromString(key);
3394 if (kv == NULL)
3395 return -1;
3396 PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
3397 err = PyDict_SetItem(v, kv, item);
3398 Py_DECREF(kv);
3399 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003400}
3401
3402int
Victor Stinner5fd2e5a2013-11-06 18:58:22 +01003403_PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
3404{
3405 PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
3406 if (kv == NULL)
3407 return -1;
3408 return PyDict_DelItem(v, kv);
3409}
3410
3411int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003412PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 PyObject *kv;
3415 int err;
3416 kv = PyUnicode_FromString(key);
3417 if (kv == NULL)
3418 return -1;
3419 err = PyDict_DelItem(v, kv);
3420 Py_DECREF(kv);
3421 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003422}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003423
Raymond Hettinger019a1482004-03-18 02:41:19 +00003424/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003425
3426typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 PyObject_HEAD
3428 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
3429 Py_ssize_t di_used;
3430 Py_ssize_t di_pos;
3431 PyObject* di_result; /* reusable result tuple for iteritems */
3432 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003433} dictiterobject;
3434
3435static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003436dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 dictiterobject *di;
3439 di = PyObject_GC_New(dictiterobject, itertype);
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003440 if (di == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 return NULL;
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003442 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 Py_INCREF(dict);
3444 di->di_dict = dict;
3445 di->di_used = dict->ma_used;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 di->len = dict->ma_used;
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003447 if ((itertype == &PyDictRevIterKey_Type ||
3448 itertype == &PyDictRevIterItem_Type ||
3449 itertype == &PyDictRevIterValue_Type) && dict->ma_used) {
3450 di->di_pos = dict->ma_keys->dk_nentries - 1;
3451 }
3452 else {
3453 di->di_pos = 0;
3454 }
3455 if (itertype == &PyDictIterItem_Type ||
3456 itertype == &PyDictRevIterItem_Type) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
3458 if (di->di_result == NULL) {
3459 Py_DECREF(di);
3460 return NULL;
3461 }
3462 }
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003463 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 di->di_result = NULL;
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003465 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 _PyObject_GC_TRACK(di);
3467 return (PyObject *)di;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003468}
3469
3470static void
3471dictiter_dealloc(dictiterobject *di)
3472{
INADA Naokia6296d32017-08-24 14:55:17 +09003473 /* bpo-31095: UnTrack is needed before calling any callbacks */
3474 _PyObject_GC_UNTRACK(di);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003475 Py_XDECREF(di->di_dict);
3476 Py_XDECREF(di->di_result);
3477 PyObject_GC_Del(di);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003478}
3479
3480static int
3481dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
3482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 Py_VISIT(di->di_dict);
3484 Py_VISIT(di->di_result);
3485 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003486}
3487
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003488static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303489dictiter_len(dictiterobject *di, PyObject *Py_UNUSED(ignored))
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 Py_ssize_t len = 0;
3492 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
3493 len = di->len;
3494 return PyLong_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003495}
3496
Guido van Rossumb90c8482007-02-10 01:11:45 +00003497PyDoc_STRVAR(length_hint_doc,
3498 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003499
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003500static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303501dictiter_reduce(dictiterobject *di, PyObject *Py_UNUSED(ignored));
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003502
3503PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3504
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003505static PyMethodDef dictiter_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003506 {"__length_hint__", (PyCFunction)(void(*)(void))dictiter_len, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 length_hint_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003508 {"__reduce__", (PyCFunction)(void(*)(void))dictiter_reduce, METH_NOARGS,
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003509 reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003511};
3512
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003513static PyObject*
3514dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00003515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 PyObject *key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003517 Py_ssize_t i;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003518 PyDictKeysObject *k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 PyDictObject *d = di->di_dict;
Guido van Rossum213c7a62001-04-23 14:08:49 +00003520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 if (d == NULL)
3522 return NULL;
3523 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00003524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 if (di->di_used != d->ma_used) {
3526 PyErr_SetString(PyExc_RuntimeError,
3527 "dictionary changed size during iteration");
3528 di->di_used = -1; /* Make this state sticky */
3529 return NULL;
3530 }
Guido van Rossum2147df72002-07-16 20:30:22 +00003531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 i = di->di_pos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003533 k = d->ma_keys;
INADA Naokica2d8be2016-11-04 16:59:10 +09003534 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003535 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003536 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003537 goto fail;
3538 key = DK_ENTRIES(k)[i].me_key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003539 assert(d->ma_values[i] != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003540 }
3541 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003542 Py_ssize_t n = k->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003543 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
3544 while (i < n && entry_ptr->me_value == NULL) {
3545 entry_ptr++;
3546 i++;
3547 }
3548 if (i >= n)
3549 goto fail;
3550 key = entry_ptr->me_key;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003551 }
Thomas Perl796cc6e2019-03-28 07:03:25 +01003552 // We found an element (key), but did not expect it
3553 if (di->len == 0) {
3554 PyErr_SetString(PyExc_RuntimeError,
3555 "dictionary keys changed during iteration");
3556 goto fail;
3557 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 di->di_pos = i+1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 di->len--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 Py_INCREF(key);
3561 return key;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003562
3563fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003565 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003567}
3568
Raymond Hettinger019a1482004-03-18 02:41:19 +00003569PyTypeObject PyDictIterKey_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3571 "dict_keyiterator", /* tp_name */
3572 sizeof(dictiterobject), /* tp_basicsize */
3573 0, /* tp_itemsize */
3574 /* methods */
3575 (destructor)dictiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003576 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 0, /* tp_getattr */
3578 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003579 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 0, /* tp_repr */
3581 0, /* tp_as_number */
3582 0, /* tp_as_sequence */
3583 0, /* tp_as_mapping */
3584 0, /* tp_hash */
3585 0, /* tp_call */
3586 0, /* tp_str */
3587 PyObject_GenericGetAttr, /* tp_getattro */
3588 0, /* tp_setattro */
3589 0, /* tp_as_buffer */
3590 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3591 0, /* tp_doc */
3592 (traverseproc)dictiter_traverse, /* tp_traverse */
3593 0, /* tp_clear */
3594 0, /* tp_richcompare */
3595 0, /* tp_weaklistoffset */
3596 PyObject_SelfIter, /* tp_iter */
3597 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
3598 dictiter_methods, /* tp_methods */
3599 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003600};
3601
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003602static PyObject *
3603dictiter_iternextvalue(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 PyObject *value;
INADA Naokica2d8be2016-11-04 16:59:10 +09003606 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 if (d == NULL)
3610 return NULL;
3611 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 if (di->di_used != d->ma_used) {
3614 PyErr_SetString(PyExc_RuntimeError,
3615 "dictionary changed size during iteration");
3616 di->di_used = -1; /* Make this state sticky */
3617 return NULL;
3618 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 i = di->di_pos;
INADA Naokica2d8be2016-11-04 16:59:10 +09003621 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003622 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003623 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003624 goto fail;
INADA Naokica2d8be2016-11-04 16:59:10 +09003625 value = d->ma_values[i];
3626 assert(value != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003627 }
3628 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003629 Py_ssize_t n = d->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003630 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3631 while (i < n && entry_ptr->me_value == NULL) {
3632 entry_ptr++;
3633 i++;
3634 }
3635 if (i >= n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003636 goto fail;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003637 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003638 }
Thomas Perlb8311cf2019-04-02 11:30:10 +02003639 // We found an element, but did not expect it
3640 if (di->len == 0) {
3641 PyErr_SetString(PyExc_RuntimeError,
3642 "dictionary keys changed during iteration");
3643 goto fail;
3644 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 di->di_pos = i+1;
3646 di->len--;
3647 Py_INCREF(value);
3648 return value;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003649
3650fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003652 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003654}
3655
3656PyTypeObject PyDictIterValue_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3658 "dict_valueiterator", /* tp_name */
3659 sizeof(dictiterobject), /* tp_basicsize */
3660 0, /* tp_itemsize */
3661 /* methods */
3662 (destructor)dictiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003663 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 0, /* tp_getattr */
3665 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003666 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 0, /* tp_repr */
3668 0, /* tp_as_number */
3669 0, /* tp_as_sequence */
3670 0, /* tp_as_mapping */
3671 0, /* tp_hash */
3672 0, /* tp_call */
3673 0, /* tp_str */
3674 PyObject_GenericGetAttr, /* tp_getattro */
3675 0, /* tp_setattro */
3676 0, /* tp_as_buffer */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003677 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 0, /* tp_doc */
3679 (traverseproc)dictiter_traverse, /* tp_traverse */
3680 0, /* tp_clear */
3681 0, /* tp_richcompare */
3682 0, /* tp_weaklistoffset */
3683 PyObject_SelfIter, /* tp_iter */
3684 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
3685 dictiter_methods, /* tp_methods */
3686 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003687};
3688
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003689static PyObject *
3690dictiter_iternextitem(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003691{
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003692 PyObject *key, *value, *result;
INADA Naokica2d8be2016-11-04 16:59:10 +09003693 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003694 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003696 if (d == NULL)
3697 return NULL;
3698 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 if (di->di_used != d->ma_used) {
3701 PyErr_SetString(PyExc_RuntimeError,
3702 "dictionary changed size during iteration");
3703 di->di_used = -1; /* Make this state sticky */
3704 return NULL;
3705 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003707 i = di->di_pos;
INADA Naokica2d8be2016-11-04 16:59:10 +09003708 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003709 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003710 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003711 goto fail;
3712 key = DK_ENTRIES(d->ma_keys)[i].me_key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003713 value = d->ma_values[i];
3714 assert(value != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003715 }
3716 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003717 Py_ssize_t n = d->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003718 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3719 while (i < n && entry_ptr->me_value == NULL) {
3720 entry_ptr++;
3721 i++;
3722 }
3723 if (i >= n)
3724 goto fail;
3725 key = entry_ptr->me_key;
3726 value = entry_ptr->me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003727 }
Thomas Perlb8311cf2019-04-02 11:30:10 +02003728 // We found an element, but did not expect it
3729 if (di->len == 0) {
3730 PyErr_SetString(PyExc_RuntimeError,
3731 "dictionary keys changed during iteration");
3732 goto fail;
3733 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 di->di_pos = i+1;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003735 di->len--;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003736 Py_INCREF(key);
3737 Py_INCREF(value);
3738 result = di->di_result;
3739 if (Py_REFCNT(result) == 1) {
3740 PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
3741 PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
3742 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3743 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003744 Py_INCREF(result);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003745 Py_DECREF(oldkey);
3746 Py_DECREF(oldvalue);
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003747 }
3748 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 result = PyTuple_New(2);
3750 if (result == NULL)
3751 return NULL;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003752 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3753 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003756
3757fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003759 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003761}
3762
3763PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3765 "dict_itemiterator", /* tp_name */
3766 sizeof(dictiterobject), /* tp_basicsize */
3767 0, /* tp_itemsize */
3768 /* methods */
3769 (destructor)dictiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003770 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 0, /* tp_getattr */
3772 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003773 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003774 0, /* tp_repr */
3775 0, /* tp_as_number */
3776 0, /* tp_as_sequence */
3777 0, /* tp_as_mapping */
3778 0, /* tp_hash */
3779 0, /* tp_call */
3780 0, /* tp_str */
3781 PyObject_GenericGetAttr, /* tp_getattro */
3782 0, /* tp_setattro */
3783 0, /* tp_as_buffer */
3784 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3785 0, /* tp_doc */
3786 (traverseproc)dictiter_traverse, /* tp_traverse */
3787 0, /* tp_clear */
3788 0, /* tp_richcompare */
3789 0, /* tp_weaklistoffset */
3790 PyObject_SelfIter, /* tp_iter */
3791 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
3792 dictiter_methods, /* tp_methods */
3793 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003794};
Guido van Rossumb90c8482007-02-10 01:11:45 +00003795
3796
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003797/* dictreviter */
3798
3799static PyObject *
3800dictreviter_iternext(dictiterobject *di)
3801{
3802 PyDictObject *d = di->di_dict;
3803
3804 if (d == NULL) {
3805 return NULL;
3806 }
3807 assert (PyDict_Check(d));
3808
3809 if (di->di_used != d->ma_used) {
3810 PyErr_SetString(PyExc_RuntimeError,
3811 "dictionary changed size during iteration");
3812 di->di_used = -1; /* Make this state sticky */
3813 return NULL;
3814 }
3815
3816 Py_ssize_t i = di->di_pos;
3817 PyDictKeysObject *k = d->ma_keys;
3818 PyObject *key, *value, *result;
3819
3820 if (d->ma_values) {
3821 if (i < 0) {
3822 goto fail;
3823 }
3824 key = DK_ENTRIES(k)[i].me_key;
3825 value = d->ma_values[i];
3826 assert (value != NULL);
3827 }
3828 else {
3829 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
3830 while (i >= 0 && entry_ptr->me_value == NULL) {
3831 entry_ptr--;
3832 i--;
3833 }
3834 if (i < 0) {
3835 goto fail;
3836 }
3837 key = entry_ptr->me_key;
3838 value = entry_ptr->me_value;
3839 }
3840 di->di_pos = i-1;
3841 di->len--;
3842
3843 if (Py_TYPE(di) == &PyDictRevIterKey_Type) {
3844 Py_INCREF(key);
3845 return key;
3846 }
3847 else if (Py_TYPE(di) == &PyDictRevIterValue_Type) {
3848 Py_INCREF(value);
3849 return value;
3850 }
3851 else if (Py_TYPE(di) == &PyDictRevIterItem_Type) {
3852 Py_INCREF(key);
3853 Py_INCREF(value);
3854 result = di->di_result;
3855 if (Py_REFCNT(result) == 1) {
3856 PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
3857 PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
3858 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3859 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
3860 Py_INCREF(result);
3861 Py_DECREF(oldkey);
3862 Py_DECREF(oldvalue);
3863 }
3864 else {
3865 result = PyTuple_New(2);
3866 if (result == NULL) {
3867 return NULL;
3868 }
3869 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3870 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
3871 }
3872 return result;
3873 }
3874 else {
3875 Py_UNREACHABLE();
3876 }
3877
3878fail:
3879 di->di_dict = NULL;
3880 Py_DECREF(d);
3881 return NULL;
3882}
3883
3884PyTypeObject PyDictRevIterKey_Type = {
3885 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3886 "dict_reversekeyiterator",
3887 sizeof(dictiterobject),
3888 .tp_dealloc = (destructor)dictiter_dealloc,
3889 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3890 .tp_traverse = (traverseproc)dictiter_traverse,
3891 .tp_iter = PyObject_SelfIter,
3892 .tp_iternext = (iternextfunc)dictreviter_iternext,
3893 .tp_methods = dictiter_methods
3894};
3895
3896
3897/*[clinic input]
3898dict.__reversed__
3899
3900Return a reverse iterator over the dict keys.
3901[clinic start generated code]*/
3902
3903static PyObject *
3904dict___reversed___impl(PyDictObject *self)
3905/*[clinic end generated code: output=e674483336d1ed51 input=23210ef3477d8c4d]*/
3906{
3907 assert (PyDict_Check(self));
3908 return dictiter_new(self, &PyDictRevIterKey_Type);
3909}
3910
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003911static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303912dictiter_reduce(dictiterobject *di, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003913{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003914 _Py_IDENTIFIER(iter);
Sergey Fedoseev63958442018-10-20 05:43:33 +05003915 /* copy the iterator state */
3916 dictiterobject tmp = *di;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003917 Py_XINCREF(tmp.di_dict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003918
Sergey Fedoseev63958442018-10-20 05:43:33 +05003919 PyObject *list = PySequence_List((PyObject*)&tmp);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003920 Py_XDECREF(tmp.di_dict);
Sergey Fedoseev63958442018-10-20 05:43:33 +05003921 if (list == NULL) {
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003922 return NULL;
3923 }
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003924 return Py_BuildValue("N(N)", _PyEval_GetBuiltinId(&PyId_iter), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003925}
3926
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003927PyTypeObject PyDictRevIterItem_Type = {
3928 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3929 "dict_reverseitemiterator",
3930 sizeof(dictiterobject),
3931 .tp_dealloc = (destructor)dictiter_dealloc,
3932 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3933 .tp_traverse = (traverseproc)dictiter_traverse,
3934 .tp_iter = PyObject_SelfIter,
3935 .tp_iternext = (iternextfunc)dictreviter_iternext,
3936 .tp_methods = dictiter_methods
3937};
3938
3939PyTypeObject PyDictRevIterValue_Type = {
3940 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3941 "dict_reversevalueiterator",
3942 sizeof(dictiterobject),
3943 .tp_dealloc = (destructor)dictiter_dealloc,
3944 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3945 .tp_traverse = (traverseproc)dictiter_traverse,
3946 .tp_iter = PyObject_SelfIter,
3947 .tp_iternext = (iternextfunc)dictreviter_iternext,
3948 .tp_methods = dictiter_methods
3949};
3950
Guido van Rossum3ac67412007-02-10 18:55:06 +00003951/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003952/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00003953/***********************************************/
3954
Guido van Rossumb90c8482007-02-10 01:11:45 +00003955/* The instance lay-out is the same for all three; but the type differs. */
3956
Guido van Rossumb90c8482007-02-10 01:11:45 +00003957static void
Eric Snow96c6af92015-05-29 22:21:39 -06003958dictview_dealloc(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003959{
INADA Naokia6296d32017-08-24 14:55:17 +09003960 /* bpo-31095: UnTrack is needed before calling any callbacks */
3961 _PyObject_GC_UNTRACK(dv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 Py_XDECREF(dv->dv_dict);
3963 PyObject_GC_Del(dv);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003964}
3965
3966static int
Eric Snow96c6af92015-05-29 22:21:39 -06003967dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 Py_VISIT(dv->dv_dict);
3970 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003971}
3972
Guido van Rossum83825ac2007-02-10 04:54:19 +00003973static Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003974dictview_len(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 Py_ssize_t len = 0;
3977 if (dv->dv_dict != NULL)
3978 len = dv->dv_dict->ma_used;
3979 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003980}
3981
Eric Snow96c6af92015-05-29 22:21:39 -06003982PyObject *
3983_PyDictView_New(PyObject *dict, PyTypeObject *type)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003984{
Eric Snow96c6af92015-05-29 22:21:39 -06003985 _PyDictViewObject *dv;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 if (dict == NULL) {
3987 PyErr_BadInternalCall();
3988 return NULL;
3989 }
3990 if (!PyDict_Check(dict)) {
3991 /* XXX Get rid of this restriction later */
3992 PyErr_Format(PyExc_TypeError,
3993 "%s() requires a dict argument, not '%s'",
3994 type->tp_name, dict->ob_type->tp_name);
3995 return NULL;
3996 }
Eric Snow96c6af92015-05-29 22:21:39 -06003997 dv = PyObject_GC_New(_PyDictViewObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003998 if (dv == NULL)
3999 return NULL;
4000 Py_INCREF(dict);
4001 dv->dv_dict = (PyDictObject *)dict;
4002 _PyObject_GC_TRACK(dv);
4003 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00004004}
4005
Neal Norwitze36f2ba2007-02-26 23:12:28 +00004006/* TODO(guido): The views objects are not complete:
4007
4008 * support more set operations
4009 * support arbitrary mappings?
4010 - either these should be static or exported in dictobject.h
4011 - if public then they should probably be in builtins
4012*/
4013
Guido van Rossumaac530c2007-08-24 22:33:45 +00004014/* Return 1 if self is a subset of other, iterating over self;
4015 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00004016static int
4017all_contained_in(PyObject *self, PyObject *other)
4018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 PyObject *iter = PyObject_GetIter(self);
4020 int ok = 1;
Guido van Rossumd9214d12007-02-12 02:23:40 +00004021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 if (iter == NULL)
4023 return -1;
4024 for (;;) {
4025 PyObject *next = PyIter_Next(iter);
4026 if (next == NULL) {
4027 if (PyErr_Occurred())
4028 ok = -1;
4029 break;
4030 }
4031 ok = PySequence_Contains(other, next);
4032 Py_DECREF(next);
4033 if (ok <= 0)
4034 break;
4035 }
4036 Py_DECREF(iter);
4037 return ok;
Guido van Rossumd9214d12007-02-12 02:23:40 +00004038}
4039
4040static PyObject *
4041dictview_richcompare(PyObject *self, PyObject *other, int op)
4042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004043 Py_ssize_t len_self, len_other;
4044 int ok;
4045 PyObject *result;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004047 assert(self != NULL);
4048 assert(PyDictViewSet_Check(self));
4049 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00004050
Brian Curtindfc80e32011-08-10 20:28:54 -05004051 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
4052 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004054 len_self = PyObject_Size(self);
4055 if (len_self < 0)
4056 return NULL;
4057 len_other = PyObject_Size(other);
4058 if (len_other < 0)
4059 return NULL;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 ok = 0;
4062 switch(op) {
Guido van Rossumaac530c2007-08-24 22:33:45 +00004063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004064 case Py_NE:
4065 case Py_EQ:
4066 if (len_self == len_other)
4067 ok = all_contained_in(self, other);
4068 if (op == Py_NE && ok >= 0)
4069 ok = !ok;
4070 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 case Py_LT:
4073 if (len_self < len_other)
4074 ok = all_contained_in(self, other);
4075 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004077 case Py_LE:
4078 if (len_self <= len_other)
4079 ok = all_contained_in(self, other);
4080 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 case Py_GT:
4083 if (len_self > len_other)
4084 ok = all_contained_in(other, self);
4085 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004087 case Py_GE:
4088 if (len_self >= len_other)
4089 ok = all_contained_in(other, self);
4090 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004092 }
4093 if (ok < 0)
4094 return NULL;
4095 result = ok ? Py_True : Py_False;
4096 Py_INCREF(result);
4097 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00004098}
4099
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00004100static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004101dictview_repr(_PyDictViewObject *dv)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00004102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 PyObject *seq;
bennorthd7773d92018-01-26 15:46:01 +00004104 PyObject *result = NULL;
4105 Py_ssize_t rc;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00004106
bennorthd7773d92018-01-26 15:46:01 +00004107 rc = Py_ReprEnter((PyObject *)dv);
4108 if (rc != 0) {
4109 return rc > 0 ? PyUnicode_FromString("...") : NULL;
4110 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 seq = PySequence_List((PyObject *)dv);
bennorthd7773d92018-01-26 15:46:01 +00004112 if (seq == NULL) {
4113 goto Done;
4114 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004115 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
4116 Py_DECREF(seq);
bennorthd7773d92018-01-26 15:46:01 +00004117
4118Done:
4119 Py_ReprLeave((PyObject *)dv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 return result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00004121}
4122
Guido van Rossum3ac67412007-02-10 18:55:06 +00004123/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004124
4125static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004126dictkeys_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 if (dv->dv_dict == NULL) {
4129 Py_RETURN_NONE;
4130 }
4131 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00004132}
4133
4134static int
Eric Snow96c6af92015-05-29 22:21:39 -06004135dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00004136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004137 if (dv->dv_dict == NULL)
4138 return 0;
4139 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004140}
4141
Guido van Rossum83825ac2007-02-10 04:54:19 +00004142static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 (lenfunc)dictview_len, /* sq_length */
4144 0, /* sq_concat */
4145 0, /* sq_repeat */
4146 0, /* sq_item */
4147 0, /* sq_slice */
4148 0, /* sq_ass_item */
4149 0, /* sq_ass_slice */
4150 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004151};
4152
Guido van Rossum523259b2007-08-24 23:41:22 +00004153static PyObject*
4154dictviews_sub(PyObject* self, PyObject *other)
4155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004156 PyObject *result = PySet_New(self);
4157 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004158 _Py_IDENTIFIER(difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004160 if (result == NULL)
4161 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004162
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08004163 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 if (tmp == NULL) {
4165 Py_DECREF(result);
4166 return NULL;
4167 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004169 Py_DECREF(tmp);
4170 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004171}
4172
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004173PyObject*
4174_PyDictView_Intersect(PyObject* self, PyObject *other)
Guido van Rossum523259b2007-08-24 23:41:22 +00004175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 PyObject *result = PySet_New(self);
4177 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004178 _Py_IDENTIFIER(intersection_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004180 if (result == NULL)
4181 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004182
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08004183 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_intersection_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184 if (tmp == NULL) {
4185 Py_DECREF(result);
4186 return NULL;
4187 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 Py_DECREF(tmp);
4190 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004191}
4192
4193static PyObject*
4194dictviews_or(PyObject* self, PyObject *other)
4195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004196 PyObject *result = PySet_New(self);
4197 PyObject *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02004198 _Py_IDENTIFIER(update);
Victor Stinnerd1a9cc22011-10-13 22:51:17 +02004199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004200 if (result == NULL)
4201 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004202
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08004203 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004204 if (tmp == NULL) {
4205 Py_DECREF(result);
4206 return NULL;
4207 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 Py_DECREF(tmp);
4210 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004211}
4212
4213static PyObject*
4214dictviews_xor(PyObject* self, PyObject *other)
4215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 PyObject *result = PySet_New(self);
4217 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004218 _Py_IDENTIFIER(symmetric_difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004220 if (result == NULL)
4221 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004222
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08004223 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_symmetric_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004224 if (tmp == NULL) {
4225 Py_DECREF(result);
4226 return NULL;
4227 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004229 Py_DECREF(tmp);
4230 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004231}
4232
4233static PyNumberMethods dictviews_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004234 0, /*nb_add*/
4235 (binaryfunc)dictviews_sub, /*nb_subtract*/
4236 0, /*nb_multiply*/
4237 0, /*nb_remainder*/
4238 0, /*nb_divmod*/
4239 0, /*nb_power*/
4240 0, /*nb_negative*/
4241 0, /*nb_positive*/
4242 0, /*nb_absolute*/
4243 0, /*nb_bool*/
4244 0, /*nb_invert*/
4245 0, /*nb_lshift*/
4246 0, /*nb_rshift*/
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004247 (binaryfunc)_PyDictView_Intersect, /*nb_and*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 (binaryfunc)dictviews_xor, /*nb_xor*/
4249 (binaryfunc)dictviews_or, /*nb_or*/
Guido van Rossum523259b2007-08-24 23:41:22 +00004250};
4251
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004252static PyObject*
4253dictviews_isdisjoint(PyObject *self, PyObject *other)
4254{
4255 PyObject *it;
4256 PyObject *item = NULL;
4257
4258 if (self == other) {
Eric Snow96c6af92015-05-29 22:21:39 -06004259 if (dictview_len((_PyDictViewObject *)self) == 0)
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004260 Py_RETURN_TRUE;
4261 else
4262 Py_RETURN_FALSE;
4263 }
4264
4265 /* Iterate over the shorter object (only if other is a set,
4266 * because PySequence_Contains may be expensive otherwise): */
4267 if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
Eric Snow96c6af92015-05-29 22:21:39 -06004268 Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004269 Py_ssize_t len_other = PyObject_Size(other);
4270 if (len_other == -1)
4271 return NULL;
4272
4273 if ((len_other > len_self)) {
4274 PyObject *tmp = other;
4275 other = self;
4276 self = tmp;
4277 }
4278 }
4279
4280 it = PyObject_GetIter(other);
4281 if (it == NULL)
4282 return NULL;
4283
4284 while ((item = PyIter_Next(it)) != NULL) {
4285 int contains = PySequence_Contains(self, item);
4286 Py_DECREF(item);
4287 if (contains == -1) {
4288 Py_DECREF(it);
4289 return NULL;
4290 }
4291
4292 if (contains) {
4293 Py_DECREF(it);
4294 Py_RETURN_FALSE;
4295 }
4296 }
4297 Py_DECREF(it);
4298 if (PyErr_Occurred())
4299 return NULL; /* PyIter_Next raised an exception. */
4300 Py_RETURN_TRUE;
4301}
4302
4303PyDoc_STRVAR(isdisjoint_doc,
4304"Return True if the view and the given iterable have a null intersection.");
4305
Serhiy Storchaka81524022018-11-27 13:05:02 +02004306static PyObject* dictkeys_reversed(_PyDictViewObject *dv, PyObject *Py_UNUSED(ignored));
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004307
4308PyDoc_STRVAR(reversed_keys_doc,
4309"Return a reverse iterator over the dict keys.");
4310
Guido van Rossumb90c8482007-02-10 01:11:45 +00004311static PyMethodDef dictkeys_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004312 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4313 isdisjoint_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02004314 {"__reversed__", (PyCFunction)(void(*)(void))dictkeys_reversed, METH_NOARGS,
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004315 reversed_keys_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004316 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004317};
4318
4319PyTypeObject PyDictKeys_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004320 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4321 "dict_keys", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004322 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004323 0, /* tp_itemsize */
4324 /* methods */
4325 (destructor)dictview_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004326 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004327 0, /* tp_getattr */
4328 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004329 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004330 (reprfunc)dictview_repr, /* tp_repr */
4331 &dictviews_as_number, /* tp_as_number */
4332 &dictkeys_as_sequence, /* tp_as_sequence */
4333 0, /* tp_as_mapping */
4334 0, /* tp_hash */
4335 0, /* tp_call */
4336 0, /* tp_str */
4337 PyObject_GenericGetAttr, /* tp_getattro */
4338 0, /* tp_setattro */
4339 0, /* tp_as_buffer */
4340 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4341 0, /* tp_doc */
4342 (traverseproc)dictview_traverse, /* tp_traverse */
4343 0, /* tp_clear */
4344 dictview_richcompare, /* tp_richcompare */
4345 0, /* tp_weaklistoffset */
4346 (getiterfunc)dictkeys_iter, /* tp_iter */
4347 0, /* tp_iternext */
4348 dictkeys_methods, /* tp_methods */
4349 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004350};
4351
4352static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304353dictkeys_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004354{
Eric Snow96c6af92015-05-29 22:21:39 -06004355 return _PyDictView_New(dict, &PyDictKeys_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004356}
4357
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004358static PyObject *
Serhiy Storchaka81524022018-11-27 13:05:02 +02004359dictkeys_reversed(_PyDictViewObject *dv, PyObject *Py_UNUSED(ignored))
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004360{
4361 if (dv->dv_dict == NULL) {
4362 Py_RETURN_NONE;
4363 }
4364 return dictiter_new(dv->dv_dict, &PyDictRevIterKey_Type);
4365}
4366
Guido van Rossum3ac67412007-02-10 18:55:06 +00004367/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004368
4369static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004370dictitems_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004372 if (dv->dv_dict == NULL) {
4373 Py_RETURN_NONE;
4374 }
4375 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00004376}
4377
4378static int
Eric Snow96c6af92015-05-29 22:21:39 -06004379dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00004380{
Serhiy Storchaka753bca32017-05-20 12:30:02 +03004381 int result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 PyObject *key, *value, *found;
4383 if (dv->dv_dict == NULL)
4384 return 0;
4385 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
4386 return 0;
4387 key = PyTuple_GET_ITEM(obj, 0);
4388 value = PyTuple_GET_ITEM(obj, 1);
Raymond Hettinger6692f012016-09-18 21:46:08 -07004389 found = PyDict_GetItemWithError((PyObject *)dv->dv_dict, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004390 if (found == NULL) {
4391 if (PyErr_Occurred())
4392 return -1;
4393 return 0;
4394 }
Serhiy Storchaka753bca32017-05-20 12:30:02 +03004395 Py_INCREF(found);
4396 result = PyObject_RichCompareBool(value, found, Py_EQ);
4397 Py_DECREF(found);
4398 return result;
Guido van Rossumb90c8482007-02-10 01:11:45 +00004399}
4400
Guido van Rossum83825ac2007-02-10 04:54:19 +00004401static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004402 (lenfunc)dictview_len, /* sq_length */
4403 0, /* sq_concat */
4404 0, /* sq_repeat */
4405 0, /* sq_item */
4406 0, /* sq_slice */
4407 0, /* sq_ass_item */
4408 0, /* sq_ass_slice */
4409 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004410};
4411
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004412static PyObject* dictitems_reversed(_PyDictViewObject *dv);
4413
4414PyDoc_STRVAR(reversed_items_doc,
4415"Return a reverse iterator over the dict items.");
4416
Guido van Rossumb90c8482007-02-10 01:11:45 +00004417static PyMethodDef dictitems_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004418 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4419 isdisjoint_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02004420 {"__reversed__", (PyCFunction)(void(*)(void))dictitems_reversed, METH_NOARGS,
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004421 reversed_items_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004422 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004423};
4424
4425PyTypeObject PyDictItems_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4427 "dict_items", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004428 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 0, /* tp_itemsize */
4430 /* methods */
4431 (destructor)dictview_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004432 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004433 0, /* tp_getattr */
4434 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004435 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 (reprfunc)dictview_repr, /* tp_repr */
4437 &dictviews_as_number, /* tp_as_number */
4438 &dictitems_as_sequence, /* tp_as_sequence */
4439 0, /* tp_as_mapping */
4440 0, /* tp_hash */
4441 0, /* tp_call */
4442 0, /* tp_str */
4443 PyObject_GenericGetAttr, /* tp_getattro */
4444 0, /* tp_setattro */
4445 0, /* tp_as_buffer */
4446 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4447 0, /* tp_doc */
4448 (traverseproc)dictview_traverse, /* tp_traverse */
4449 0, /* tp_clear */
4450 dictview_richcompare, /* tp_richcompare */
4451 0, /* tp_weaklistoffset */
4452 (getiterfunc)dictitems_iter, /* tp_iter */
4453 0, /* tp_iternext */
4454 dictitems_methods, /* tp_methods */
4455 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004456};
4457
4458static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304459dictitems_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004460{
Eric Snow96c6af92015-05-29 22:21:39 -06004461 return _PyDictView_New(dict, &PyDictItems_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004462}
4463
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004464static PyObject *
4465dictitems_reversed(_PyDictViewObject *dv)
4466{
4467 if (dv->dv_dict == NULL) {
4468 Py_RETURN_NONE;
4469 }
4470 return dictiter_new(dv->dv_dict, &PyDictRevIterItem_Type);
4471}
4472
Guido van Rossum3ac67412007-02-10 18:55:06 +00004473/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004474
4475static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004476dictvalues_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004478 if (dv->dv_dict == NULL) {
4479 Py_RETURN_NONE;
4480 }
4481 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004482}
4483
Guido van Rossum83825ac2007-02-10 04:54:19 +00004484static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004485 (lenfunc)dictview_len, /* sq_length */
4486 0, /* sq_concat */
4487 0, /* sq_repeat */
4488 0, /* sq_item */
4489 0, /* sq_slice */
4490 0, /* sq_ass_item */
4491 0, /* sq_ass_slice */
4492 (objobjproc)0, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004493};
4494
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004495static PyObject* dictvalues_reversed(_PyDictViewObject *dv);
4496
4497PyDoc_STRVAR(reversed_values_doc,
4498"Return a reverse iterator over the dict values.");
4499
Guido van Rossumb90c8482007-02-10 01:11:45 +00004500static PyMethodDef dictvalues_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02004501 {"__reversed__", (PyCFunction)(void(*)(void))dictvalues_reversed, METH_NOARGS,
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004502 reversed_values_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004504};
4505
4506PyTypeObject PyDictValues_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4508 "dict_values", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004509 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004510 0, /* tp_itemsize */
4511 /* methods */
4512 (destructor)dictview_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004513 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004514 0, /* tp_getattr */
4515 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004516 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 (reprfunc)dictview_repr, /* tp_repr */
4518 0, /* tp_as_number */
4519 &dictvalues_as_sequence, /* tp_as_sequence */
4520 0, /* tp_as_mapping */
4521 0, /* tp_hash */
4522 0, /* tp_call */
4523 0, /* tp_str */
4524 PyObject_GenericGetAttr, /* tp_getattro */
4525 0, /* tp_setattro */
4526 0, /* tp_as_buffer */
4527 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4528 0, /* tp_doc */
4529 (traverseproc)dictview_traverse, /* tp_traverse */
4530 0, /* tp_clear */
4531 0, /* tp_richcompare */
4532 0, /* tp_weaklistoffset */
4533 (getiterfunc)dictvalues_iter, /* tp_iter */
4534 0, /* tp_iternext */
4535 dictvalues_methods, /* tp_methods */
4536 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004537};
4538
4539static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304540dictvalues_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004541{
Eric Snow96c6af92015-05-29 22:21:39 -06004542 return _PyDictView_New(dict, &PyDictValues_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004543}
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004544
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004545static PyObject *
4546dictvalues_reversed(_PyDictViewObject *dv)
4547{
4548 if (dv->dv_dict == NULL) {
4549 Py_RETURN_NONE;
4550 }
4551 return dictiter_new(dv->dv_dict, &PyDictRevIterValue_Type);
4552}
4553
4554
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004555/* Returns NULL if cannot allocate a new PyDictKeysObject,
4556 but does not set an error */
4557PyDictKeysObject *
4558_PyDict_NewKeysForClass(void)
4559{
Victor Stinner742da042016-09-07 17:40:12 -07004560 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004561 if (keys == NULL)
4562 PyErr_Clear();
4563 else
4564 keys->dk_lookup = lookdict_split;
4565 return keys;
4566}
4567
4568#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
4569
4570PyObject *
4571PyObject_GenericGetDict(PyObject *obj, void *context)
4572{
4573 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
4574 if (dictptr == NULL) {
4575 PyErr_SetString(PyExc_AttributeError,
4576 "This object has no __dict__");
4577 return NULL;
4578 }
4579 dict = *dictptr;
4580 if (dict == NULL) {
4581 PyTypeObject *tp = Py_TYPE(obj);
4582 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
INADA Naokia7576492018-11-14 18:39:27 +09004583 dictkeys_incref(CACHED_KEYS(tp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004584 *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
4585 }
4586 else {
4587 *dictptr = dict = PyDict_New();
4588 }
4589 }
4590 Py_XINCREF(dict);
4591 return dict;
4592}
4593
4594int
4595_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
Victor Stinner742da042016-09-07 17:40:12 -07004596 PyObject *key, PyObject *value)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004597{
4598 PyObject *dict;
4599 int res;
4600 PyDictKeysObject *cached;
4601
4602 assert(dictptr != NULL);
4603 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
4604 assert(dictptr != NULL);
4605 dict = *dictptr;
4606 if (dict == NULL) {
INADA Naokia7576492018-11-14 18:39:27 +09004607 dictkeys_incref(cached);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004608 dict = new_dict_with_shared_keys(cached);
4609 if (dict == NULL)
4610 return -1;
4611 *dictptr = dict;
4612 }
4613 if (value == NULL) {
4614 res = PyDict_DelItem(dict, key);
INADA Naoki2294f3a2017-02-12 13:51:30 +09004615 // Since key sharing dict doesn't allow deletion, PyDict_DelItem()
4616 // always converts dict to combined form.
4617 if ((cached = CACHED_KEYS(tp)) != NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004618 CACHED_KEYS(tp) = NULL;
INADA Naokia7576492018-11-14 18:39:27 +09004619 dictkeys_decref(cached);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004620 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01004621 }
4622 else {
INADA Naoki2294f3a2017-02-12 13:51:30 +09004623 int was_shared = (cached == ((PyDictObject *)dict)->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004624 res = PyDict_SetItem(dict, key, value);
INADA Naoki2294f3a2017-02-12 13:51:30 +09004625 if (was_shared &&
4626 (cached = CACHED_KEYS(tp)) != NULL &&
4627 cached != ((PyDictObject *)dict)->ma_keys) {
Victor Stinner3d3f2642016-12-15 17:21:23 +01004628 /* PyDict_SetItem() may call dictresize and convert split table
4629 * into combined table. In such case, convert it to split
4630 * table again and update type's shared key only when this is
4631 * the only dict sharing key with the type.
4632 *
4633 * This is to allow using shared key in class like this:
4634 *
4635 * class C:
4636 * def __init__(self):
4637 * # one dict resize happens
4638 * self.a, self.b, self.c = 1, 2, 3
4639 * self.d, self.e, self.f = 4, 5, 6
4640 * a = C()
4641 */
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004642 if (cached->dk_refcnt == 1) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004643 CACHED_KEYS(tp) = make_keys_shared(dict);
Victor Stinner742da042016-09-07 17:40:12 -07004644 }
4645 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004646 CACHED_KEYS(tp) = NULL;
4647 }
INADA Naokia7576492018-11-14 18:39:27 +09004648 dictkeys_decref(cached);
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004649 if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
4650 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004651 }
4652 }
4653 } else {
4654 dict = *dictptr;
4655 if (dict == NULL) {
4656 dict = PyDict_New();
4657 if (dict == NULL)
4658 return -1;
4659 *dictptr = dict;
4660 }
4661 if (value == NULL) {
4662 res = PyDict_DelItem(dict, key);
4663 } else {
4664 res = PyDict_SetItem(dict, key, value);
4665 }
4666 }
4667 return res;
4668}
4669
4670void
4671_PyDictKeys_DecRef(PyDictKeysObject *keys)
4672{
INADA Naokia7576492018-11-14 18:39:27 +09004673 dictkeys_decref(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004674}