blob: b6205d93ca1408f134902aa1943040f1445d8fb9 [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) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +02002116 res = _PyObject_CallOneArg(missing, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 Py_DECREF(missing);
2118 return res;
2119 }
2120 else if (PyErr_Occurred())
2121 return NULL;
2122 }
Raymond Hettinger69492da2013-09-02 15:59:26 -07002123 _PyErr_SetKeyError(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 return NULL;
2125 }
INADA Naokiba609772016-12-07 20:41:42 +09002126 Py_INCREF(value);
2127 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002128}
2129
2130static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002131dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 if (w == NULL)
2134 return PyDict_DelItem((PyObject *)mp, v);
2135 else
2136 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002137}
2138
Guido van Rossuma9e7a811997-05-13 21:02:11 +00002139static PyMappingMethods dict_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 (lenfunc)dict_length, /*mp_length*/
2141 (binaryfunc)dict_subscript, /*mp_subscript*/
2142 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002143};
2144
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002145static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002146dict_keys(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002147{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002148 PyObject *v;
2149 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002150 PyDictKeyEntry *ep;
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002151 Py_ssize_t n, offset;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002152 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002153
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002154 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 n = mp->ma_used;
2156 v = PyList_New(n);
2157 if (v == NULL)
2158 return NULL;
2159 if (n != mp->ma_used) {
2160 /* Durnit. The allocations caused the dict to resize.
2161 * Just start over, this shouldn't normally happen.
2162 */
2163 Py_DECREF(v);
2164 goto again;
2165 }
Victor Stinner742da042016-09-07 17:40:12 -07002166 ep = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002167 if (mp->ma_values) {
2168 value_ptr = mp->ma_values;
2169 offset = sizeof(PyObject *);
2170 }
2171 else {
2172 value_ptr = &ep[0].me_value;
2173 offset = sizeof(PyDictKeyEntry);
2174 }
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002175 for (i = 0, j = 0; j < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002176 if (*value_ptr != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 PyObject *key = ep[i].me_key;
2178 Py_INCREF(key);
2179 PyList_SET_ITEM(v, j, key);
2180 j++;
2181 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002182 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 }
2184 assert(j == n);
2185 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002186}
2187
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002188static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002189dict_values(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002190{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002191 PyObject *v;
2192 Py_ssize_t i, j;
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002193 PyDictKeyEntry *ep;
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002194 Py_ssize_t n, offset;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002195 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002196
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002197 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 n = mp->ma_used;
2199 v = PyList_New(n);
2200 if (v == NULL)
2201 return NULL;
2202 if (n != mp->ma_used) {
2203 /* Durnit. The allocations caused the dict to resize.
2204 * Just start over, this shouldn't normally happen.
2205 */
2206 Py_DECREF(v);
2207 goto again;
2208 }
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002209 ep = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002210 if (mp->ma_values) {
2211 value_ptr = mp->ma_values;
2212 offset = sizeof(PyObject *);
2213 }
2214 else {
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002215 value_ptr = &ep[0].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002216 offset = sizeof(PyDictKeyEntry);
2217 }
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002218 for (i = 0, j = 0; j < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002219 PyObject *value = *value_ptr;
2220 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2221 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 Py_INCREF(value);
2223 PyList_SET_ITEM(v, j, value);
2224 j++;
2225 }
2226 }
2227 assert(j == n);
2228 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002229}
2230
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002231static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002232dict_items(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002233{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002234 PyObject *v;
2235 Py_ssize_t i, j, n;
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002236 Py_ssize_t offset;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002237 PyObject *item, *key;
2238 PyDictKeyEntry *ep;
2239 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 /* Preallocate the list of tuples, to avoid allocations during
2242 * the loop over the items, which could trigger GC, which
2243 * could resize the dict. :-(
2244 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002245 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 n = mp->ma_used;
2247 v = PyList_New(n);
2248 if (v == NULL)
2249 return NULL;
2250 for (i = 0; i < n; i++) {
2251 item = PyTuple_New(2);
2252 if (item == NULL) {
2253 Py_DECREF(v);
2254 return NULL;
2255 }
2256 PyList_SET_ITEM(v, i, item);
2257 }
2258 if (n != mp->ma_used) {
2259 /* Durnit. The allocations caused the dict to resize.
2260 * Just start over, this shouldn't normally happen.
2261 */
2262 Py_DECREF(v);
2263 goto again;
2264 }
2265 /* Nothing we do below makes any function calls. */
Victor Stinner742da042016-09-07 17:40:12 -07002266 ep = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002267 if (mp->ma_values) {
2268 value_ptr = mp->ma_values;
2269 offset = sizeof(PyObject *);
2270 }
2271 else {
2272 value_ptr = &ep[0].me_value;
2273 offset = sizeof(PyDictKeyEntry);
2274 }
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002275 for (i = 0, j = 0; j < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002276 PyObject *value = *value_ptr;
2277 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2278 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 key = ep[i].me_key;
2280 item = PyList_GET_ITEM(v, j);
2281 Py_INCREF(key);
2282 PyTuple_SET_ITEM(item, 0, key);
2283 Py_INCREF(value);
2284 PyTuple_SET_ITEM(item, 1, value);
2285 j++;
2286 }
2287 }
2288 assert(j == n);
2289 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002290}
2291
Larry Hastings5c661892014-01-24 06:17:25 -08002292/*[clinic input]
2293@classmethod
2294dict.fromkeys
Larry Hastings5c661892014-01-24 06:17:25 -08002295 iterable: object
2296 value: object=None
2297 /
2298
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002299Create a new dictionary with keys from iterable and values set to value.
Larry Hastings5c661892014-01-24 06:17:25 -08002300[clinic start generated code]*/
2301
Larry Hastings5c661892014-01-24 06:17:25 -08002302static PyObject *
2303dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002304/*[clinic end generated code: output=8fb98e4b10384999 input=382ba4855d0f74c3]*/
Larry Hastings5c661892014-01-24 06:17:25 -08002305{
Eric Snow96c6af92015-05-29 22:21:39 -06002306 return _PyDict_FromKeys((PyObject *)type, iterable, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002307}
2308
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002309static int
Victor Stinner742da042016-09-07 17:40:12 -07002310dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
2311 const char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 PyObject *arg = NULL;
2314 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002315
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002316 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 result = -1;
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002318 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 else if (arg != NULL) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02002320 _Py_IDENTIFIER(keys);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002321 PyObject *func;
2322 if (_PyObject_LookupAttrId(arg, &PyId_keys, &func) < 0) {
2323 result = -1;
2324 }
2325 else if (func != NULL) {
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002326 Py_DECREF(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 result = PyDict_Merge(self, arg, 1);
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002328 }
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002329 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002330 result = PyDict_MergeFromSeq2(self, arg, 1);
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002331 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 }
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 if (result == 0 && kwds != NULL) {
2335 if (PyArg_ValidateKeywordArguments(kwds))
2336 result = PyDict_Merge(self, kwds, 1);
2337 else
2338 result = -1;
2339 }
2340 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002341}
2342
Victor Stinner91f0d4a2017-01-19 12:45:06 +01002343/* Note: dict.update() uses the METH_VARARGS|METH_KEYWORDS calling convention.
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002344 Using METH_FASTCALL|METH_KEYWORDS would make dict.update(**dict2) calls
2345 slower, see the issue #29312. */
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002346static PyObject *
2347dict_update(PyObject *self, PyObject *args, PyObject *kwds)
2348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 if (dict_update_common(self, args, kwds, "update") != -1)
2350 Py_RETURN_NONE;
2351 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002352}
2353
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002354/* Update unconditionally replaces existing items.
2355 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00002356 otherwise it leaves existing items unchanged.
2357
2358 PyDict_{Update,Merge} update/merge from a mapping object.
2359
Tim Petersf582b822001-12-11 18:51:08 +00002360 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00002361 producing iterable objects of length 2.
2362*/
2363
Tim Petersf582b822001-12-11 18:51:08 +00002364int
Tim Peters1fc240e2001-10-26 05:06:50 +00002365PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
2366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 PyObject *it; /* iter(seq2) */
2368 Py_ssize_t i; /* index into seq2 of current element */
2369 PyObject *item; /* seq2[i] */
2370 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00002371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 assert(d != NULL);
2373 assert(PyDict_Check(d));
2374 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 it = PyObject_GetIter(seq2);
2377 if (it == NULL)
2378 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 for (i = 0; ; ++i) {
2381 PyObject *key, *value;
2382 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 fast = NULL;
2385 item = PyIter_Next(it);
2386 if (item == NULL) {
2387 if (PyErr_Occurred())
2388 goto Fail;
2389 break;
2390 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 /* Convert item to sequence, and verify length 2. */
2393 fast = PySequence_Fast(item, "");
2394 if (fast == NULL) {
2395 if (PyErr_ExceptionMatches(PyExc_TypeError))
2396 PyErr_Format(PyExc_TypeError,
2397 "cannot convert dictionary update "
2398 "sequence element #%zd to a sequence",
2399 i);
2400 goto Fail;
2401 }
2402 n = PySequence_Fast_GET_SIZE(fast);
2403 if (n != 2) {
2404 PyErr_Format(PyExc_ValueError,
2405 "dictionary update sequence element #%zd "
2406 "has length %zd; 2 is required",
2407 i, n);
2408 goto Fail;
2409 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 /* Update/merge with this (key, value) pair. */
2412 key = PySequence_Fast_GET_ITEM(fast, 0);
2413 value = PySequence_Fast_GET_ITEM(fast, 1);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002414 Py_INCREF(key);
2415 Py_INCREF(value);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002416 if (override) {
2417 if (PyDict_SetItem(d, key, value) < 0) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002418 Py_DECREF(key);
2419 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 goto Fail;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002421 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002423 else if (PyDict_GetItemWithError(d, key) == NULL) {
2424 if (PyErr_Occurred() || PyDict_SetItem(d, key, value) < 0) {
2425 Py_DECREF(key);
2426 Py_DECREF(value);
2427 goto Fail;
2428 }
2429 }
2430
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002431 Py_DECREF(key);
2432 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 Py_DECREF(fast);
2434 Py_DECREF(item);
2435 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 i = 0;
Victor Stinner0fc91ee2019-04-12 21:51:34 +02002438 ASSERT_CONSISTENT(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00002440Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 Py_XDECREF(item);
2442 Py_XDECREF(fast);
2443 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002444Return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 Py_DECREF(it);
2446 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00002447}
2448
doko@ubuntu.comc96df682016-10-11 08:04:02 +02002449static int
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002450dict_merge(PyObject *a, PyObject *b, int override)
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002451{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002452 PyDictObject *mp, *other;
2453 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -07002454 PyDictKeyEntry *entry, *ep0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002455
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002456 assert(0 <= override && override <= 2);
2457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 /* We accept for the argument either a concrete dictionary object,
2459 * or an abstract "mapping" object. For the former, we can do
2460 * things quite efficiently. For the latter, we only require that
2461 * PyMapping_Keys() and PyObject_GetItem() be supported.
2462 */
2463 if (a == NULL || !PyDict_Check(a) || b == NULL) {
2464 PyErr_BadInternalCall();
2465 return -1;
2466 }
2467 mp = (PyDictObject*)a;
INADA Naoki2aaf98c2018-09-26 12:59:00 +09002468 if (PyDict_Check(b) && (Py_TYPE(b)->tp_iter == (getiterfunc)dict_iter)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 other = (PyDictObject*)b;
2470 if (other == mp || other->ma_used == 0)
2471 /* a.update(a) or a.update({}); nothing to do */
2472 return 0;
2473 if (mp->ma_used == 0)
2474 /* Since the target dict is empty, PyDict_GetItem()
2475 * always returns NULL. Setting override to 1
2476 * skips the unnecessary test.
2477 */
2478 override = 1;
2479 /* Do one big resize at the start, rather than
2480 * incrementally resizing as we insert new items. Expect
2481 * that there will be no (or few) overlapping keys.
2482 */
INADA Naokib1152be2016-10-27 19:26:50 +09002483 if (USABLE_FRACTION(mp->ma_keys->dk_size) < other->ma_used) {
2484 if (dictresize(mp, ESTIMATE_SIZE(mp->ma_used + other->ma_used))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 return -1;
INADA Naokib1152be2016-10-27 19:26:50 +09002486 }
2487 }
Victor Stinner742da042016-09-07 17:40:12 -07002488 ep0 = DK_ENTRIES(other->ma_keys);
2489 for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002490 PyObject *key, *value;
2491 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002492 entry = &ep0[i];
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002493 key = entry->me_key;
2494 hash = entry->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002495 if (other->ma_values)
2496 value = other->ma_values[i];
2497 else
2498 value = entry->me_value;
2499
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002500 if (value != NULL) {
2501 int err = 0;
2502 Py_INCREF(key);
2503 Py_INCREF(value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002504 if (override == 1)
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002505 err = insertdict(mp, key, hash, value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002506 else if (_PyDict_GetItem_KnownHash(a, key, hash) == NULL) {
2507 if (PyErr_Occurred()) {
2508 Py_DECREF(value);
2509 Py_DECREF(key);
2510 return -1;
2511 }
2512 err = insertdict(mp, key, hash, value);
2513 }
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002514 else if (override != 0) {
2515 _PyErr_SetKeyError(key);
2516 Py_DECREF(value);
2517 Py_DECREF(key);
2518 return -1;
2519 }
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002520 Py_DECREF(value);
2521 Py_DECREF(key);
2522 if (err != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 return -1;
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002524
Victor Stinner742da042016-09-07 17:40:12 -07002525 if (n != other->ma_keys->dk_nentries) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002526 PyErr_SetString(PyExc_RuntimeError,
2527 "dict mutated during update");
2528 return -1;
2529 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 }
2531 }
2532 }
2533 else {
2534 /* Do it the generic, slower way */
2535 PyObject *keys = PyMapping_Keys(b);
2536 PyObject *iter;
2537 PyObject *key, *value;
2538 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 if (keys == NULL)
2541 /* Docstring says this is equivalent to E.keys() so
2542 * if E doesn't have a .keys() method we want
2543 * AttributeError to percolate up. Might as well
2544 * do the same for any other error.
2545 */
2546 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 iter = PyObject_GetIter(keys);
2549 Py_DECREF(keys);
2550 if (iter == NULL)
2551 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002554 if (override != 1) {
2555 if (PyDict_GetItemWithError(a, key) != NULL) {
2556 if (override != 0) {
2557 _PyErr_SetKeyError(key);
2558 Py_DECREF(key);
2559 Py_DECREF(iter);
2560 return -1;
2561 }
2562 Py_DECREF(key);
2563 continue;
2564 }
2565 else if (PyErr_Occurred()) {
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002566 Py_DECREF(key);
2567 Py_DECREF(iter);
2568 return -1;
2569 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 }
2571 value = PyObject_GetItem(b, key);
2572 if (value == NULL) {
2573 Py_DECREF(iter);
2574 Py_DECREF(key);
2575 return -1;
2576 }
2577 status = PyDict_SetItem(a, key, value);
2578 Py_DECREF(key);
2579 Py_DECREF(value);
2580 if (status < 0) {
2581 Py_DECREF(iter);
2582 return -1;
2583 }
2584 }
2585 Py_DECREF(iter);
2586 if (PyErr_Occurred())
2587 /* Iterator completed, via error */
2588 return -1;
2589 }
Victor Stinner0fc91ee2019-04-12 21:51:34 +02002590 ASSERT_CONSISTENT(a);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002592}
2593
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002594int
2595PyDict_Update(PyObject *a, PyObject *b)
2596{
2597 return dict_merge(a, b, 1);
2598}
2599
2600int
2601PyDict_Merge(PyObject *a, PyObject *b, int override)
2602{
2603 /* XXX Deprecate override not in (0, 1). */
2604 return dict_merge(a, b, override != 0);
2605}
2606
2607int
2608_PyDict_MergeEx(PyObject *a, PyObject *b, int override)
2609{
2610 return dict_merge(a, b, override);
2611}
2612
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002613static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302614dict_copy(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002617}
2618
2619PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002620PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 PyObject *copy;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002623 PyDictObject *mp;
2624 Py_ssize_t i, n;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 if (o == NULL || !PyDict_Check(o)) {
2627 PyErr_BadInternalCall();
2628 return NULL;
2629 }
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002630
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002631 mp = (PyDictObject *)o;
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002632 if (mp->ma_used == 0) {
2633 /* The dict is empty; just return a new dict. */
2634 return PyDict_New();
2635 }
2636
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002637 if (_PyDict_HasSplitTable(mp)) {
2638 PyDictObject *split_copy;
Victor Stinner742da042016-09-07 17:40:12 -07002639 Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
2640 PyObject **newvalues;
2641 newvalues = new_values(size);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002642 if (newvalues == NULL)
2643 return PyErr_NoMemory();
2644 split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
2645 if (split_copy == NULL) {
2646 free_values(newvalues);
2647 return NULL;
2648 }
2649 split_copy->ma_values = newvalues;
2650 split_copy->ma_keys = mp->ma_keys;
2651 split_copy->ma_used = mp->ma_used;
INADA Naokid1c82c52018-04-03 11:43:53 +09002652 split_copy->ma_version_tag = DICT_NEXT_VERSION();
INADA Naokia7576492018-11-14 18:39:27 +09002653 dictkeys_incref(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002654 for (i = 0, n = size; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002655 PyObject *value = mp->ma_values[i];
2656 Py_XINCREF(value);
2657 split_copy->ma_values[i] = value;
2658 }
Benjamin Peterson7ce67e42012-04-24 10:32:57 -04002659 if (_PyObject_GC_IS_TRACKED(mp))
2660 _PyObject_GC_TRACK(split_copy);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002661 return (PyObject *)split_copy;
2662 }
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002663
2664 if (PyDict_CheckExact(mp) && mp->ma_values == NULL &&
2665 (mp->ma_used >= (mp->ma_keys->dk_nentries * 2) / 3))
2666 {
2667 /* Use fast-copy if:
2668
2669 (1) 'mp' is an instance of a subclassed dict; and
2670
2671 (2) 'mp' is not a split-dict; and
2672
2673 (3) if 'mp' is non-compact ('del' operation does not resize dicts),
2674 do fast-copy only if it has at most 1/3 non-used keys.
2675
Ville Skyttä61f82e02018-04-20 23:08:45 +03002676 The last condition (3) is important to guard against a pathological
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002677 case when a large dict is almost emptied with multiple del/pop
2678 operations and copied after that. In cases like this, we defer to
2679 PyDict_Merge, which produces a compacted copy.
2680 */
2681 return clone_combined_dict(mp);
2682 }
2683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 copy = PyDict_New();
2685 if (copy == NULL)
2686 return NULL;
2687 if (PyDict_Merge(copy, o, 1) == 0)
2688 return copy;
2689 Py_DECREF(copy);
2690 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002691}
2692
Martin v. Löwis18e16552006-02-15 17:27:45 +00002693Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00002694PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00002695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 if (mp == NULL || !PyDict_Check(mp)) {
2697 PyErr_BadInternalCall();
2698 return -1;
2699 }
2700 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00002701}
2702
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002703PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002704PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 if (mp == NULL || !PyDict_Check(mp)) {
2707 PyErr_BadInternalCall();
2708 return NULL;
2709 }
2710 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002711}
2712
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002713PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002714PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 if (mp == NULL || !PyDict_Check(mp)) {
2717 PyErr_BadInternalCall();
2718 return NULL;
2719 }
2720 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002721}
2722
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002723PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002724PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 if (mp == NULL || !PyDict_Check(mp)) {
2727 PyErr_BadInternalCall();
2728 return NULL;
2729 }
2730 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002731}
2732
Tim Peterse63415e2001-05-08 04:38:29 +00002733/* Return 1 if dicts equal, 0 if not, -1 if error.
2734 * Gets out as soon as any difference is detected.
2735 * Uses only Py_EQ comparison.
2736 */
2737static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002738dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00002739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00002741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 if (a->ma_used != b->ma_used)
2743 /* can't be equal if # of entries differ */
2744 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Victor Stinner742da042016-09-07 17:40:12 -07002746 for (i = 0; i < a->ma_keys->dk_nentries; i++) {
2747 PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002748 PyObject *aval;
2749 if (a->ma_values)
2750 aval = a->ma_values[i];
2751 else
2752 aval = ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 if (aval != NULL) {
2754 int cmp;
2755 PyObject *bval;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002756 PyObject *key = ep->me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 /* temporarily bump aval's refcount to ensure it stays
2758 alive until we're done with it */
2759 Py_INCREF(aval);
2760 /* ditto for key */
2761 Py_INCREF(key);
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002762 /* reuse the known hash value */
INADA Naoki778928b2017-08-03 23:45:15 +09002763 b->ma_keys->dk_lookup(b, key, ep->me_hash, &bval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 if (bval == NULL) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002765 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 Py_DECREF(aval);
2767 if (PyErr_Occurred())
2768 return -1;
2769 return 0;
2770 }
2771 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002772 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 Py_DECREF(aval);
2774 if (cmp <= 0) /* error or not equal */
2775 return cmp;
2776 }
2777 }
2778 return 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002779}
Tim Peterse63415e2001-05-08 04:38:29 +00002780
2781static PyObject *
2782dict_richcompare(PyObject *v, PyObject *w, int op)
2783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 int cmp;
2785 PyObject *res;
Tim Peterse63415e2001-05-08 04:38:29 +00002786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 if (!PyDict_Check(v) || !PyDict_Check(w)) {
2788 res = Py_NotImplemented;
2789 }
2790 else if (op == Py_EQ || op == Py_NE) {
2791 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
2792 if (cmp < 0)
2793 return NULL;
2794 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
2795 }
2796 else
2797 res = Py_NotImplemented;
2798 Py_INCREF(res);
2799 return res;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002800}
Tim Peterse63415e2001-05-08 04:38:29 +00002801
Larry Hastings61272b72014-01-07 12:41:53 -08002802/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002803
2804@coexist
2805dict.__contains__
2806
2807 key: object
2808 /
2809
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002810True if the dictionary has the specified key, else False.
Larry Hastings61272b72014-01-07 12:41:53 -08002811[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002812
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002813static PyObject *
Larry Hastingsc2047262014-01-25 20:43:29 -08002814dict___contains__(PyDictObject *self, PyObject *key)
Serhiy Storchaka19d25972017-02-04 08:05:07 +02002815/*[clinic end generated code: output=a3d03db709ed6e6b input=fe1cb42ad831e820]*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002816{
Larry Hastingsc2047262014-01-25 20:43:29 -08002817 register PyDictObject *mp = self;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002818 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002819 Py_ssize_t ix;
INADA Naokiba609772016-12-07 20:41:42 +09002820 PyObject *value;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002823 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 hash = PyObject_Hash(key);
2825 if (hash == -1)
2826 return NULL;
2827 }
INADA Naoki778928b2017-08-03 23:45:15 +09002828 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002829 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002831 if (ix == DKIX_EMPTY || value == NULL)
Victor Stinner742da042016-09-07 17:40:12 -07002832 Py_RETURN_FALSE;
2833 Py_RETURN_TRUE;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002834}
2835
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002836/*[clinic input]
2837dict.get
2838
2839 key: object
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002840 default: object = None
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002841 /
2842
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002843Return the value for key if key is in the dictionary, else default.
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002844[clinic start generated code]*/
2845
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002846static PyObject *
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002847dict_get_impl(PyDictObject *self, PyObject *key, PyObject *default_value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002848/*[clinic end generated code: output=bba707729dee05bf input=279ddb5790b6b107]*/
Barry Warsawc38c5da1997-10-06 17:49:20 +00002849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002851 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002852 Py_ssize_t ix;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002855 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 hash = PyObject_Hash(key);
2857 if (hash == -1)
2858 return NULL;
2859 }
INADA Naoki778928b2017-08-03 23:45:15 +09002860 ix = (self->ma_keys->dk_lookup) (self, key, hash, &val);
Victor Stinner742da042016-09-07 17:40:12 -07002861 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002863 if (ix == DKIX_EMPTY || val == NULL) {
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002864 val = default_value;
INADA Naokiba609772016-12-07 20:41:42 +09002865 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 Py_INCREF(val);
2867 return val;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002868}
2869
Benjamin Peterson00e98862013-03-07 22:16:29 -05002870PyObject *
2871PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
Guido van Rossum164452c2000-08-08 16:12:54 +00002872{
Benjamin Peterson00e98862013-03-07 22:16:29 -05002873 PyDictObject *mp = (PyDictObject *)d;
INADA Naoki93f26f72016-11-02 18:45:16 +09002874 PyObject *value;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002875 Py_hash_t hash;
Guido van Rossum164452c2000-08-08 16:12:54 +00002876
Benjamin Peterson00e98862013-03-07 22:16:29 -05002877 if (!PyDict_Check(d)) {
2878 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 return NULL;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002880 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002883 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 hash = PyObject_Hash(key);
2885 if (hash == -1)
2886 return NULL;
2887 }
Inada Naoki2ddc7f62019-03-18 20:38:33 +09002888 if (mp->ma_keys == Py_EMPTY_KEYS) {
2889 if (insert_to_emptydict(mp, key, hash, defaultobj) < 0) {
2890 return NULL;
2891 }
2892 return defaultobj;
2893 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002894
2895 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
2896 if (insertion_resize(mp) < 0)
2897 return NULL;
2898 }
2899
INADA Naoki778928b2017-08-03 23:45:15 +09002900 Py_ssize_t ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002901 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 return NULL;
INADA Naoki93f26f72016-11-02 18:45:16 +09002903
2904 if (_PyDict_HasSplitTable(mp) &&
INADA Naokiba609772016-12-07 20:41:42 +09002905 ((ix >= 0 && value == NULL && mp->ma_used != ix) ||
INADA Naoki93f26f72016-11-02 18:45:16 +09002906 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
2907 if (insertion_resize(mp) < 0) {
2908 return NULL;
2909 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002910 ix = DKIX_EMPTY;
2911 }
2912
2913 if (ix == DKIX_EMPTY) {
2914 PyDictKeyEntry *ep, *ep0;
2915 value = defaultobj;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002916 if (mp->ma_keys->dk_usable <= 0) {
Victor Stinner3c336c52016-09-12 14:17:40 +02002917 if (insertion_resize(mp) < 0) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002918 return NULL;
Victor Stinner3c336c52016-09-12 14:17:40 +02002919 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002920 }
INADA Naoki778928b2017-08-03 23:45:15 +09002921 Py_ssize_t hashpos = find_empty_slot(mp->ma_keys, hash);
INADA Naoki93f26f72016-11-02 18:45:16 +09002922 ep0 = DK_ENTRIES(mp->ma_keys);
2923 ep = &ep0[mp->ma_keys->dk_nentries];
INADA Naokia7576492018-11-14 18:39:27 +09002924 dictkeys_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
Benjamin Petersonb1efa532013-03-04 09:47:50 -05002925 Py_INCREF(key);
INADA Naoki93f26f72016-11-02 18:45:16 +09002926 Py_INCREF(value);
2927 MAINTAIN_TRACKING(mp, key, value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002928 ep->me_key = key;
2929 ep->me_hash = hash;
INADA Naokiba609772016-12-07 20:41:42 +09002930 if (_PyDict_HasSplitTable(mp)) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002931 assert(mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
2932 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Victor Stinner742da042016-09-07 17:40:12 -07002933 }
2934 else {
INADA Naoki93f26f72016-11-02 18:45:16 +09002935 ep->me_value = value;
Victor Stinner742da042016-09-07 17:40:12 -07002936 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002937 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07002938 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naoki93f26f72016-11-02 18:45:16 +09002939 mp->ma_keys->dk_usable--;
2940 mp->ma_keys->dk_nentries++;
2941 assert(mp->ma_keys->dk_usable >= 0);
2942 }
INADA Naokiba609772016-12-07 20:41:42 +09002943 else if (value == NULL) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002944 value = defaultobj;
2945 assert(_PyDict_HasSplitTable(mp));
2946 assert(ix == mp->ma_used);
2947 Py_INCREF(value);
2948 MAINTAIN_TRACKING(mp, key, value);
INADA Naokiba609772016-12-07 20:41:42 +09002949 mp->ma_values[ix] = value;
INADA Naoki93f26f72016-11-02 18:45:16 +09002950 mp->ma_used++;
2951 mp->ma_version_tag = DICT_NEXT_VERSION();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002953
Victor Stinner0fc91ee2019-04-12 21:51:34 +02002954 ASSERT_CONSISTENT(mp);
INADA Naoki93f26f72016-11-02 18:45:16 +09002955 return value;
Guido van Rossum164452c2000-08-08 16:12:54 +00002956}
2957
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002958/*[clinic input]
2959dict.setdefault
2960
2961 key: object
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002962 default: object = None
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002963 /
2964
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002965Insert key with a value of default if key is not in the dictionary.
2966
2967Return the value for key if key is in the dictionary, else default.
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002968[clinic start generated code]*/
2969
Benjamin Peterson00e98862013-03-07 22:16:29 -05002970static PyObject *
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002971dict_setdefault_impl(PyDictObject *self, PyObject *key,
2972 PyObject *default_value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002973/*[clinic end generated code: output=f8c1101ebf69e220 input=0f063756e815fd9d]*/
Benjamin Peterson00e98862013-03-07 22:16:29 -05002974{
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002975 PyObject *val;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002976
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002977 val = PyDict_SetDefault((PyObject *)self, key, default_value);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002978 Py_XINCREF(val);
2979 return val;
2980}
Guido van Rossum164452c2000-08-08 16:12:54 +00002981
2982static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302983dict_clear(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 PyDict_Clear((PyObject *)mp);
2986 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002987}
2988
Inada Naoki9e4f2f32019-04-12 16:11:28 +09002989/*[clinic input]
2990dict.pop
2991
2992 key: object
2993 default: object = NULL
2994 /
2995
2996Remove specified key and return the corresponding value.
2997
2998If key is not found, default is returned if given, otherwise KeyError is raised
2999[clinic start generated code]*/
3000
Guido van Rossumba6ab842000-12-12 22:02:18 +00003001static PyObject *
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003002dict_pop_impl(PyDictObject *self, PyObject *key, PyObject *default_value)
3003/*[clinic end generated code: output=3abb47b89f24c21c input=016f6a000e4e633b]*/
Guido van Rossume027d982002-04-12 15:11:59 +00003004{
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003005 return _PyDict_Pop((PyObject*)self, key, default_value);
Guido van Rossume027d982002-04-12 15:11:59 +00003006}
3007
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003008/*[clinic input]
3009dict.popitem
3010
3011Remove and return a (key, value) pair as a 2-tuple.
3012
3013Pairs are returned in LIFO (last-in, first-out) order.
3014Raises KeyError if the dict is empty.
3015[clinic start generated code]*/
3016
Guido van Rossume027d982002-04-12 15:11:59 +00003017static PyObject *
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003018dict_popitem_impl(PyDictObject *self)
3019/*[clinic end generated code: output=e65fcb04420d230d input=1c38a49f21f64941]*/
Guido van Rossumba6ab842000-12-12 22:02:18 +00003020{
Victor Stinner742da042016-09-07 17:40:12 -07003021 Py_ssize_t i, j;
3022 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 PyObject *res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00003024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 /* Allocate the result tuple before checking the size. Believe it
3026 * or not, this allocation could trigger a garbage collection which
3027 * could empty the dict, so if we checked the size first and that
3028 * happened, the result would be an infinite loop (searching for an
3029 * entry that no longer exists). Note that the usual popitem()
3030 * idiom is "while d: k, v = d.popitem()". so needing to throw the
3031 * tuple away if the dict *is* empty isn't a significant
3032 * inefficiency -- possible, but unlikely in practice.
3033 */
3034 res = PyTuple_New(2);
3035 if (res == NULL)
3036 return NULL;
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003037 if (self->ma_used == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 Py_DECREF(res);
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003039 PyErr_SetString(PyExc_KeyError, "popitem(): dictionary is empty");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 return NULL;
3041 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003042 /* Convert split table to combined table */
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003043 if (self->ma_keys->dk_lookup == lookdict_split) {
3044 if (dictresize(self, DK_SIZE(self->ma_keys))) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003045 Py_DECREF(res);
3046 return NULL;
3047 }
3048 }
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003049 ENSURE_ALLOWS_DELETIONS(self);
Victor Stinner742da042016-09-07 17:40:12 -07003050
3051 /* Pop last item */
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003052 ep0 = DK_ENTRIES(self->ma_keys);
3053 i = self->ma_keys->dk_nentries - 1;
Victor Stinner742da042016-09-07 17:40:12 -07003054 while (i >= 0 && ep0[i].me_value == NULL) {
3055 i--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 }
Victor Stinner742da042016-09-07 17:40:12 -07003057 assert(i >= 0);
3058
3059 ep = &ep0[i];
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003060 j = lookdict_index(self->ma_keys, ep->me_hash, i);
Victor Stinner742da042016-09-07 17:40:12 -07003061 assert(j >= 0);
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003062 assert(dictkeys_get_index(self->ma_keys, j) == i);
3063 dictkeys_set_index(self->ma_keys, j, DKIX_DUMMY);
Victor Stinner742da042016-09-07 17:40:12 -07003064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 PyTuple_SET_ITEM(res, 0, ep->me_key);
3066 PyTuple_SET_ITEM(res, 1, ep->me_value);
Victor Stinner742da042016-09-07 17:40:12 -07003067 ep->me_key = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 ep->me_value = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07003069 /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003070 self->ma_keys->dk_nentries = i;
3071 self->ma_used--;
3072 self->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner0fc91ee2019-04-12 21:51:34 +02003073 ASSERT_CONSISTENT(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 return res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00003075}
3076
Jeremy Hylton8caad492000-06-23 14:18:11 +00003077static int
3078dict_traverse(PyObject *op, visitproc visit, void *arg)
3079{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003080 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson55f44522016-09-05 12:12:59 -07003081 PyDictKeysObject *keys = mp->ma_keys;
Serhiy Storchaka46825d22016-09-26 21:29:34 +03003082 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Victor Stinner742da042016-09-07 17:40:12 -07003083 Py_ssize_t i, n = keys->dk_nentries;
3084
Benjamin Peterson55f44522016-09-05 12:12:59 -07003085 if (keys->dk_lookup == lookdict) {
3086 for (i = 0; i < n; i++) {
3087 if (entries[i].me_value != NULL) {
3088 Py_VISIT(entries[i].me_value);
3089 Py_VISIT(entries[i].me_key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003090 }
3091 }
Victor Stinner742da042016-09-07 17:40:12 -07003092 }
3093 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003094 if (mp->ma_values != NULL) {
Benjamin Peterson55f44522016-09-05 12:12:59 -07003095 for (i = 0; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003096 Py_VISIT(mp->ma_values[i]);
3097 }
3098 }
3099 else {
Benjamin Peterson55f44522016-09-05 12:12:59 -07003100 for (i = 0; i < n; i++) {
3101 Py_VISIT(entries[i].me_value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003102 }
3103 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 }
3105 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00003106}
3107
3108static int
3109dict_tp_clear(PyObject *op)
3110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 PyDict_Clear(op);
3112 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00003113}
3114
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003115static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003116
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003117Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003118_PyDict_SizeOf(PyDictObject *mp)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003119{
Victor Stinner742da042016-09-07 17:40:12 -07003120 Py_ssize_t size, usable, res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003121
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003122 size = DK_SIZE(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07003123 usable = USABLE_FRACTION(size);
3124
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02003125 res = _PyObject_SIZE(Py_TYPE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003126 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07003127 res += usable * sizeof(PyObject*);
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003128 /* If the dictionary is split, the keys portion is accounted-for
3129 in the type object. */
3130 if (mp->ma_keys->dk_refcnt == 1)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003131 res += (sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003132 + DK_IXSIZE(mp->ma_keys) * size
3133 + sizeof(PyDictKeyEntry) * usable);
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003134 return res;
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003135}
3136
3137Py_ssize_t
3138_PyDict_KeysSize(PyDictKeysObject *keys)
3139{
Victor Stinner98ee9d52016-09-08 09:33:56 -07003140 return (sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003141 + DK_IXSIZE(keys) * DK_SIZE(keys)
3142 + USABLE_FRACTION(DK_SIZE(keys)) * sizeof(PyDictKeyEntry));
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003143}
3144
doko@ubuntu.com17210f52016-01-14 14:04:59 +01003145static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303146dict_sizeof(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003147{
3148 return PyLong_FromSsize_t(_PyDict_SizeOf(mp));
3149}
3150
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003151PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
3152
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003153PyDoc_STRVAR(sizeof__doc__,
3154"D.__sizeof__() -> size of D in memory, in bytes");
3155
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003156PyDoc_STRVAR(update__doc__,
Brett Cannonf2754162013-05-11 14:46:48 -04003157"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n\
3158If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]\n\
3159If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n\
3160In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00003161
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003162PyDoc_STRVAR(clear__doc__,
3163"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00003164
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003165PyDoc_STRVAR(copy__doc__,
3166"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00003167
Guido van Rossumb90c8482007-02-10 01:11:45 +00003168/* Forward */
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303169static PyObject *dictkeys_new(PyObject *, PyObject *);
3170static PyObject *dictitems_new(PyObject *, PyObject *);
3171static PyObject *dictvalues_new(PyObject *, PyObject *);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003172
Guido van Rossum45c85d12007-07-27 16:31:40 +00003173PyDoc_STRVAR(keys__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 "D.keys() -> a set-like object providing a view on D's keys");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003175PyDoc_STRVAR(items__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 "D.items() -> a set-like object providing a view on D's items");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003177PyDoc_STRVAR(values__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 "D.values() -> an object providing a view on D's values");
Guido van Rossumb90c8482007-02-10 01:11:45 +00003179
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003180static PyMethodDef mapp_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -07003181 DICT___CONTAINS___METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003182 {"__getitem__", (PyCFunction)(void(*)(void))dict_subscript, METH_O | METH_COEXIST,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 getitem__doc__},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003184 {"__sizeof__", (PyCFunction)(void(*)(void))dict_sizeof, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 sizeof__doc__},
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01003186 DICT_GET_METHODDEF
3187 DICT_SETDEFAULT_METHODDEF
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003188 DICT_POP_METHODDEF
3189 DICT_POPITEM_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303190 {"keys", dictkeys_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 keys__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303192 {"items", dictitems_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 items__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303194 {"values", dictvalues_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 values__doc__},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003196 {"update", (PyCFunction)(void(*)(void))dict_update, METH_VARARGS | METH_KEYWORDS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 update__doc__},
Larry Hastings5c661892014-01-24 06:17:25 -08003198 DICT_FROMKEYS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
3200 clear__doc__},
3201 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
3202 copy__doc__},
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003203 DICT___REVERSED___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003205};
3206
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00003207/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00003208int
3209PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003210{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003211 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07003212 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09003214 PyObject *value;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003217 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 hash = PyObject_Hash(key);
3219 if (hash == -1)
3220 return -1;
3221 }
INADA Naoki778928b2017-08-03 23:45:15 +09003222 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07003223 if (ix == DKIX_ERROR)
3224 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09003225 return (ix != DKIX_EMPTY && value != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003226}
3227
Thomas Wouterscf297e42007-02-23 15:07:44 +00003228/* Internal version of PyDict_Contains used when the hash value is already known */
3229int
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003230_PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00003231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09003233 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -07003234 Py_ssize_t ix;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003235
INADA Naoki778928b2017-08-03 23:45:15 +09003236 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07003237 if (ix == DKIX_ERROR)
3238 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09003239 return (ix != DKIX_EMPTY && value != NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00003240}
3241
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003242/* Hack to implement "key in dict" */
3243static PySequenceMethods dict_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003244 0, /* sq_length */
3245 0, /* sq_concat */
3246 0, /* sq_repeat */
3247 0, /* sq_item */
3248 0, /* sq_slice */
3249 0, /* sq_ass_item */
3250 0, /* sq_ass_slice */
3251 PyDict_Contains, /* sq_contains */
3252 0, /* sq_inplace_concat */
3253 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003254};
3255
Guido van Rossum09e563a2001-05-01 12:10:21 +00003256static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003257dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 PyObject *self;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003260 PyDictObject *d;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 assert(type != NULL && type->tp_alloc != NULL);
3263 self = type->tp_alloc(type, 0);
Victor Stinnera9f61a52013-07-16 22:17:26 +02003264 if (self == NULL)
3265 return NULL;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003266 d = (PyDictObject *)self;
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003267
Victor Stinnera9f61a52013-07-16 22:17:26 +02003268 /* The object has been implicitly tracked by tp_alloc */
3269 if (type == &PyDict_Type)
3270 _PyObject_GC_UNTRACK(d);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003271
3272 d->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07003273 d->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07003274 d->ma_keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003275 if (d->ma_keys == NULL) {
3276 Py_DECREF(self);
3277 return NULL;
3278 }
Victor Stinner0fc91ee2019-04-12 21:51:34 +02003279 ASSERT_CONSISTENT(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 return self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003281}
3282
Tim Peters25786c02001-09-02 08:22:48 +00003283static int
3284dict_init(PyObject *self, PyObject *args, PyObject *kwds)
3285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00003287}
3288
Tim Peters6d6c1a32001-08-02 04:15:00 +00003289static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003290dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00003291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003293}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003294
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003295PyDoc_STRVAR(dictionary_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00003296"dict() -> new empty dictionary\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00003297"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003298" (key, value) pairs\n"
3299"dict(iterable) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00003300" d = {}\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003301" for k, v in iterable:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00003302" d[k] = v\n"
3303"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
3304" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00003305
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003306PyTypeObject PyDict_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3308 "dict",
3309 sizeof(PyDictObject),
3310 0,
3311 (destructor)dict_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003312 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 0, /* tp_getattr */
3314 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003315 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 (reprfunc)dict_repr, /* tp_repr */
3317 0, /* tp_as_number */
3318 &dict_as_sequence, /* tp_as_sequence */
3319 &dict_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003320 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 0, /* tp_call */
3322 0, /* tp_str */
3323 PyObject_GenericGetAttr, /* tp_getattro */
3324 0, /* tp_setattro */
3325 0, /* tp_as_buffer */
3326 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3327 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
3328 dictionary_doc, /* tp_doc */
3329 dict_traverse, /* tp_traverse */
3330 dict_tp_clear, /* tp_clear */
3331 dict_richcompare, /* tp_richcompare */
3332 0, /* tp_weaklistoffset */
3333 (getiterfunc)dict_iter, /* tp_iter */
3334 0, /* tp_iternext */
3335 mapp_methods, /* tp_methods */
3336 0, /* tp_members */
3337 0, /* tp_getset */
3338 0, /* tp_base */
3339 0, /* tp_dict */
3340 0, /* tp_descr_get */
3341 0, /* tp_descr_set */
3342 0, /* tp_dictoffset */
3343 dict_init, /* tp_init */
3344 PyType_GenericAlloc, /* tp_alloc */
3345 dict_new, /* tp_new */
3346 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003347};
3348
Victor Stinner3c1e4812012-03-26 22:10:51 +02003349PyObject *
3350_PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
3351{
3352 PyObject *kv;
3353 kv = _PyUnicode_FromId(key); /* borrowed */
Victor Stinner5b3b1002013-07-22 23:50:57 +02003354 if (kv == NULL) {
3355 PyErr_Clear();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003356 return NULL;
Victor Stinner5b3b1002013-07-22 23:50:57 +02003357 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003358 return PyDict_GetItem(dp, kv);
3359}
3360
Guido van Rossum3cca2451997-05-16 14:23:33 +00003361/* For backward compatibility with old dictionary interface */
3362
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003363PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003364PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 PyObject *kv, *rv;
3367 kv = PyUnicode_FromString(key);
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003368 if (kv == NULL) {
3369 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 return NULL;
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003371 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 rv = PyDict_GetItem(v, kv);
3373 Py_DECREF(kv);
3374 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003375}
3376
3377int
Victor Stinner3c1e4812012-03-26 22:10:51 +02003378_PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
3379{
3380 PyObject *kv;
3381 kv = _PyUnicode_FromId(key); /* borrowed */
3382 if (kv == NULL)
3383 return -1;
3384 return PyDict_SetItem(v, kv, item);
3385}
3386
3387int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003388PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 PyObject *kv;
3391 int err;
3392 kv = PyUnicode_FromString(key);
3393 if (kv == NULL)
3394 return -1;
3395 PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
3396 err = PyDict_SetItem(v, kv, item);
3397 Py_DECREF(kv);
3398 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003399}
3400
3401int
Victor Stinner5fd2e5a2013-11-06 18:58:22 +01003402_PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
3403{
3404 PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
3405 if (kv == NULL)
3406 return -1;
3407 return PyDict_DelItem(v, kv);
3408}
3409
3410int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003411PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 PyObject *kv;
3414 int err;
3415 kv = PyUnicode_FromString(key);
3416 if (kv == NULL)
3417 return -1;
3418 err = PyDict_DelItem(v, kv);
3419 Py_DECREF(kv);
3420 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003421}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003422
Raymond Hettinger019a1482004-03-18 02:41:19 +00003423/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003424
3425typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 PyObject_HEAD
3427 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
3428 Py_ssize_t di_used;
3429 Py_ssize_t di_pos;
3430 PyObject* di_result; /* reusable result tuple for iteritems */
3431 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003432} dictiterobject;
3433
3434static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003435dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 dictiterobject *di;
3438 di = PyObject_GC_New(dictiterobject, itertype);
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003439 if (di == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 return NULL;
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003441 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 Py_INCREF(dict);
3443 di->di_dict = dict;
3444 di->di_used = dict->ma_used;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003445 di->len = dict->ma_used;
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003446 if ((itertype == &PyDictRevIterKey_Type ||
3447 itertype == &PyDictRevIterItem_Type ||
3448 itertype == &PyDictRevIterValue_Type) && dict->ma_used) {
3449 di->di_pos = dict->ma_keys->dk_nentries - 1;
3450 }
3451 else {
3452 di->di_pos = 0;
3453 }
3454 if (itertype == &PyDictIterItem_Type ||
3455 itertype == &PyDictRevIterItem_Type) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
3457 if (di->di_result == NULL) {
3458 Py_DECREF(di);
3459 return NULL;
3460 }
3461 }
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003462 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 di->di_result = NULL;
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003464 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003465 _PyObject_GC_TRACK(di);
3466 return (PyObject *)di;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003467}
3468
3469static void
3470dictiter_dealloc(dictiterobject *di)
3471{
INADA Naokia6296d32017-08-24 14:55:17 +09003472 /* bpo-31095: UnTrack is needed before calling any callbacks */
3473 _PyObject_GC_UNTRACK(di);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003474 Py_XDECREF(di->di_dict);
3475 Py_XDECREF(di->di_result);
3476 PyObject_GC_Del(di);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003477}
3478
3479static int
3480dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
3481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 Py_VISIT(di->di_dict);
3483 Py_VISIT(di->di_result);
3484 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003485}
3486
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003487static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303488dictiter_len(dictiterobject *di, PyObject *Py_UNUSED(ignored))
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 Py_ssize_t len = 0;
3491 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
3492 len = di->len;
3493 return PyLong_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003494}
3495
Guido van Rossumb90c8482007-02-10 01:11:45 +00003496PyDoc_STRVAR(length_hint_doc,
3497 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003498
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003499static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303500dictiter_reduce(dictiterobject *di, PyObject *Py_UNUSED(ignored));
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003501
3502PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3503
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003504static PyMethodDef dictiter_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003505 {"__length_hint__", (PyCFunction)(void(*)(void))dictiter_len, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 length_hint_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003507 {"__reduce__", (PyCFunction)(void(*)(void))dictiter_reduce, METH_NOARGS,
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003508 reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003510};
3511
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003512static PyObject*
3513dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00003514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 PyObject *key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003516 Py_ssize_t i;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003517 PyDictKeysObject *k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 PyDictObject *d = di->di_dict;
Guido van Rossum213c7a62001-04-23 14:08:49 +00003519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 if (d == NULL)
3521 return NULL;
3522 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00003523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 if (di->di_used != d->ma_used) {
3525 PyErr_SetString(PyExc_RuntimeError,
3526 "dictionary changed size during iteration");
3527 di->di_used = -1; /* Make this state sticky */
3528 return NULL;
3529 }
Guido van Rossum2147df72002-07-16 20:30:22 +00003530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 i = di->di_pos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003532 k = d->ma_keys;
INADA Naokica2d8be2016-11-04 16:59:10 +09003533 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003534 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003535 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003536 goto fail;
3537 key = DK_ENTRIES(k)[i].me_key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003538 assert(d->ma_values[i] != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003539 }
3540 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003541 Py_ssize_t n = k->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003542 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
3543 while (i < n && entry_ptr->me_value == NULL) {
3544 entry_ptr++;
3545 i++;
3546 }
3547 if (i >= n)
3548 goto fail;
3549 key = entry_ptr->me_key;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003550 }
Thomas Perl796cc6e2019-03-28 07:03:25 +01003551 // We found an element (key), but did not expect it
3552 if (di->len == 0) {
3553 PyErr_SetString(PyExc_RuntimeError,
3554 "dictionary keys changed during iteration");
3555 goto fail;
3556 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557 di->di_pos = i+1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 di->len--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 Py_INCREF(key);
3560 return key;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003561
3562fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003564 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003566}
3567
Raymond Hettinger019a1482004-03-18 02:41:19 +00003568PyTypeObject PyDictIterKey_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3570 "dict_keyiterator", /* tp_name */
3571 sizeof(dictiterobject), /* tp_basicsize */
3572 0, /* tp_itemsize */
3573 /* methods */
3574 (destructor)dictiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003575 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 0, /* tp_getattr */
3577 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003578 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 0, /* tp_repr */
3580 0, /* tp_as_number */
3581 0, /* tp_as_sequence */
3582 0, /* tp_as_mapping */
3583 0, /* tp_hash */
3584 0, /* tp_call */
3585 0, /* tp_str */
3586 PyObject_GenericGetAttr, /* tp_getattro */
3587 0, /* tp_setattro */
3588 0, /* tp_as_buffer */
3589 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3590 0, /* tp_doc */
3591 (traverseproc)dictiter_traverse, /* tp_traverse */
3592 0, /* tp_clear */
3593 0, /* tp_richcompare */
3594 0, /* tp_weaklistoffset */
3595 PyObject_SelfIter, /* tp_iter */
3596 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
3597 dictiter_methods, /* tp_methods */
3598 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003599};
3600
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003601static PyObject *
3602dictiter_iternextvalue(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 PyObject *value;
INADA Naokica2d8be2016-11-04 16:59:10 +09003605 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 if (d == NULL)
3609 return NULL;
3610 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003612 if (di->di_used != d->ma_used) {
3613 PyErr_SetString(PyExc_RuntimeError,
3614 "dictionary changed size during iteration");
3615 di->di_used = -1; /* Make this state sticky */
3616 return NULL;
3617 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 i = di->di_pos;
INADA Naokica2d8be2016-11-04 16:59:10 +09003620 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003621 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003622 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003623 goto fail;
INADA Naokica2d8be2016-11-04 16:59:10 +09003624 value = d->ma_values[i];
3625 assert(value != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003626 }
3627 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003628 Py_ssize_t n = d->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003629 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3630 while (i < n && entry_ptr->me_value == NULL) {
3631 entry_ptr++;
3632 i++;
3633 }
3634 if (i >= n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 goto fail;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003636 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 }
Thomas Perlb8311cf2019-04-02 11:30:10 +02003638 // We found an element, but did not expect it
3639 if (di->len == 0) {
3640 PyErr_SetString(PyExc_RuntimeError,
3641 "dictionary keys changed during iteration");
3642 goto fail;
3643 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 di->di_pos = i+1;
3645 di->len--;
3646 Py_INCREF(value);
3647 return value;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003648
3649fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003651 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003653}
3654
3655PyTypeObject PyDictIterValue_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3657 "dict_valueiterator", /* tp_name */
3658 sizeof(dictiterobject), /* tp_basicsize */
3659 0, /* tp_itemsize */
3660 /* methods */
3661 (destructor)dictiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003662 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 0, /* tp_getattr */
3664 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003665 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 0, /* tp_repr */
3667 0, /* tp_as_number */
3668 0, /* tp_as_sequence */
3669 0, /* tp_as_mapping */
3670 0, /* tp_hash */
3671 0, /* tp_call */
3672 0, /* tp_str */
3673 PyObject_GenericGetAttr, /* tp_getattro */
3674 0, /* tp_setattro */
3675 0, /* tp_as_buffer */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003676 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003677 0, /* tp_doc */
3678 (traverseproc)dictiter_traverse, /* tp_traverse */
3679 0, /* tp_clear */
3680 0, /* tp_richcompare */
3681 0, /* tp_weaklistoffset */
3682 PyObject_SelfIter, /* tp_iter */
3683 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
3684 dictiter_methods, /* tp_methods */
3685 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003686};
3687
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003688static PyObject *
3689dictiter_iternextitem(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003690{
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003691 PyObject *key, *value, *result;
INADA Naokica2d8be2016-11-04 16:59:10 +09003692 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 if (d == NULL)
3696 return NULL;
3697 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 if (di->di_used != d->ma_used) {
3700 PyErr_SetString(PyExc_RuntimeError,
3701 "dictionary changed size during iteration");
3702 di->di_used = -1; /* Make this state sticky */
3703 return NULL;
3704 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003706 i = di->di_pos;
INADA Naokica2d8be2016-11-04 16:59:10 +09003707 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003708 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003709 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003710 goto fail;
3711 key = DK_ENTRIES(d->ma_keys)[i].me_key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003712 value = d->ma_values[i];
3713 assert(value != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003714 }
3715 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003716 Py_ssize_t n = d->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003717 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3718 while (i < n && entry_ptr->me_value == NULL) {
3719 entry_ptr++;
3720 i++;
3721 }
3722 if (i >= n)
3723 goto fail;
3724 key = entry_ptr->me_key;
3725 value = entry_ptr->me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003726 }
Thomas Perlb8311cf2019-04-02 11:30:10 +02003727 // We found an element, but did not expect it
3728 if (di->len == 0) {
3729 PyErr_SetString(PyExc_RuntimeError,
3730 "dictionary keys changed during iteration");
3731 goto fail;
3732 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003733 di->di_pos = i+1;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003734 di->len--;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003735 Py_INCREF(key);
3736 Py_INCREF(value);
3737 result = di->di_result;
3738 if (Py_REFCNT(result) == 1) {
3739 PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
3740 PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
3741 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3742 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 Py_INCREF(result);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003744 Py_DECREF(oldkey);
3745 Py_DECREF(oldvalue);
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003746 }
3747 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 result = PyTuple_New(2);
3749 if (result == NULL)
3750 return NULL;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003751 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3752 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003753 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003755
3756fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003758 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003759 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003760}
3761
3762PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3764 "dict_itemiterator", /* tp_name */
3765 sizeof(dictiterobject), /* tp_basicsize */
3766 0, /* tp_itemsize */
3767 /* methods */
3768 (destructor)dictiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003769 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003770 0, /* tp_getattr */
3771 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003772 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 0, /* tp_repr */
3774 0, /* tp_as_number */
3775 0, /* tp_as_sequence */
3776 0, /* tp_as_mapping */
3777 0, /* tp_hash */
3778 0, /* tp_call */
3779 0, /* tp_str */
3780 PyObject_GenericGetAttr, /* tp_getattro */
3781 0, /* tp_setattro */
3782 0, /* tp_as_buffer */
3783 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3784 0, /* tp_doc */
3785 (traverseproc)dictiter_traverse, /* tp_traverse */
3786 0, /* tp_clear */
3787 0, /* tp_richcompare */
3788 0, /* tp_weaklistoffset */
3789 PyObject_SelfIter, /* tp_iter */
3790 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
3791 dictiter_methods, /* tp_methods */
3792 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003793};
Guido van Rossumb90c8482007-02-10 01:11:45 +00003794
3795
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003796/* dictreviter */
3797
3798static PyObject *
3799dictreviter_iternext(dictiterobject *di)
3800{
3801 PyDictObject *d = di->di_dict;
3802
3803 if (d == NULL) {
3804 return NULL;
3805 }
3806 assert (PyDict_Check(d));
3807
3808 if (di->di_used != d->ma_used) {
3809 PyErr_SetString(PyExc_RuntimeError,
3810 "dictionary changed size during iteration");
3811 di->di_used = -1; /* Make this state sticky */
3812 return NULL;
3813 }
3814
3815 Py_ssize_t i = di->di_pos;
3816 PyDictKeysObject *k = d->ma_keys;
3817 PyObject *key, *value, *result;
3818
3819 if (d->ma_values) {
3820 if (i < 0) {
3821 goto fail;
3822 }
3823 key = DK_ENTRIES(k)[i].me_key;
3824 value = d->ma_values[i];
3825 assert (value != NULL);
3826 }
3827 else {
3828 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
3829 while (i >= 0 && entry_ptr->me_value == NULL) {
3830 entry_ptr--;
3831 i--;
3832 }
3833 if (i < 0) {
3834 goto fail;
3835 }
3836 key = entry_ptr->me_key;
3837 value = entry_ptr->me_value;
3838 }
3839 di->di_pos = i-1;
3840 di->len--;
3841
3842 if (Py_TYPE(di) == &PyDictRevIterKey_Type) {
3843 Py_INCREF(key);
3844 return key;
3845 }
3846 else if (Py_TYPE(di) == &PyDictRevIterValue_Type) {
3847 Py_INCREF(value);
3848 return value;
3849 }
3850 else if (Py_TYPE(di) == &PyDictRevIterItem_Type) {
3851 Py_INCREF(key);
3852 Py_INCREF(value);
3853 result = di->di_result;
3854 if (Py_REFCNT(result) == 1) {
3855 PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
3856 PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
3857 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3858 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
3859 Py_INCREF(result);
3860 Py_DECREF(oldkey);
3861 Py_DECREF(oldvalue);
3862 }
3863 else {
3864 result = PyTuple_New(2);
3865 if (result == NULL) {
3866 return NULL;
3867 }
3868 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3869 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
3870 }
3871 return result;
3872 }
3873 else {
3874 Py_UNREACHABLE();
3875 }
3876
3877fail:
3878 di->di_dict = NULL;
3879 Py_DECREF(d);
3880 return NULL;
3881}
3882
3883PyTypeObject PyDictRevIterKey_Type = {
3884 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3885 "dict_reversekeyiterator",
3886 sizeof(dictiterobject),
3887 .tp_dealloc = (destructor)dictiter_dealloc,
3888 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3889 .tp_traverse = (traverseproc)dictiter_traverse,
3890 .tp_iter = PyObject_SelfIter,
3891 .tp_iternext = (iternextfunc)dictreviter_iternext,
3892 .tp_methods = dictiter_methods
3893};
3894
3895
3896/*[clinic input]
3897dict.__reversed__
3898
3899Return a reverse iterator over the dict keys.
3900[clinic start generated code]*/
3901
3902static PyObject *
3903dict___reversed___impl(PyDictObject *self)
3904/*[clinic end generated code: output=e674483336d1ed51 input=23210ef3477d8c4d]*/
3905{
3906 assert (PyDict_Check(self));
3907 return dictiter_new(self, &PyDictRevIterKey_Type);
3908}
3909
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003910static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303911dictiter_reduce(dictiterobject *di, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003912{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003913 _Py_IDENTIFIER(iter);
Sergey Fedoseev63958442018-10-20 05:43:33 +05003914 /* copy the iterator state */
3915 dictiterobject tmp = *di;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003916 Py_XINCREF(tmp.di_dict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003917
Sergey Fedoseev63958442018-10-20 05:43:33 +05003918 PyObject *list = PySequence_List((PyObject*)&tmp);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003919 Py_XDECREF(tmp.di_dict);
Sergey Fedoseev63958442018-10-20 05:43:33 +05003920 if (list == NULL) {
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003921 return NULL;
3922 }
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003923 return Py_BuildValue("N(N)", _PyEval_GetBuiltinId(&PyId_iter), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003924}
3925
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003926PyTypeObject PyDictRevIterItem_Type = {
3927 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3928 "dict_reverseitemiterator",
3929 sizeof(dictiterobject),
3930 .tp_dealloc = (destructor)dictiter_dealloc,
3931 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3932 .tp_traverse = (traverseproc)dictiter_traverse,
3933 .tp_iter = PyObject_SelfIter,
3934 .tp_iternext = (iternextfunc)dictreviter_iternext,
3935 .tp_methods = dictiter_methods
3936};
3937
3938PyTypeObject PyDictRevIterValue_Type = {
3939 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3940 "dict_reversevalueiterator",
3941 sizeof(dictiterobject),
3942 .tp_dealloc = (destructor)dictiter_dealloc,
3943 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3944 .tp_traverse = (traverseproc)dictiter_traverse,
3945 .tp_iter = PyObject_SelfIter,
3946 .tp_iternext = (iternextfunc)dictreviter_iternext,
3947 .tp_methods = dictiter_methods
3948};
3949
Guido van Rossum3ac67412007-02-10 18:55:06 +00003950/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003951/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00003952/***********************************************/
3953
Guido van Rossumb90c8482007-02-10 01:11:45 +00003954/* The instance lay-out is the same for all three; but the type differs. */
3955
Guido van Rossumb90c8482007-02-10 01:11:45 +00003956static void
Eric Snow96c6af92015-05-29 22:21:39 -06003957dictview_dealloc(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003958{
INADA Naokia6296d32017-08-24 14:55:17 +09003959 /* bpo-31095: UnTrack is needed before calling any callbacks */
3960 _PyObject_GC_UNTRACK(dv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 Py_XDECREF(dv->dv_dict);
3962 PyObject_GC_Del(dv);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003963}
3964
3965static int
Eric Snow96c6af92015-05-29 22:21:39 -06003966dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003968 Py_VISIT(dv->dv_dict);
3969 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003970}
3971
Guido van Rossum83825ac2007-02-10 04:54:19 +00003972static Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003973dictview_len(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 Py_ssize_t len = 0;
3976 if (dv->dv_dict != NULL)
3977 len = dv->dv_dict->ma_used;
3978 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003979}
3980
Eric Snow96c6af92015-05-29 22:21:39 -06003981PyObject *
3982_PyDictView_New(PyObject *dict, PyTypeObject *type)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003983{
Eric Snow96c6af92015-05-29 22:21:39 -06003984 _PyDictViewObject *dv;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003985 if (dict == NULL) {
3986 PyErr_BadInternalCall();
3987 return NULL;
3988 }
3989 if (!PyDict_Check(dict)) {
3990 /* XXX Get rid of this restriction later */
3991 PyErr_Format(PyExc_TypeError,
3992 "%s() requires a dict argument, not '%s'",
3993 type->tp_name, dict->ob_type->tp_name);
3994 return NULL;
3995 }
Eric Snow96c6af92015-05-29 22:21:39 -06003996 dv = PyObject_GC_New(_PyDictViewObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 if (dv == NULL)
3998 return NULL;
3999 Py_INCREF(dict);
4000 dv->dv_dict = (PyDictObject *)dict;
4001 _PyObject_GC_TRACK(dv);
4002 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00004003}
4004
Neal Norwitze36f2ba2007-02-26 23:12:28 +00004005/* TODO(guido): The views objects are not complete:
4006
4007 * support more set operations
4008 * support arbitrary mappings?
4009 - either these should be static or exported in dictobject.h
4010 - if public then they should probably be in builtins
4011*/
4012
Guido van Rossumaac530c2007-08-24 22:33:45 +00004013/* Return 1 if self is a subset of other, iterating over self;
4014 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00004015static int
4016all_contained_in(PyObject *self, PyObject *other)
4017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 PyObject *iter = PyObject_GetIter(self);
4019 int ok = 1;
Guido van Rossumd9214d12007-02-12 02:23:40 +00004020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004021 if (iter == NULL)
4022 return -1;
4023 for (;;) {
4024 PyObject *next = PyIter_Next(iter);
4025 if (next == NULL) {
4026 if (PyErr_Occurred())
4027 ok = -1;
4028 break;
4029 }
4030 ok = PySequence_Contains(other, next);
4031 Py_DECREF(next);
4032 if (ok <= 0)
4033 break;
4034 }
4035 Py_DECREF(iter);
4036 return ok;
Guido van Rossumd9214d12007-02-12 02:23:40 +00004037}
4038
4039static PyObject *
4040dictview_richcompare(PyObject *self, PyObject *other, int op)
4041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004042 Py_ssize_t len_self, len_other;
4043 int ok;
4044 PyObject *result;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 assert(self != NULL);
4047 assert(PyDictViewSet_Check(self));
4048 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00004049
Brian Curtindfc80e32011-08-10 20:28:54 -05004050 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
4051 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 len_self = PyObject_Size(self);
4054 if (len_self < 0)
4055 return NULL;
4056 len_other = PyObject_Size(other);
4057 if (len_other < 0)
4058 return NULL;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004060 ok = 0;
4061 switch(op) {
Guido van Rossumaac530c2007-08-24 22:33:45 +00004062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004063 case Py_NE:
4064 case Py_EQ:
4065 if (len_self == len_other)
4066 ok = all_contained_in(self, other);
4067 if (op == Py_NE && ok >= 0)
4068 ok = !ok;
4069 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 case Py_LT:
4072 if (len_self < len_other)
4073 ok = all_contained_in(self, other);
4074 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004076 case Py_LE:
4077 if (len_self <= len_other)
4078 ok = all_contained_in(self, other);
4079 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004081 case Py_GT:
4082 if (len_self > len_other)
4083 ok = all_contained_in(other, self);
4084 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 case Py_GE:
4087 if (len_self >= len_other)
4088 ok = all_contained_in(other, self);
4089 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004091 }
4092 if (ok < 0)
4093 return NULL;
4094 result = ok ? Py_True : Py_False;
4095 Py_INCREF(result);
4096 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00004097}
4098
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00004099static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004100dictview_repr(_PyDictViewObject *dv)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00004101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 PyObject *seq;
bennorthd7773d92018-01-26 15:46:01 +00004103 PyObject *result = NULL;
4104 Py_ssize_t rc;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00004105
bennorthd7773d92018-01-26 15:46:01 +00004106 rc = Py_ReprEnter((PyObject *)dv);
4107 if (rc != 0) {
4108 return rc > 0 ? PyUnicode_FromString("...") : NULL;
4109 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 seq = PySequence_List((PyObject *)dv);
bennorthd7773d92018-01-26 15:46:01 +00004111 if (seq == NULL) {
4112 goto Done;
4113 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004114 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
4115 Py_DECREF(seq);
bennorthd7773d92018-01-26 15:46:01 +00004116
4117Done:
4118 Py_ReprLeave((PyObject *)dv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 return result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00004120}
4121
Guido van Rossum3ac67412007-02-10 18:55:06 +00004122/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004123
4124static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004125dictkeys_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 if (dv->dv_dict == NULL) {
4128 Py_RETURN_NONE;
4129 }
4130 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00004131}
4132
4133static int
Eric Snow96c6af92015-05-29 22:21:39 -06004134dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00004135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 if (dv->dv_dict == NULL)
4137 return 0;
4138 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004139}
4140
Guido van Rossum83825ac2007-02-10 04:54:19 +00004141static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004142 (lenfunc)dictview_len, /* sq_length */
4143 0, /* sq_concat */
4144 0, /* sq_repeat */
4145 0, /* sq_item */
4146 0, /* sq_slice */
4147 0, /* sq_ass_item */
4148 0, /* sq_ass_slice */
4149 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004150};
4151
Guido van Rossum523259b2007-08-24 23:41:22 +00004152static PyObject*
4153dictviews_sub(PyObject* self, PyObject *other)
4154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004155 PyObject *result = PySet_New(self);
4156 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004157 _Py_IDENTIFIER(difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 if (result == NULL)
4160 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004161
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02004162 tmp = _PyObject_CallMethodIdOneArg(result, &PyId_difference_update, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 if (tmp == NULL) {
4164 Py_DECREF(result);
4165 return NULL;
4166 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004168 Py_DECREF(tmp);
4169 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004170}
4171
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004172PyObject*
4173_PyDictView_Intersect(PyObject* self, PyObject *other)
Guido van Rossum523259b2007-08-24 23:41:22 +00004174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004175 PyObject *result = PySet_New(self);
4176 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004177 _Py_IDENTIFIER(intersection_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 if (result == NULL)
4180 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004181
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02004182 tmp = _PyObject_CallMethodIdOneArg(result, &PyId_intersection_update, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004183 if (tmp == NULL) {
4184 Py_DECREF(result);
4185 return NULL;
4186 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 Py_DECREF(tmp);
4189 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004190}
4191
4192static PyObject*
4193dictviews_or(PyObject* self, PyObject *other)
4194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004195 PyObject *result = PySet_New(self);
4196 PyObject *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02004197 _Py_IDENTIFIER(update);
Victor Stinnerd1a9cc22011-10-13 22:51:17 +02004198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004199 if (result == NULL)
4200 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004201
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02004202 tmp = _PyObject_CallMethodIdOneArg(result, &PyId_update, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004203 if (tmp == NULL) {
4204 Py_DECREF(result);
4205 return NULL;
4206 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 Py_DECREF(tmp);
4209 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004210}
4211
4212static PyObject*
4213dictviews_xor(PyObject* self, PyObject *other)
4214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215 PyObject *result = PySet_New(self);
4216 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004217 _Py_IDENTIFIER(symmetric_difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 if (result == NULL)
4220 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004221
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02004222 tmp = _PyObject_CallMethodIdOneArg(result, &PyId_symmetric_difference_update, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004223 if (tmp == NULL) {
4224 Py_DECREF(result);
4225 return NULL;
4226 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 Py_DECREF(tmp);
4229 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004230}
4231
4232static PyNumberMethods dictviews_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004233 0, /*nb_add*/
4234 (binaryfunc)dictviews_sub, /*nb_subtract*/
4235 0, /*nb_multiply*/
4236 0, /*nb_remainder*/
4237 0, /*nb_divmod*/
4238 0, /*nb_power*/
4239 0, /*nb_negative*/
4240 0, /*nb_positive*/
4241 0, /*nb_absolute*/
4242 0, /*nb_bool*/
4243 0, /*nb_invert*/
4244 0, /*nb_lshift*/
4245 0, /*nb_rshift*/
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004246 (binaryfunc)_PyDictView_Intersect, /*nb_and*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 (binaryfunc)dictviews_xor, /*nb_xor*/
4248 (binaryfunc)dictviews_or, /*nb_or*/
Guido van Rossum523259b2007-08-24 23:41:22 +00004249};
4250
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004251static PyObject*
4252dictviews_isdisjoint(PyObject *self, PyObject *other)
4253{
4254 PyObject *it;
4255 PyObject *item = NULL;
4256
4257 if (self == other) {
Eric Snow96c6af92015-05-29 22:21:39 -06004258 if (dictview_len((_PyDictViewObject *)self) == 0)
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004259 Py_RETURN_TRUE;
4260 else
4261 Py_RETURN_FALSE;
4262 }
4263
4264 /* Iterate over the shorter object (only if other is a set,
4265 * because PySequence_Contains may be expensive otherwise): */
4266 if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
Eric Snow96c6af92015-05-29 22:21:39 -06004267 Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004268 Py_ssize_t len_other = PyObject_Size(other);
4269 if (len_other == -1)
4270 return NULL;
4271
4272 if ((len_other > len_self)) {
4273 PyObject *tmp = other;
4274 other = self;
4275 self = tmp;
4276 }
4277 }
4278
4279 it = PyObject_GetIter(other);
4280 if (it == NULL)
4281 return NULL;
4282
4283 while ((item = PyIter_Next(it)) != NULL) {
4284 int contains = PySequence_Contains(self, item);
4285 Py_DECREF(item);
4286 if (contains == -1) {
4287 Py_DECREF(it);
4288 return NULL;
4289 }
4290
4291 if (contains) {
4292 Py_DECREF(it);
4293 Py_RETURN_FALSE;
4294 }
4295 }
4296 Py_DECREF(it);
4297 if (PyErr_Occurred())
4298 return NULL; /* PyIter_Next raised an exception. */
4299 Py_RETURN_TRUE;
4300}
4301
4302PyDoc_STRVAR(isdisjoint_doc,
4303"Return True if the view and the given iterable have a null intersection.");
4304
Serhiy Storchaka81524022018-11-27 13:05:02 +02004305static PyObject* dictkeys_reversed(_PyDictViewObject *dv, PyObject *Py_UNUSED(ignored));
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004306
4307PyDoc_STRVAR(reversed_keys_doc,
4308"Return a reverse iterator over the dict keys.");
4309
Guido van Rossumb90c8482007-02-10 01:11:45 +00004310static PyMethodDef dictkeys_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004311 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4312 isdisjoint_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02004313 {"__reversed__", (PyCFunction)(void(*)(void))dictkeys_reversed, METH_NOARGS,
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004314 reversed_keys_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004315 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004316};
4317
4318PyTypeObject PyDictKeys_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004319 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4320 "dict_keys", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004321 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004322 0, /* tp_itemsize */
4323 /* methods */
4324 (destructor)dictview_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004325 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 0, /* tp_getattr */
4327 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004328 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004329 (reprfunc)dictview_repr, /* tp_repr */
4330 &dictviews_as_number, /* tp_as_number */
4331 &dictkeys_as_sequence, /* tp_as_sequence */
4332 0, /* tp_as_mapping */
4333 0, /* tp_hash */
4334 0, /* tp_call */
4335 0, /* tp_str */
4336 PyObject_GenericGetAttr, /* tp_getattro */
4337 0, /* tp_setattro */
4338 0, /* tp_as_buffer */
4339 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4340 0, /* tp_doc */
4341 (traverseproc)dictview_traverse, /* tp_traverse */
4342 0, /* tp_clear */
4343 dictview_richcompare, /* tp_richcompare */
4344 0, /* tp_weaklistoffset */
4345 (getiterfunc)dictkeys_iter, /* tp_iter */
4346 0, /* tp_iternext */
4347 dictkeys_methods, /* tp_methods */
4348 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004349};
4350
4351static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304352dictkeys_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004353{
Eric Snow96c6af92015-05-29 22:21:39 -06004354 return _PyDictView_New(dict, &PyDictKeys_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004355}
4356
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004357static PyObject *
Serhiy Storchaka81524022018-11-27 13:05:02 +02004358dictkeys_reversed(_PyDictViewObject *dv, PyObject *Py_UNUSED(ignored))
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004359{
4360 if (dv->dv_dict == NULL) {
4361 Py_RETURN_NONE;
4362 }
4363 return dictiter_new(dv->dv_dict, &PyDictRevIterKey_Type);
4364}
4365
Guido van Rossum3ac67412007-02-10 18:55:06 +00004366/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004367
4368static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004369dictitems_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 if (dv->dv_dict == NULL) {
4372 Py_RETURN_NONE;
4373 }
4374 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00004375}
4376
4377static int
Eric Snow96c6af92015-05-29 22:21:39 -06004378dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00004379{
Serhiy Storchaka753bca32017-05-20 12:30:02 +03004380 int result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004381 PyObject *key, *value, *found;
4382 if (dv->dv_dict == NULL)
4383 return 0;
4384 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
4385 return 0;
4386 key = PyTuple_GET_ITEM(obj, 0);
4387 value = PyTuple_GET_ITEM(obj, 1);
Raymond Hettinger6692f012016-09-18 21:46:08 -07004388 found = PyDict_GetItemWithError((PyObject *)dv->dv_dict, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004389 if (found == NULL) {
4390 if (PyErr_Occurred())
4391 return -1;
4392 return 0;
4393 }
Serhiy Storchaka753bca32017-05-20 12:30:02 +03004394 Py_INCREF(found);
4395 result = PyObject_RichCompareBool(value, found, Py_EQ);
4396 Py_DECREF(found);
4397 return result;
Guido van Rossumb90c8482007-02-10 01:11:45 +00004398}
4399
Guido van Rossum83825ac2007-02-10 04:54:19 +00004400static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 (lenfunc)dictview_len, /* sq_length */
4402 0, /* sq_concat */
4403 0, /* sq_repeat */
4404 0, /* sq_item */
4405 0, /* sq_slice */
4406 0, /* sq_ass_item */
4407 0, /* sq_ass_slice */
4408 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004409};
4410
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004411static PyObject* dictitems_reversed(_PyDictViewObject *dv);
4412
4413PyDoc_STRVAR(reversed_items_doc,
4414"Return a reverse iterator over the dict items.");
4415
Guido van Rossumb90c8482007-02-10 01:11:45 +00004416static PyMethodDef dictitems_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004417 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4418 isdisjoint_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02004419 {"__reversed__", (PyCFunction)(void(*)(void))dictitems_reversed, METH_NOARGS,
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004420 reversed_items_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004422};
4423
4424PyTypeObject PyDictItems_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4426 "dict_items", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004427 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 0, /* tp_itemsize */
4429 /* methods */
4430 (destructor)dictview_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004431 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 0, /* tp_getattr */
4433 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004434 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 (reprfunc)dictview_repr, /* tp_repr */
4436 &dictviews_as_number, /* tp_as_number */
4437 &dictitems_as_sequence, /* tp_as_sequence */
4438 0, /* tp_as_mapping */
4439 0, /* tp_hash */
4440 0, /* tp_call */
4441 0, /* tp_str */
4442 PyObject_GenericGetAttr, /* tp_getattro */
4443 0, /* tp_setattro */
4444 0, /* tp_as_buffer */
4445 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4446 0, /* tp_doc */
4447 (traverseproc)dictview_traverse, /* tp_traverse */
4448 0, /* tp_clear */
4449 dictview_richcompare, /* tp_richcompare */
4450 0, /* tp_weaklistoffset */
4451 (getiterfunc)dictitems_iter, /* tp_iter */
4452 0, /* tp_iternext */
4453 dictitems_methods, /* tp_methods */
4454 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004455};
4456
4457static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304458dictitems_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004459{
Eric Snow96c6af92015-05-29 22:21:39 -06004460 return _PyDictView_New(dict, &PyDictItems_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004461}
4462
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004463static PyObject *
4464dictitems_reversed(_PyDictViewObject *dv)
4465{
4466 if (dv->dv_dict == NULL) {
4467 Py_RETURN_NONE;
4468 }
4469 return dictiter_new(dv->dv_dict, &PyDictRevIterItem_Type);
4470}
4471
Guido van Rossum3ac67412007-02-10 18:55:06 +00004472/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004473
4474static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004475dictvalues_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004477 if (dv->dv_dict == NULL) {
4478 Py_RETURN_NONE;
4479 }
4480 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004481}
4482
Guido van Rossum83825ac2007-02-10 04:54:19 +00004483static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004484 (lenfunc)dictview_len, /* sq_length */
4485 0, /* sq_concat */
4486 0, /* sq_repeat */
4487 0, /* sq_item */
4488 0, /* sq_slice */
4489 0, /* sq_ass_item */
4490 0, /* sq_ass_slice */
4491 (objobjproc)0, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004492};
4493
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004494static PyObject* dictvalues_reversed(_PyDictViewObject *dv);
4495
4496PyDoc_STRVAR(reversed_values_doc,
4497"Return a reverse iterator over the dict values.");
4498
Guido van Rossumb90c8482007-02-10 01:11:45 +00004499static PyMethodDef dictvalues_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02004500 {"__reversed__", (PyCFunction)(void(*)(void))dictvalues_reversed, METH_NOARGS,
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004501 reversed_values_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004502 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004503};
4504
4505PyTypeObject PyDictValues_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4507 "dict_values", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004508 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004509 0, /* tp_itemsize */
4510 /* methods */
4511 (destructor)dictview_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004512 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004513 0, /* tp_getattr */
4514 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004515 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004516 (reprfunc)dictview_repr, /* tp_repr */
4517 0, /* tp_as_number */
4518 &dictvalues_as_sequence, /* tp_as_sequence */
4519 0, /* tp_as_mapping */
4520 0, /* tp_hash */
4521 0, /* tp_call */
4522 0, /* tp_str */
4523 PyObject_GenericGetAttr, /* tp_getattro */
4524 0, /* tp_setattro */
4525 0, /* tp_as_buffer */
4526 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4527 0, /* tp_doc */
4528 (traverseproc)dictview_traverse, /* tp_traverse */
4529 0, /* tp_clear */
4530 0, /* tp_richcompare */
4531 0, /* tp_weaklistoffset */
4532 (getiterfunc)dictvalues_iter, /* tp_iter */
4533 0, /* tp_iternext */
4534 dictvalues_methods, /* tp_methods */
4535 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004536};
4537
4538static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304539dictvalues_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004540{
Eric Snow96c6af92015-05-29 22:21:39 -06004541 return _PyDictView_New(dict, &PyDictValues_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004542}
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004543
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004544static PyObject *
4545dictvalues_reversed(_PyDictViewObject *dv)
4546{
4547 if (dv->dv_dict == NULL) {
4548 Py_RETURN_NONE;
4549 }
4550 return dictiter_new(dv->dv_dict, &PyDictRevIterValue_Type);
4551}
4552
4553
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004554/* Returns NULL if cannot allocate a new PyDictKeysObject,
4555 but does not set an error */
4556PyDictKeysObject *
4557_PyDict_NewKeysForClass(void)
4558{
Victor Stinner742da042016-09-07 17:40:12 -07004559 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004560 if (keys == NULL)
4561 PyErr_Clear();
4562 else
4563 keys->dk_lookup = lookdict_split;
4564 return keys;
4565}
4566
4567#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
4568
4569PyObject *
4570PyObject_GenericGetDict(PyObject *obj, void *context)
4571{
4572 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
4573 if (dictptr == NULL) {
4574 PyErr_SetString(PyExc_AttributeError,
4575 "This object has no __dict__");
4576 return NULL;
4577 }
4578 dict = *dictptr;
4579 if (dict == NULL) {
4580 PyTypeObject *tp = Py_TYPE(obj);
4581 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
INADA Naokia7576492018-11-14 18:39:27 +09004582 dictkeys_incref(CACHED_KEYS(tp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004583 *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
4584 }
4585 else {
4586 *dictptr = dict = PyDict_New();
4587 }
4588 }
4589 Py_XINCREF(dict);
4590 return dict;
4591}
4592
4593int
4594_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
Victor Stinner742da042016-09-07 17:40:12 -07004595 PyObject *key, PyObject *value)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004596{
4597 PyObject *dict;
4598 int res;
4599 PyDictKeysObject *cached;
4600
4601 assert(dictptr != NULL);
4602 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
4603 assert(dictptr != NULL);
4604 dict = *dictptr;
4605 if (dict == NULL) {
INADA Naokia7576492018-11-14 18:39:27 +09004606 dictkeys_incref(cached);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004607 dict = new_dict_with_shared_keys(cached);
4608 if (dict == NULL)
4609 return -1;
4610 *dictptr = dict;
4611 }
4612 if (value == NULL) {
4613 res = PyDict_DelItem(dict, key);
INADA Naoki2294f3a2017-02-12 13:51:30 +09004614 // Since key sharing dict doesn't allow deletion, PyDict_DelItem()
4615 // always converts dict to combined form.
4616 if ((cached = CACHED_KEYS(tp)) != NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004617 CACHED_KEYS(tp) = NULL;
INADA Naokia7576492018-11-14 18:39:27 +09004618 dictkeys_decref(cached);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004619 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01004620 }
4621 else {
INADA Naoki2294f3a2017-02-12 13:51:30 +09004622 int was_shared = (cached == ((PyDictObject *)dict)->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004623 res = PyDict_SetItem(dict, key, value);
INADA Naoki2294f3a2017-02-12 13:51:30 +09004624 if (was_shared &&
4625 (cached = CACHED_KEYS(tp)) != NULL &&
4626 cached != ((PyDictObject *)dict)->ma_keys) {
Victor Stinner3d3f2642016-12-15 17:21:23 +01004627 /* PyDict_SetItem() may call dictresize and convert split table
4628 * into combined table. In such case, convert it to split
4629 * table again and update type's shared key only when this is
4630 * the only dict sharing key with the type.
4631 *
4632 * This is to allow using shared key in class like this:
4633 *
4634 * class C:
4635 * def __init__(self):
4636 * # one dict resize happens
4637 * self.a, self.b, self.c = 1, 2, 3
4638 * self.d, self.e, self.f = 4, 5, 6
4639 * a = C()
4640 */
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004641 if (cached->dk_refcnt == 1) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004642 CACHED_KEYS(tp) = make_keys_shared(dict);
Victor Stinner742da042016-09-07 17:40:12 -07004643 }
4644 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004645 CACHED_KEYS(tp) = NULL;
4646 }
INADA Naokia7576492018-11-14 18:39:27 +09004647 dictkeys_decref(cached);
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004648 if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
4649 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004650 }
4651 }
4652 } else {
4653 dict = *dictptr;
4654 if (dict == NULL) {
4655 dict = PyDict_New();
4656 if (dict == NULL)
4657 return -1;
4658 *dictptr = dict;
4659 }
4660 if (value == NULL) {
4661 res = PyDict_DelItem(dict, key);
4662 } else {
4663 res = PyDict_SetItem(dict, key, value);
4664 }
4665 }
4666 return res;
4667}
4668
4669void
4670_PyDictKeys_DecRef(PyDictKeysObject *keys)
4671{
INADA Naokia7576492018-11-14 18:39:27 +09004672 dictkeys_decref(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004673}