blob: e417cd2119c6df2299dfbe6fd7d42a37dc952990 [file] [log] [blame]
Guido van Rossum2bc13791999-03-24 19:06:42 +00001/* Dictionary object implementation using a hash table */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002
Raymond Hettinger930427b2003-05-03 06:51:59 +00003/* The distribution includes a separate file, Objects/dictnotes.txt,
Tim Peters60b29962006-01-01 01:19:23 +00004 describing explorations into dictionary design and optimization.
Raymond Hettinger930427b2003-05-03 06:51:59 +00005 It covers typical dictionary use patterns, the parameters for
6 tuning dictionaries, and several ideas for possible optimizations.
7*/
8
Victor Stinner742da042016-09-07 17:40:12 -07009/* PyDictKeysObject
10
11This implements the dictionary's hashtable.
12
Raymond Hettingerb12785d2016-10-22 09:58:14 -070013As of Python 3.6, this is compact and ordered. Basic idea is described here:
14* https://mail.python.org/pipermail/python-dev/2012-December/123028.html
15* https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html
Victor Stinner742da042016-09-07 17:40:12 -070016
17layout:
18
19+---------------+
20| dk_refcnt |
21| dk_size |
22| dk_lookup |
23| dk_usable |
24| dk_nentries |
25+---------------+
26| dk_indices |
27| |
28+---------------+
29| dk_entries |
30| |
31+---------------+
32
33dk_indices is actual hashtable. It holds index in entries, or DKIX_EMPTY(-1)
34or DKIX_DUMMY(-2).
35Size of indices is dk_size. Type of each index in indices is vary on dk_size:
36
37* int8 for dk_size <= 128
38* int16 for 256 <= dk_size <= 2**15
39* int32 for 2**16 <= dk_size <= 2**31
40* int64 for 2**32 <= dk_size
41
42dk_entries is array of PyDictKeyEntry. It's size is USABLE_FRACTION(dk_size).
43DK_ENTRIES(dk) can be used to get pointer to entries.
44
45NOTE: Since negative value is used for DKIX_EMPTY and DKIX_DUMMY, type of
46dk_indices entry is signed integer and int16 is used for table which
47dk_size == 256.
48*/
49
Benjamin Peterson7d95e402012-04-23 11:24:50 -040050
51/*
Benjamin Peterson7d95e402012-04-23 11:24:50 -040052The DictObject can be in one of two forms.
Victor Stinner742da042016-09-07 17:40:12 -070053
Benjamin Peterson7d95e402012-04-23 11:24:50 -040054Either:
55 A combined table:
56 ma_values == NULL, dk_refcnt == 1.
57 Values are stored in the me_value field of the PyDictKeysObject.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040058Or:
59 A split table:
60 ma_values != NULL, dk_refcnt >= 1
61 Values are stored in the ma_values array.
Victor Stinner742da042016-09-07 17:40:12 -070062 Only string (unicode) keys are allowed.
63 All dicts sharing same key must have same insertion order.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040064
Victor Stinner742da042016-09-07 17:40:12 -070065There are four kinds of slots in the table (slot is index, and
66DK_ENTRIES(keys)[index] if index >= 0):
67
681. Unused. index == DKIX_EMPTY
69 Does not hold an active (key, value) pair now and never did. Unused can
70 transition to Active upon key insertion. This is each slot's initial state.
71
722. Active. index >= 0, me_key != NULL and me_value != NULL
73 Holds an active (key, value) pair. Active can transition to Dummy or
74 Pending upon key deletion (for combined and split tables respectively).
75 This is the only case in which me_value != NULL.
76
773. Dummy. index == DKIX_DUMMY (combined only)
78 Previously held an active (key, value) pair, but that was deleted and an
79 active pair has not yet overwritten the slot. Dummy can transition to
80 Active upon key insertion. Dummy slots cannot be made Unused again
81 else the probe sequence in case of collision would have no way to know
82 they were once active.
83
844. Pending. index >= 0, key != NULL, and value == NULL (split only)
85 Not yet inserted in split-table.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040086*/
87
Victor Stinner742da042016-09-07 17:40:12 -070088/*
89Preserving insertion order
Benjamin Peterson7d95e402012-04-23 11:24:50 -040090
Victor Stinner742da042016-09-07 17:40:12 -070091It's simple for combined table. Since dk_entries is mostly append only, we can
92get insertion order by just iterating dk_entries.
93
94One exception is .popitem(). It removes last item in dk_entries and decrement
95dk_nentries to achieve amortized O(1). Since there are DKIX_DUMMY remains in
96dk_indices, we can't increment dk_usable even though dk_nentries is
97decremented.
98
99In split table, inserting into pending entry is allowed only for dk_entries[ix]
100where ix == mp->ma_used. Inserting into other index and deleting item cause
101converting the dict to the combined table.
102*/
103
104/* PyDict_MINSIZE is the starting size for any new dict.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400105 * 8 allows dicts with no more than 5 active entries; experiments suggested
106 * this suffices for the majority of dicts (consisting mostly of usually-small
107 * dicts created to pass keyword arguments).
108 * Making this 8, rather than 4 reduces the number of resizes for most
109 * dictionaries, without any significant extra memory use.
110 */
Victor Stinner742da042016-09-07 17:40:12 -0700111#define PyDict_MINSIZE 8
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400112
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113#include "Python.h"
Victor Stinnerbcda8f12018-11-21 22:27:47 +0100114#include "pycore_object.h"
Victor Stinner621cebe2018-11-12 16:53:38 +0100115#include "pycore_pystate.h"
Eric Snow96c6af92015-05-29 22:21:39 -0600116#include "dict-common.h"
Victor Stinner990397e2016-09-09 20:22:59 -0700117#include "stringlib/eq.h" /* to get unicode_eq() */
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000118
Larry Hastings61272b72014-01-07 12:41:53 -0800119/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -0800120class dict "PyDictObject *" "&PyDict_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800121[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -0800122/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f157a5a0ce9589d6]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800123
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400124
125/*
126To ensure the lookup algorithm terminates, there must be at least one Unused
127slot (NULL key) in the table.
128To avoid slowing down lookups on a near-full table, we resize the table when
129it's USABLE_FRACTION (currently two-thirds) full.
130*/
Guido van Rossum16e93a81997-01-28 00:00:11 +0000131
Tim Peterseb28ef22001-06-02 05:27:19 +0000132#define PERTURB_SHIFT 5
133
Guido van Rossum16e93a81997-01-28 00:00:11 +0000134/*
Tim Peterseb28ef22001-06-02 05:27:19 +0000135Major subtleties ahead: Most hash schemes depend on having a "good" hash
136function, in the sense of simulating randomness. Python doesn't: its most
R David Murray537ad7a2016-07-10 12:33:18 -0400137important hash functions (for ints) are very regular in common
Tim Peterseb28ef22001-06-02 05:27:19 +0000138cases:
Tim Peters15d49292001-05-27 07:39:22 +0000139
R David Murray537ad7a2016-07-10 12:33:18 -0400140 >>>[hash(i) for i in range(4)]
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000141 [0, 1, 2, 3]
Tim Peters15d49292001-05-27 07:39:22 +0000142
Tim Peterseb28ef22001-06-02 05:27:19 +0000143This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
144the low-order i bits as the initial table index is extremely fast, and there
R David Murray537ad7a2016-07-10 12:33:18 -0400145are no collisions at all for dicts indexed by a contiguous range of ints. So
146this gives better-than-random behavior in common cases, and that's very
147desirable.
Tim Peters15d49292001-05-27 07:39:22 +0000148
Tim Peterseb28ef22001-06-02 05:27:19 +0000149OTOH, when collisions occur, the tendency to fill contiguous slices of the
150hash table makes a good collision resolution strategy crucial. Taking only
151the last i bits of the hash code is also vulnerable: for example, consider
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152the list [i << 16 for i in range(20000)] as a set of keys. Since ints are
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000153their own hash codes, and this fits in a dict of size 2**15, the last 15 bits
154 of every hash code are all 0: they *all* map to the same table index.
Tim Peters15d49292001-05-27 07:39:22 +0000155
Tim Peterseb28ef22001-06-02 05:27:19 +0000156But catering to unusual cases should not slow the usual ones, so we just take
157the last i bits anyway. It's up to collision resolution to do the rest. If
158we *usually* find the key we're looking for on the first try (and, it turns
159out, we usually do -- the table load factor is kept under 2/3, so the odds
160are solidly in our favor), then it makes best sense to keep the initial index
161computation dirt cheap.
Tim Peters15d49292001-05-27 07:39:22 +0000162
Tim Peterseb28ef22001-06-02 05:27:19 +0000163The first half of collision resolution is to visit table indices via this
164recurrence:
Tim Peters15d49292001-05-27 07:39:22 +0000165
Tim Peterseb28ef22001-06-02 05:27:19 +0000166 j = ((5*j) + 1) mod 2**i
Tim Peters15d49292001-05-27 07:39:22 +0000167
Tim Peterseb28ef22001-06-02 05:27:19 +0000168For any initial j in range(2**i), repeating that 2**i times generates each
169int in range(2**i) exactly once (see any text on random-number generation for
170proof). By itself, this doesn't help much: like linear probing (setting
171j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
172order. This would be bad, except that's not the only thing we do, and it's
173actually *good* in the common cases where hash keys are consecutive. In an
174example that's really too small to make this entirely clear, for a table of
175size 2**3 the order of indices is:
Tim Peters15d49292001-05-27 07:39:22 +0000176
Tim Peterseb28ef22001-06-02 05:27:19 +0000177 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
178
179If two things come in at index 5, the first place we look after is index 2,
180not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
181Linear probing is deadly in this case because there the fixed probe order
182is the *same* as the order consecutive keys are likely to arrive. But it's
183extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
184and certain that consecutive hash codes do not.
185
186The other half of the strategy is to get the other bits of the hash code
187into play. This is done by initializing a (unsigned) vrbl "perturb" to the
188full hash code, and changing the recurrence to:
189
Tim Peterseb28ef22001-06-02 05:27:19 +0000190 perturb >>= PERTURB_SHIFT;
INADA Naoki267941c2016-10-06 15:19:07 +0900191 j = (5*j) + 1 + perturb;
Tim Peterseb28ef22001-06-02 05:27:19 +0000192 use j % 2**i as the next table index;
193
194Now the probe sequence depends (eventually) on every bit in the hash code,
195and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
196because it quickly magnifies small differences in the bits that didn't affect
197the initial index. Note that because perturb is unsigned, if the recurrence
198is executed often enough perturb eventually becomes and remains 0. At that
199point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
200that's certain to find an empty slot eventually (since it generates every int
201in range(2**i), and we make sure there's always at least one empty slot).
202
203Selecting a good value for PERTURB_SHIFT is a balancing act. You want it
204small so that the high bits of the hash code continue to affect the probe
205sequence across iterations; but you want it large so that in really bad cases
206the high-order hash bits have an effect on early iterations. 5 was "the
207best" in minimizing total collisions across experiments Tim Peters ran (on
208both normal and pathological cases), but 4 and 6 weren't significantly worse.
209
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000210Historical: Reimer Behrends contributed the idea of using a polynomial-based
Tim Peterseb28ef22001-06-02 05:27:19 +0000211approach, using repeated multiplication by x in GF(2**n) where an irreducible
212polynomial for each table size was chosen such that x was a primitive root.
213Christian Tismer later extended that to use division by x instead, as an
214efficient way to get the high bits of the hash code into play. This scheme
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000215also gave excellent collision statistics, but was more expensive: two
216if-tests were required inside the loop; computing "the next" index took about
217the same number of operations but without as much potential parallelism
218(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
219above, and then shifting perturb can be done while the table index is being
220masked); and the PyDictObject struct required a member to hold the table's
221polynomial. In Tim's experiments the current scheme ran faster, produced
222equally good collision statistics, needed less code & used less memory.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000223
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000224*/
Tim Petersdea48ec2001-05-22 20:40:22 +0000225
Fred Drake1bff34a2000-08-31 19:31:38 +0000226/* forward declarations */
Victor Stinner742da042016-09-07 17:40:12 -0700227static Py_ssize_t lookdict(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900228 Py_hash_t hash, PyObject **value_addr);
Victor Stinner742da042016-09-07 17:40:12 -0700229static Py_ssize_t lookdict_unicode(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900230 Py_hash_t hash, PyObject **value_addr);
Victor Stinner742da042016-09-07 17:40:12 -0700231static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400232lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900233 Py_hash_t hash, PyObject **value_addr);
Victor Stinner742da042016-09-07 17:40:12 -0700234static Py_ssize_t lookdict_split(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900235 Py_hash_t hash, PyObject **value_addr);
Fred Drake1bff34a2000-08-31 19:31:38 +0000236
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400237static int dictresize(PyDictObject *mp, Py_ssize_t minused);
Tim Petersdea48ec2001-05-22 20:40:22 +0000238
INADA Naoki2aaf98c2018-09-26 12:59:00 +0900239static PyObject* dict_iter(PyDictObject *dict);
240
Benjamin Peterson3c569292016-09-08 13:16:41 -0700241/*Global counter used to set ma_version_tag field of dictionary.
Victor Stinner3b6a6b42016-09-08 12:51:24 -0700242 * It is incremented each time that a dictionary is created and each
243 * time that a dictionary is modified. */
244static uint64_t pydict_global_version = 0;
245
246#define DICT_NEXT_VERSION() (++pydict_global_version)
247
Victor Stinner742da042016-09-07 17:40:12 -0700248/* Dictionary reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +0000249#ifndef PyDict_MAXFREELIST
250#define PyDict_MAXFREELIST 80
251#endif
252static PyDictObject *free_list[PyDict_MAXFREELIST];
253static int numfree = 0;
Victor Stinner742da042016-09-07 17:40:12 -0700254static PyDictKeysObject *keys_free_list[PyDict_MAXFREELIST];
255static int numfreekeys = 0;
Raymond Hettinger43442782004-03-17 21:55:03 +0000256
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300257#include "clinic/dictobject.c.h"
258
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100259int
260PyDict_ClearFreeList(void)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 PyDictObject *op;
Victor Stinner742da042016-09-07 17:40:12 -0700263 int ret = numfree + numfreekeys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 while (numfree) {
265 op = free_list[--numfree];
266 assert(PyDict_CheckExact(op));
267 PyObject_GC_Del(op);
268 }
Victor Stinner742da042016-09-07 17:40:12 -0700269 while (numfreekeys) {
270 PyObject_FREE(keys_free_list[--numfreekeys]);
271 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100272 return ret;
273}
274
David Malcolm49526f42012-06-22 14:55:41 -0400275/* Print summary info about the state of the optimized allocator */
276void
277_PyDict_DebugMallocStats(FILE *out)
278{
279 _PyDebugAllocatorStats(out,
280 "free PyDictObject", numfree, sizeof(PyDictObject));
281}
282
283
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100284void
285PyDict_Fini(void)
286{
287 PyDict_ClearFreeList();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000288}
289
Victor Stinner742da042016-09-07 17:40:12 -0700290#define DK_SIZE(dk) ((dk)->dk_size)
291#if SIZEOF_VOID_P > 4
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700292#define DK_IXSIZE(dk) \
293 (DK_SIZE(dk) <= 0xff ? \
294 1 : DK_SIZE(dk) <= 0xffff ? \
295 2 : DK_SIZE(dk) <= 0xffffffff ? \
Benjamin Peterson3c569292016-09-08 13:16:41 -0700296 4 : sizeof(int64_t))
Victor Stinner742da042016-09-07 17:40:12 -0700297#else
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700298#define DK_IXSIZE(dk) \
299 (DK_SIZE(dk) <= 0xff ? \
300 1 : DK_SIZE(dk) <= 0xffff ? \
Benjamin Peterson3c569292016-09-08 13:16:41 -0700301 2 : sizeof(int32_t))
Victor Stinner742da042016-09-07 17:40:12 -0700302#endif
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700303#define DK_ENTRIES(dk) \
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700304 ((PyDictKeyEntry*)(&((int8_t*)((dk)->dk_indices))[DK_SIZE(dk) * DK_IXSIZE(dk)]))
Victor Stinner742da042016-09-07 17:40:12 -0700305
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400306#define DK_MASK(dk) (((dk)->dk_size)-1)
307#define IS_POWER_OF_2(x) (((x) & (x-1)) == 0)
308
INADA Naokia7576492018-11-14 18:39:27 +0900309static void free_keys_object(PyDictKeysObject *keys);
310
311static inline void
312dictkeys_incref(PyDictKeysObject *dk)
313{
314 _Py_INC_REFTOTAL;
315 dk->dk_refcnt++;
316}
317
318static inline void
319dictkeys_decref(PyDictKeysObject *dk)
320{
321 assert(dk->dk_refcnt > 0);
322 _Py_DEC_REFTOTAL;
323 if (--dk->dk_refcnt == 0) {
324 free_keys_object(dk);
325 }
326}
327
Victor Stinner742da042016-09-07 17:40:12 -0700328/* lookup indices. returns DKIX_EMPTY, DKIX_DUMMY, or ix >=0 */
Benjamin Peterson73222252016-09-08 09:58:47 -0700329static inline Py_ssize_t
INADA Naokia7576492018-11-14 18:39:27 +0900330dictkeys_get_index(PyDictKeysObject *keys, Py_ssize_t i)
Victor Stinner742da042016-09-07 17:40:12 -0700331{
332 Py_ssize_t s = DK_SIZE(keys);
Victor Stinner71211e32016-09-08 10:52:46 -0700333 Py_ssize_t ix;
334
Victor Stinner742da042016-09-07 17:40:12 -0700335 if (s <= 0xff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700336 int8_t *indices = (int8_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700337 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700338 }
339 else if (s <= 0xffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700340 int16_t *indices = (int16_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700341 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700342 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700343#if SIZEOF_VOID_P > 4
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300344 else if (s > 0xffffffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700345 int64_t *indices = (int64_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700346 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700347 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700348#endif
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300349 else {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700350 int32_t *indices = (int32_t*)(keys->dk_indices);
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300351 ix = indices[i];
352 }
Victor Stinner71211e32016-09-08 10:52:46 -0700353 assert(ix >= DKIX_DUMMY);
354 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700355}
356
357/* write to indices. */
Benjamin Peterson73222252016-09-08 09:58:47 -0700358static inline void
INADA Naokia7576492018-11-14 18:39:27 +0900359dictkeys_set_index(PyDictKeysObject *keys, Py_ssize_t i, Py_ssize_t ix)
Victor Stinner742da042016-09-07 17:40:12 -0700360{
361 Py_ssize_t s = DK_SIZE(keys);
Victor Stinner71211e32016-09-08 10:52:46 -0700362
363 assert(ix >= DKIX_DUMMY);
364
Victor Stinner742da042016-09-07 17:40:12 -0700365 if (s <= 0xff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700366 int8_t *indices = (int8_t*)(keys->dk_indices);
Victor Stinner71211e32016-09-08 10:52:46 -0700367 assert(ix <= 0x7f);
Victor Stinner208857e2016-09-08 11:35:46 -0700368 indices[i] = (char)ix;
Victor Stinner742da042016-09-07 17:40:12 -0700369 }
370 else if (s <= 0xffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700371 int16_t *indices = (int16_t*)(keys->dk_indices);
Victor Stinner71211e32016-09-08 10:52:46 -0700372 assert(ix <= 0x7fff);
Victor Stinner208857e2016-09-08 11:35:46 -0700373 indices[i] = (int16_t)ix;
Victor Stinner742da042016-09-07 17:40:12 -0700374 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700375#if SIZEOF_VOID_P > 4
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300376 else if (s > 0xffffffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700377 int64_t *indices = (int64_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700378 indices[i] = ix;
Victor Stinner742da042016-09-07 17:40:12 -0700379 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700380#endif
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300381 else {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700382 int32_t *indices = (int32_t*)(keys->dk_indices);
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300383 assert(ix <= 0x7fffffff);
384 indices[i] = (int32_t)ix;
385 }
Victor Stinner742da042016-09-07 17:40:12 -0700386}
387
388
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200389/* USABLE_FRACTION is the maximum dictionary load.
Victor Stinner742da042016-09-07 17:40:12 -0700390 * Increasing this ratio makes dictionaries more dense resulting in more
391 * collisions. Decreasing it improves sparseness at the expense of spreading
392 * indices over more cache lines and at the cost of total memory consumed.
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200393 *
394 * USABLE_FRACTION must obey the following:
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400395 * (0 < USABLE_FRACTION(n) < n) for all n >= 2
396 *
Victor Stinner742da042016-09-07 17:40:12 -0700397 * USABLE_FRACTION should be quick to calculate.
398 * Fractions around 1/2 to 2/3 seem to work well in practice.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400399 */
Victor Stinner742da042016-09-07 17:40:12 -0700400#define USABLE_FRACTION(n) (((n) << 1)/3)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400401
Victor Stinner742da042016-09-07 17:40:12 -0700402/* ESTIMATE_SIZE is reverse function of USABLE_FRACTION.
403 * This can be used to reserve enough size to insert n entries without
404 * resizing.
405 */
INADA Naoki92c50ee2016-11-22 00:57:02 +0900406#define ESTIMATE_SIZE(n) (((n)*3+1) >> 1)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400407
Victor Stinner742da042016-09-07 17:40:12 -0700408/* Alternative fraction that is otherwise close enough to 2n/3 to make
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400409 * little difference. 8 * 2/3 == 8 * 5/8 == 5. 16 * 2/3 == 16 * 5/8 == 10.
410 * 32 * 2/3 = 21, 32 * 5/8 = 20.
411 * Its advantage is that it is faster to compute on machines with slow division.
412 * #define USABLE_FRACTION(n) (((n) >> 1) + ((n) >> 2) - ((n) >> 3))
Victor Stinner742da042016-09-07 17:40:12 -0700413 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400414
Victor Stinnera9f61a52013-07-16 22:17:26 +0200415/* GROWTH_RATE. Growth rate upon hitting maximum load.
INADA Naoki5fbc5112018-04-17 15:53:34 +0900416 * Currently set to used*3.
Victor Stinnera9f61a52013-07-16 22:17:26 +0200417 * This means that dicts double in size when growing without deletions,
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700418 * but have more head room when the number of deletions is on a par with the
INADA Naoki5fbc5112018-04-17 15:53:34 +0900419 * number of insertions. See also bpo-17563 and bpo-33205.
420 *
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700421 * GROWTH_RATE was set to used*4 up to version 3.2.
422 * GROWTH_RATE was set to used*2 in version 3.3.0
INADA Naoki5fbc5112018-04-17 15:53:34 +0900423 * GROWTH_RATE was set to used*2 + capacity/2 in 3.4.0-3.6.0.
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200424 */
INADA Naoki5fbc5112018-04-17 15:53:34 +0900425#define GROWTH_RATE(d) ((d)->ma_used*3)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400426
427#define ENSURE_ALLOWS_DELETIONS(d) \
428 if ((d)->ma_keys->dk_lookup == lookdict_unicode_nodummy) { \
429 (d)->ma_keys->dk_lookup = lookdict_unicode; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400431
432/* This immutable, empty PyDictKeysObject is used for PyDict_Clear()
433 * (which cannot fail and thus can do no allocation).
434 */
435static PyDictKeysObject empty_keys_struct = {
Serhiy Storchaka97932e42016-09-26 23:01:23 +0300436 1, /* dk_refcnt */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400437 1, /* dk_size */
438 lookdict_split, /* dk_lookup */
439 0, /* dk_usable (immutable) */
Victor Stinner742da042016-09-07 17:40:12 -0700440 0, /* dk_nentries */
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700441 {DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY,
442 DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY}, /* dk_indices */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400443};
444
445static PyObject *empty_values[1] = { NULL };
446
447#define Py_EMPTY_KEYS &empty_keys_struct
448
Victor Stinner611b0fa2016-09-14 15:02:01 +0200449/* Uncomment to check the dict content in _PyDict_CheckConsistency() */
450/* #define DEBUG_PYDICT */
451
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200452#ifdef DEBUG_PYDICT
453# define ASSERT_CONSISTENT(op) assert(_PyDict_CheckConsistency((PyObject *)(op), 1))
454#else
455# define ASSERT_CONSISTENT(op) assert(_PyDict_CheckConsistency((PyObject *)(op), 0))
456#endif
Victor Stinner611b0fa2016-09-14 15:02:01 +0200457
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200458
459int
460_PyDict_CheckConsistency(PyObject *op, int check_content)
Victor Stinner611b0fa2016-09-14 15:02:01 +0200461{
Emmanuel Ariasa2fedd82019-05-10 07:08:08 -0300462#ifndef NDEBUG
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200463 _PyObject_ASSERT(op, PyDict_Check(op));
464 PyDictObject *mp = (PyDictObject *)op;
Victor Stinner50fe3f82018-10-26 18:47:15 +0200465
Victor Stinner611b0fa2016-09-14 15:02:01 +0200466 PyDictKeysObject *keys = mp->ma_keys;
467 int splitted = _PyDict_HasSplitTable(mp);
468 Py_ssize_t usable = USABLE_FRACTION(keys->dk_size);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200469
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200470 _PyObject_ASSERT(op, 0 <= mp->ma_used && mp->ma_used <= usable);
471 _PyObject_ASSERT(op, IS_POWER_OF_2(keys->dk_size));
472 _PyObject_ASSERT(op, 0 <= keys->dk_usable && keys->dk_usable <= usable);
473 _PyObject_ASSERT(op, 0 <= keys->dk_nentries && keys->dk_nentries <= usable);
474 _PyObject_ASSERT(op, keys->dk_usable + keys->dk_nentries <= usable);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200475
476 if (!splitted) {
477 /* combined table */
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200478 _PyObject_ASSERT(op, keys->dk_refcnt == 1);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200479 }
480
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200481 if (check_content) {
482 PyDictKeyEntry *entries = DK_ENTRIES(keys);
483 Py_ssize_t i;
Victor Stinner611b0fa2016-09-14 15:02:01 +0200484
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200485 for (i=0; i < keys->dk_size; i++) {
486 Py_ssize_t ix = dictkeys_get_index(keys, i);
487 _PyObject_ASSERT(op, DKIX_DUMMY <= ix && ix <= usable);
488 }
Victor Stinner611b0fa2016-09-14 15:02:01 +0200489
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200490 for (i=0; i < usable; i++) {
491 PyDictKeyEntry *entry = &entries[i];
492 PyObject *key = entry->me_key;
493
494 if (key != NULL) {
495 if (PyUnicode_CheckExact(key)) {
496 Py_hash_t hash = ((PyASCIIObject *)key)->hash;
497 _PyObject_ASSERT(op, hash != -1);
498 _PyObject_ASSERT(op, entry->me_hash == hash);
499 }
500 else {
501 /* test_dict fails if PyObject_Hash() is called again */
502 _PyObject_ASSERT(op, entry->me_hash != -1);
503 }
504 if (!splitted) {
505 _PyObject_ASSERT(op, entry->me_value != NULL);
506 }
Victor Stinner611b0fa2016-09-14 15:02:01 +0200507 }
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200508
509 if (splitted) {
510 _PyObject_ASSERT(op, entry->me_value == NULL);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200511 }
512 }
513
514 if (splitted) {
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200515 /* splitted table */
516 for (i=0; i < mp->ma_used; i++) {
517 _PyObject_ASSERT(op, mp->ma_values[i] != NULL);
518 }
Victor Stinner611b0fa2016-09-14 15:02:01 +0200519 }
520 }
Emmanuel Ariasa2fedd82019-05-10 07:08:08 -0300521#endif
Victor Stinner611b0fa2016-09-14 15:02:01 +0200522 return 1;
523}
Victor Stinner611b0fa2016-09-14 15:02:01 +0200524
525
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400526static PyDictKeysObject *new_keys_object(Py_ssize_t size)
527{
528 PyDictKeysObject *dk;
Victor Stinner742da042016-09-07 17:40:12 -0700529 Py_ssize_t es, usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400530
Victor Stinner742da042016-09-07 17:40:12 -0700531 assert(size >= PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400532 assert(IS_POWER_OF_2(size));
Victor Stinner742da042016-09-07 17:40:12 -0700533
534 usable = USABLE_FRACTION(size);
535 if (size <= 0xff) {
536 es = 1;
537 }
538 else if (size <= 0xffff) {
539 es = 2;
540 }
541#if SIZEOF_VOID_P > 4
542 else if (size <= 0xffffffff) {
543 es = 4;
544 }
545#endif
546 else {
547 es = sizeof(Py_ssize_t);
548 }
549
550 if (size == PyDict_MINSIZE && numfreekeys > 0) {
551 dk = keys_free_list[--numfreekeys];
552 }
553 else {
Victor Stinner98ee9d52016-09-08 09:33:56 -0700554 dk = PyObject_MALLOC(sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -0700555 + es * size
556 + sizeof(PyDictKeyEntry) * usable);
Victor Stinner742da042016-09-07 17:40:12 -0700557 if (dk == NULL) {
558 PyErr_NoMemory();
559 return NULL;
560 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400561 }
INADA Naokia7576492018-11-14 18:39:27 +0900562 _Py_INC_REFTOTAL;
563 dk->dk_refcnt = 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400564 dk->dk_size = size;
Victor Stinner742da042016-09-07 17:40:12 -0700565 dk->dk_usable = usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400566 dk->dk_lookup = lookdict_unicode_nodummy;
Victor Stinner742da042016-09-07 17:40:12 -0700567 dk->dk_nentries = 0;
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700568 memset(&dk->dk_indices[0], 0xff, es * size);
Victor Stinner742da042016-09-07 17:40:12 -0700569 memset(DK_ENTRIES(dk), 0, sizeof(PyDictKeyEntry) * usable);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400570 return dk;
571}
572
573static void
574free_keys_object(PyDictKeysObject *keys)
575{
Victor Stinner742da042016-09-07 17:40:12 -0700576 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400577 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -0700578 for (i = 0, n = keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400579 Py_XDECREF(entries[i].me_key);
580 Py_XDECREF(entries[i].me_value);
581 }
Victor Stinner742da042016-09-07 17:40:12 -0700582 if (keys->dk_size == PyDict_MINSIZE && numfreekeys < PyDict_MAXFREELIST) {
583 keys_free_list[numfreekeys++] = keys;
584 return;
585 }
Raymond Hettingerce5179f2016-01-31 08:56:21 -0800586 PyObject_FREE(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400587}
588
589#define new_values(size) PyMem_NEW(PyObject *, size)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400590#define free_values(values) PyMem_FREE(values)
591
592/* Consumes a reference to the keys object */
593static PyObject *
594new_dict(PyDictKeysObject *keys, PyObject **values)
595{
596 PyDictObject *mp;
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200597 assert(keys != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 if (numfree) {
599 mp = free_list[--numfree];
600 assert (mp != NULL);
601 assert (Py_TYPE(mp) == &PyDict_Type);
602 _Py_NewReference((PyObject *)mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400604 else {
605 mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
606 if (mp == NULL) {
INADA Naokia7576492018-11-14 18:39:27 +0900607 dictkeys_decref(keys);
Zackery Spytz3d07c1e2019-03-23 20:23:29 -0600608 if (values != empty_values) {
609 free_values(values);
610 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400611 return NULL;
612 }
613 }
614 mp->ma_keys = keys;
615 mp->ma_values = values;
616 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -0700617 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200618 ASSERT_CONSISTENT(mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000620}
621
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400622/* Consumes a reference to the keys object */
623static PyObject *
624new_dict_with_shared_keys(PyDictKeysObject *keys)
625{
626 PyObject **values;
627 Py_ssize_t i, size;
628
Victor Stinner742da042016-09-07 17:40:12 -0700629 size = USABLE_FRACTION(DK_SIZE(keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400630 values = new_values(size);
631 if (values == NULL) {
INADA Naokia7576492018-11-14 18:39:27 +0900632 dictkeys_decref(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400633 return PyErr_NoMemory();
634 }
635 for (i = 0; i < size; i++) {
636 values[i] = NULL;
637 }
638 return new_dict(keys, values);
639}
640
Yury Selivanovb0a7a032018-01-22 11:54:41 -0500641
642static PyObject *
643clone_combined_dict(PyDictObject *orig)
644{
645 assert(PyDict_CheckExact(orig));
646 assert(orig->ma_values == NULL);
647 assert(orig->ma_keys->dk_refcnt == 1);
648
649 Py_ssize_t keys_size = _PyDict_KeysSize(orig->ma_keys);
650 PyDictKeysObject *keys = PyObject_Malloc(keys_size);
651 if (keys == NULL) {
652 PyErr_NoMemory();
653 return NULL;
654 }
655
656 memcpy(keys, orig->ma_keys, keys_size);
657
658 /* After copying key/value pairs, we need to incref all
659 keys and values and they are about to be co-owned by a
660 new dict object. */
661 PyDictKeyEntry *ep0 = DK_ENTRIES(keys);
662 Py_ssize_t n = keys->dk_nentries;
663 for (Py_ssize_t i = 0; i < n; i++) {
664 PyDictKeyEntry *entry = &ep0[i];
665 PyObject *value = entry->me_value;
666 if (value != NULL) {
667 Py_INCREF(value);
668 Py_INCREF(entry->me_key);
669 }
670 }
671
672 PyDictObject *new = (PyDictObject *)new_dict(keys, NULL);
673 if (new == NULL) {
674 /* In case of an error, `new_dict()` takes care of
675 cleaning up `keys`. */
676 return NULL;
677 }
678 new->ma_used = orig->ma_used;
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200679 ASSERT_CONSISTENT(new);
Yury Selivanovb0a7a032018-01-22 11:54:41 -0500680 if (_PyObject_GC_IS_TRACKED(orig)) {
681 /* Maintain tracking. */
682 _PyObject_GC_TRACK(new);
683 }
Yury Selivanov0b752282018-07-06 12:20:07 -0400684
685 /* Since we copied the keys table we now have an extra reference
686 in the system. Manually call _Py_INC_REFTOTAL to signal that
INADA Naokia7576492018-11-14 18:39:27 +0900687 we have it now; calling dictkeys_incref would be an error as
Yury Selivanov0b752282018-07-06 12:20:07 -0400688 keys->dk_refcnt is already set to 1 (after memcpy). */
689 _Py_INC_REFTOTAL;
690
Yury Selivanovb0a7a032018-01-22 11:54:41 -0500691 return (PyObject *)new;
692}
693
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400694PyObject *
695PyDict_New(void)
696{
Inada Naokif2a18672019-03-12 17:25:44 +0900697 dictkeys_incref(Py_EMPTY_KEYS);
698 return new_dict(Py_EMPTY_KEYS, empty_values);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400699}
700
Victor Stinner742da042016-09-07 17:40:12 -0700701/* Search index of hash table from offset of entry table */
702static Py_ssize_t
703lookdict_index(PyDictKeysObject *k, Py_hash_t hash, Py_ssize_t index)
704{
Victor Stinner742da042016-09-07 17:40:12 -0700705 size_t mask = DK_MASK(k);
INADA Naoki073ae482017-06-23 15:22:50 +0900706 size_t perturb = (size_t)hash;
707 size_t i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700708
INADA Naoki073ae482017-06-23 15:22:50 +0900709 for (;;) {
INADA Naokia7576492018-11-14 18:39:27 +0900710 Py_ssize_t ix = dictkeys_get_index(k, i);
Victor Stinner742da042016-09-07 17:40:12 -0700711 if (ix == index) {
712 return i;
713 }
714 if (ix == DKIX_EMPTY) {
715 return DKIX_EMPTY;
716 }
INADA Naoki073ae482017-06-23 15:22:50 +0900717 perturb >>= PERTURB_SHIFT;
718 i = mask & (i*5 + perturb + 1);
Victor Stinner742da042016-09-07 17:40:12 -0700719 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700720 Py_UNREACHABLE();
Victor Stinner742da042016-09-07 17:40:12 -0700721}
722
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000723/*
724The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000725This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000726Open addressing is preferred over chaining since the link overhead for
727chaining would be substantial (100% with typical malloc overhead).
728
Tim Peterseb28ef22001-06-02 05:27:19 +0000729The initial probe index is computed as hash mod the table size. Subsequent
730probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000731
732All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000733
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000734The details in this version are due to Tim Peters, building on many past
Tim Peterseb28ef22001-06-02 05:27:19 +0000735contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000736Christian Tismer.
Fred Drake1bff34a2000-08-31 19:31:38 +0000737
Victor Stinner742da042016-09-07 17:40:12 -0700738lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a
Victor Stinnera4348cc2016-09-08 12:01:25 -0700739comparison raises an exception.
Guido van Rossum89d8c602007-09-18 17:26:56 +0000740lookdict_unicode() below is specialized to string keys, comparison of which can
INADA Naoki1b8df102017-02-20 22:48:10 +0900741never raise an exception; that function can never return DKIX_ERROR when key
742is string. Otherwise, it falls back to lookdict().
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400743lookdict_unicode_nodummy is further specialized for string keys that cannot be
744the <dummy> value.
INADA Naoki778928b2017-08-03 23:45:15 +0900745For both, when the key isn't found a DKIX_EMPTY is returned.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000746*/
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100747static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400748lookdict(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900749 Py_hash_t hash, PyObject **value_addr)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000750{
INADA Naoki778928b2017-08-03 23:45:15 +0900751 size_t i, mask, perturb;
Victor Stinner742da042016-09-07 17:40:12 -0700752 PyDictKeysObject *dk;
INADA Naoki778928b2017-08-03 23:45:15 +0900753 PyDictKeyEntry *ep0;
Tim Peterseb28ef22001-06-02 05:27:19 +0000754
Antoine Pitrou9a234902012-05-13 20:48:01 +0200755top:
Victor Stinner742da042016-09-07 17:40:12 -0700756 dk = mp->ma_keys;
Victor Stinner742da042016-09-07 17:40:12 -0700757 ep0 = DK_ENTRIES(dk);
INADA Naoki778928b2017-08-03 23:45:15 +0900758 mask = DK_MASK(dk);
759 perturb = hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700761
INADA Naoki778928b2017-08-03 23:45:15 +0900762 for (;;) {
INADA Naokia7576492018-11-14 18:39:27 +0900763 Py_ssize_t ix = dictkeys_get_index(dk, i);
Victor Stinner742da042016-09-07 17:40:12 -0700764 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700765 *value_addr = NULL;
766 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400767 }
INADA Naoki778928b2017-08-03 23:45:15 +0900768 if (ix >= 0) {
769 PyDictKeyEntry *ep = &ep0[ix];
770 assert(ep->me_key != NULL);
771 if (ep->me_key == key) {
772 *value_addr = ep->me_value;
773 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700774 }
INADA Naoki778928b2017-08-03 23:45:15 +0900775 if (ep->me_hash == hash) {
776 PyObject *startkey = ep->me_key;
777 Py_INCREF(startkey);
778 int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
779 Py_DECREF(startkey);
780 if (cmp < 0) {
781 *value_addr = NULL;
782 return DKIX_ERROR;
783 }
784 if (dk == mp->ma_keys && ep->me_key == startkey) {
785 if (cmp > 0) {
786 *value_addr = ep->me_value;
787 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700788 }
INADA Naoki778928b2017-08-03 23:45:15 +0900789 }
790 else {
791 /* The dict was mutated, restart */
792 goto top;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400793 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 }
INADA Naoki778928b2017-08-03 23:45:15 +0900796 perturb >>= PERTURB_SHIFT;
797 i = (i*5 + perturb + 1) & mask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700799 Py_UNREACHABLE();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000800}
801
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400802/* Specialized version for string-only keys */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100803static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400804lookdict_unicode(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900805 Py_hash_t hash, PyObject **value_addr)
Fred Drake1bff34a2000-08-31 19:31:38 +0000806{
Victor Stinner742da042016-09-07 17:40:12 -0700807 assert(mp->ma_values == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 /* Make sure this function doesn't have to handle non-unicode keys,
809 including subclasses of str; e.g., one reason to subclass
810 unicodes is to override __eq__, and for speed we don't cater to
811 that here. */
812 if (!PyUnicode_CheckExact(key)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400813 mp->ma_keys->dk_lookup = lookdict;
INADA Naoki778928b2017-08-03 23:45:15 +0900814 return lookdict(mp, key, hash, value_addr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 }
Tim Peters15d49292001-05-27 07:39:22 +0000816
INADA Naoki778928b2017-08-03 23:45:15 +0900817 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
818 size_t mask = DK_MASK(mp->ma_keys);
819 size_t perturb = (size_t)hash;
820 size_t i = (size_t)hash & mask;
821
822 for (;;) {
INADA Naokia7576492018-11-14 18:39:27 +0900823 Py_ssize_t ix = dictkeys_get_index(mp->ma_keys, i);
Victor Stinner742da042016-09-07 17:40:12 -0700824 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700825 *value_addr = NULL;
826 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400827 }
INADA Naoki778928b2017-08-03 23:45:15 +0900828 if (ix >= 0) {
829 PyDictKeyEntry *ep = &ep0[ix];
830 assert(ep->me_key != NULL);
831 assert(PyUnicode_CheckExact(ep->me_key));
832 if (ep->me_key == key ||
833 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
834 *value_addr = ep->me_value;
835 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700836 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400837 }
INADA Naoki778928b2017-08-03 23:45:15 +0900838 perturb >>= PERTURB_SHIFT;
839 i = mask & (i*5 + perturb + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700841 Py_UNREACHABLE();
Fred Drake1bff34a2000-08-31 19:31:38 +0000842}
843
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400844/* Faster version of lookdict_unicode when it is known that no <dummy> keys
845 * will be present. */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100846static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400847lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900848 Py_hash_t hash, PyObject **value_addr)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400849{
Victor Stinner742da042016-09-07 17:40:12 -0700850 assert(mp->ma_values == NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400851 /* Make sure this function doesn't have to handle non-unicode keys,
852 including subclasses of str; e.g., one reason to subclass
853 unicodes is to override __eq__, and for speed we don't cater to
854 that here. */
855 if (!PyUnicode_CheckExact(key)) {
856 mp->ma_keys->dk_lookup = lookdict;
INADA Naoki778928b2017-08-03 23:45:15 +0900857 return lookdict(mp, key, hash, value_addr);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400858 }
INADA Naoki778928b2017-08-03 23:45:15 +0900859
860 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
861 size_t mask = DK_MASK(mp->ma_keys);
862 size_t perturb = (size_t)hash;
863 size_t i = (size_t)hash & mask;
864
865 for (;;) {
INADA Naokia7576492018-11-14 18:39:27 +0900866 Py_ssize_t ix = dictkeys_get_index(mp->ma_keys, i);
Victor Stinner742da042016-09-07 17:40:12 -0700867 assert (ix != DKIX_DUMMY);
868 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700869 *value_addr = NULL;
870 return DKIX_EMPTY;
871 }
INADA Naoki778928b2017-08-03 23:45:15 +0900872 PyDictKeyEntry *ep = &ep0[ix];
873 assert(ep->me_key != NULL);
874 assert(PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700875 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400876 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
INADA Naokiba609772016-12-07 20:41:42 +0900877 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700878 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400879 }
INADA Naoki778928b2017-08-03 23:45:15 +0900880 perturb >>= PERTURB_SHIFT;
881 i = mask & (i*5 + perturb + 1);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400882 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700883 Py_UNREACHABLE();
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400884}
885
886/* Version of lookdict for split tables.
887 * All split tables and only split tables use this lookup function.
888 * Split tables only contain unicode keys and no dummy keys,
889 * so algorithm is the same as lookdict_unicode_nodummy.
890 */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100891static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400892lookdict_split(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900893 Py_hash_t hash, PyObject **value_addr)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400894{
Victor Stinner742da042016-09-07 17:40:12 -0700895 /* mp must split table */
896 assert(mp->ma_values != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400897 if (!PyUnicode_CheckExact(key)) {
INADA Naoki778928b2017-08-03 23:45:15 +0900898 Py_ssize_t ix = lookdict(mp, key, hash, value_addr);
Victor Stinner742da042016-09-07 17:40:12 -0700899 if (ix >= 0) {
INADA Naokiba609772016-12-07 20:41:42 +0900900 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700901 }
902 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400903 }
Victor Stinner742da042016-09-07 17:40:12 -0700904
INADA Naoki778928b2017-08-03 23:45:15 +0900905 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
906 size_t mask = DK_MASK(mp->ma_keys);
907 size_t perturb = (size_t)hash;
908 size_t i = (size_t)hash & mask;
909
910 for (;;) {
INADA Naokia7576492018-11-14 18:39:27 +0900911 Py_ssize_t ix = dictkeys_get_index(mp->ma_keys, i);
INADA Naoki778928b2017-08-03 23:45:15 +0900912 assert (ix != DKIX_DUMMY);
Victor Stinner742da042016-09-07 17:40:12 -0700913 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700914 *value_addr = NULL;
915 return DKIX_EMPTY;
916 }
INADA Naoki778928b2017-08-03 23:45:15 +0900917 PyDictKeyEntry *ep = &ep0[ix];
918 assert(ep->me_key != NULL);
919 assert(PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700920 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400921 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
INADA Naokiba609772016-12-07 20:41:42 +0900922 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700923 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400924 }
INADA Naoki778928b2017-08-03 23:45:15 +0900925 perturb >>= PERTURB_SHIFT;
926 i = mask & (i*5 + perturb + 1);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400927 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700928 Py_UNREACHABLE();
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400929}
930
Benjamin Petersonfb886362010-04-24 18:21:17 +0000931int
932_PyDict_HasOnlyStringKeys(PyObject *dict)
933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 Py_ssize_t pos = 0;
935 PyObject *key, *value;
Benjamin Petersonf6096542010-11-17 22:33:12 +0000936 assert(PyDict_Check(dict));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 /* Shortcut */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400938 if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 return 1;
940 while (PyDict_Next(dict, &pos, &key, &value))
941 if (!PyUnicode_Check(key))
942 return 0;
943 return 1;
Benjamin Petersonfb886362010-04-24 18:21:17 +0000944}
945
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000946#define MAINTAIN_TRACKING(mp, key, value) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 do { \
948 if (!_PyObject_GC_IS_TRACKED(mp)) { \
949 if (_PyObject_GC_MAY_BE_TRACKED(key) || \
950 _PyObject_GC_MAY_BE_TRACKED(value)) { \
951 _PyObject_GC_TRACK(mp); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 } \
953 } \
954 } while(0)
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000955
956void
957_PyDict_MaybeUntrack(PyObject *op)
958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 PyDictObject *mp;
960 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -0700961 Py_ssize_t i, numentries;
962 PyDictKeyEntry *ep0;
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
965 return;
966
967 mp = (PyDictObject *) op;
Victor Stinner742da042016-09-07 17:40:12 -0700968 ep0 = DK_ENTRIES(mp->ma_keys);
969 numentries = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400970 if (_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -0700971 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400972 if ((value = mp->ma_values[i]) == NULL)
973 continue;
974 if (_PyObject_GC_MAY_BE_TRACKED(value)) {
Victor Stinner742da042016-09-07 17:40:12 -0700975 assert(!_PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400976 return;
977 }
978 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400980 else {
Victor Stinner742da042016-09-07 17:40:12 -0700981 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400982 if ((value = ep0[i].me_value) == NULL)
983 continue;
984 if (_PyObject_GC_MAY_BE_TRACKED(value) ||
985 _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
986 return;
987 }
988 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 _PyObject_GC_UNTRACK(op);
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000990}
991
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400992/* Internal function to find slot for an item from its hash
Victor Stinner3c336c52016-09-12 14:17:40 +0200993 when it is known that the key is not present in the dict.
994
995 The dict must be combined. */
INADA Naokiba609772016-12-07 20:41:42 +0900996static Py_ssize_t
INADA Naoki778928b2017-08-03 23:45:15 +0900997find_empty_slot(PyDictKeysObject *keys, Py_hash_t hash)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000998{
INADA Naoki778928b2017-08-03 23:45:15 +0900999 assert(keys != NULL);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001000
INADA Naoki778928b2017-08-03 23:45:15 +09001001 const size_t mask = DK_MASK(keys);
1002 size_t i = hash & mask;
INADA Naokia7576492018-11-14 18:39:27 +09001003 Py_ssize_t ix = dictkeys_get_index(keys, i);
INADA Naoki778928b2017-08-03 23:45:15 +09001004 for (size_t perturb = hash; ix >= 0;) {
INADA Naoki267941c2016-10-06 15:19:07 +09001005 perturb >>= PERTURB_SHIFT;
INADA Naoki778928b2017-08-03 23:45:15 +09001006 i = (i*5 + perturb + 1) & mask;
INADA Naokia7576492018-11-14 18:39:27 +09001007 ix = dictkeys_get_index(keys, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 }
INADA Naoki778928b2017-08-03 23:45:15 +09001009 return i;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001010}
1011
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001012static int
1013insertion_resize(PyDictObject *mp)
1014{
Raymond Hettinger36f74aa2013-05-17 03:01:13 -07001015 return dictresize(mp, GROWTH_RATE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001016}
Antoine Pitroue965d972012-02-27 00:45:12 +01001017
1018/*
1019Internal routine to insert a new item into the table.
1020Used both by the internal resize routine and by the public insert routine.
Antoine Pitroue965d972012-02-27 00:45:12 +01001021Returns -1 if an error occurred, or 0 on success.
1022*/
1023static int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001024insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001025{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001026 PyObject *old_value;
INADA Naokiba609772016-12-07 20:41:42 +09001027 PyDictKeyEntry *ep;
Antoine Pitroue965d972012-02-27 00:45:12 +01001028
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001029 Py_INCREF(key);
1030 Py_INCREF(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001031 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
1032 if (insertion_resize(mp) < 0)
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001033 goto Fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001034 }
1035
INADA Naoki778928b2017-08-03 23:45:15 +09001036 Py_ssize_t ix = mp->ma_keys->dk_lookup(mp, key, hash, &old_value);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001037 if (ix == DKIX_ERROR)
1038 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001039
Antoine Pitroud6967322014-10-18 00:35:00 +02001040 assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001041 MAINTAIN_TRACKING(mp, key, value);
Victor Stinner742da042016-09-07 17:40:12 -07001042
1043 /* When insertion order is different from shared key, we can't share
1044 * the key anymore. Convert this instance to combine table.
1045 */
1046 if (_PyDict_HasSplitTable(mp) &&
INADA Naokiba609772016-12-07 20:41:42 +09001047 ((ix >= 0 && old_value == NULL && mp->ma_used != ix) ||
Victor Stinner742da042016-09-07 17:40:12 -07001048 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001049 if (insertion_resize(mp) < 0)
1050 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001051 ix = DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001052 }
Victor Stinner742da042016-09-07 17:40:12 -07001053
1054 if (ix == DKIX_EMPTY) {
1055 /* Insert into new slot. */
INADA Naokiba609772016-12-07 20:41:42 +09001056 assert(old_value == NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001057 if (mp->ma_keys->dk_usable <= 0) {
1058 /* Need to resize. */
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001059 if (insertion_resize(mp) < 0)
1060 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001061 }
INADA Naoki778928b2017-08-03 23:45:15 +09001062 Py_ssize_t hashpos = find_empty_slot(mp->ma_keys, hash);
INADA Naokiba609772016-12-07 20:41:42 +09001063 ep = &DK_ENTRIES(mp->ma_keys)[mp->ma_keys->dk_nentries];
INADA Naokia7576492018-11-14 18:39:27 +09001064 dictkeys_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
Victor Stinner742da042016-09-07 17:40:12 -07001065 ep->me_key = key;
1066 ep->me_hash = hash;
1067 if (mp->ma_values) {
1068 assert (mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
1069 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001070 }
1071 else {
Victor Stinner742da042016-09-07 17:40:12 -07001072 ep->me_value = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001073 }
1074 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001075 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07001076 mp->ma_keys->dk_usable--;
1077 mp->ma_keys->dk_nentries++;
1078 assert(mp->ma_keys->dk_usable >= 0);
Victor Stinner0fc91ee2019-04-12 21:51:34 +02001079 ASSERT_CONSISTENT(mp);
Victor Stinner742da042016-09-07 17:40:12 -07001080 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001081 }
Victor Stinner742da042016-09-07 17:40:12 -07001082
Inada Naoki91234a12019-06-03 21:30:58 +09001083 if (old_value != value) {
1084 if (_PyDict_HasSplitTable(mp)) {
1085 mp->ma_values[ix] = value;
1086 if (old_value == NULL) {
1087 /* pending state */
1088 assert(ix == mp->ma_used);
1089 mp->ma_used++;
1090 }
INADA Naokiba609772016-12-07 20:41:42 +09001091 }
Inada Naoki91234a12019-06-03 21:30:58 +09001092 else {
1093 assert(old_value != NULL);
1094 DK_ENTRIES(mp->ma_keys)[ix].me_value = value;
1095 }
1096 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naokiba609772016-12-07 20:41:42 +09001097 }
INADA Naokiba609772016-12-07 20:41:42 +09001098 Py_XDECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
Victor Stinner0fc91ee2019-04-12 21:51:34 +02001099 ASSERT_CONSISTENT(mp);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001100 Py_DECREF(key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001101 return 0;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001102
1103Fail:
1104 Py_DECREF(value);
1105 Py_DECREF(key);
1106 return -1;
Antoine Pitroue965d972012-02-27 00:45:12 +01001107}
1108
Inada Naoki2ddc7f62019-03-18 20:38:33 +09001109// Same to insertdict but specialized for ma_keys = Py_EMPTY_KEYS.
1110static int
1111insert_to_emptydict(PyDictObject *mp, PyObject *key, Py_hash_t hash,
1112 PyObject *value)
1113{
1114 assert(mp->ma_keys == Py_EMPTY_KEYS);
1115
1116 PyDictKeysObject *newkeys = new_keys_object(PyDict_MINSIZE);
1117 if (newkeys == NULL) {
1118 return -1;
1119 }
1120 if (!PyUnicode_CheckExact(key)) {
1121 newkeys->dk_lookup = lookdict;
1122 }
1123 dictkeys_decref(Py_EMPTY_KEYS);
1124 mp->ma_keys = newkeys;
1125 mp->ma_values = NULL;
1126
1127 Py_INCREF(key);
1128 Py_INCREF(value);
1129 MAINTAIN_TRACKING(mp, key, value);
1130
1131 size_t hashpos = (size_t)hash & (PyDict_MINSIZE-1);
1132 PyDictKeyEntry *ep = &DK_ENTRIES(mp->ma_keys)[0];
1133 dictkeys_set_index(mp->ma_keys, hashpos, 0);
1134 ep->me_key = key;
1135 ep->me_hash = hash;
1136 ep->me_value = value;
1137 mp->ma_used++;
1138 mp->ma_version_tag = DICT_NEXT_VERSION();
1139 mp->ma_keys->dk_usable--;
1140 mp->ma_keys->dk_nentries++;
1141 return 0;
1142}
1143
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001144/*
luzpaza5293b42017-11-05 07:37:50 -06001145Internal routine used by dictresize() to build a hashtable of entries.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001146*/
1147static void
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001148build_indices(PyDictKeysObject *keys, PyDictKeyEntry *ep, Py_ssize_t n)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001149{
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001150 size_t mask = (size_t)DK_SIZE(keys) - 1;
1151 for (Py_ssize_t ix = 0; ix != n; ix++, ep++) {
1152 Py_hash_t hash = ep->me_hash;
1153 size_t i = hash & mask;
INADA Naokia7576492018-11-14 18:39:27 +09001154 for (size_t perturb = hash; dictkeys_get_index(keys, i) != DKIX_EMPTY;) {
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001155 perturb >>= PERTURB_SHIFT;
INADA Naoki870c2862017-06-24 09:03:19 +09001156 i = mask & (i*5 + perturb + 1);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001157 }
INADA Naokia7576492018-11-14 18:39:27 +09001158 dictkeys_set_index(keys, i, ix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001160}
1161
1162/*
1163Restructure the table by allocating a new table and reinserting all
1164items again. When entries have been deleted, the new table may
1165actually be smaller than the old one.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001166If a table is split (its keys and hashes are shared, its values are not),
1167then the values are temporarily copied into the table, it is resized as
1168a combined table, then the me_value slots in the old table are NULLed out.
1169After resizing a table is always combined,
1170but can be resplit by make_keys_shared().
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001171*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001172static int
Victor Stinner3d3f2642016-12-15 17:21:23 +01001173dictresize(PyDictObject *mp, Py_ssize_t minsize)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001174{
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001175 Py_ssize_t newsize, numentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001176 PyDictKeysObject *oldkeys;
1177 PyObject **oldvalues;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001178 PyDictKeyEntry *oldentries, *newentries;
Tim Peters91a364d2001-05-19 07:04:38 +00001179
Victor Stinner742da042016-09-07 17:40:12 -07001180 /* Find the smallest table size > minused. */
1181 for (newsize = PyDict_MINSIZE;
Victor Stinner3d3f2642016-12-15 17:21:23 +01001182 newsize < minsize && newsize > 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 newsize <<= 1)
1184 ;
1185 if (newsize <= 0) {
1186 PyErr_NoMemory();
1187 return -1;
1188 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001189
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001190 oldkeys = mp->ma_keys;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001191
1192 /* NOTE: Current odict checks mp->ma_keys to detect resize happen.
1193 * So we can't reuse oldkeys even if oldkeys->dk_size == newsize.
1194 * TODO: Try reusing oldkeys when reimplement odict.
1195 */
1196
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001197 /* Allocate a new table. */
1198 mp->ma_keys = new_keys_object(newsize);
1199 if (mp->ma_keys == NULL) {
1200 mp->ma_keys = oldkeys;
1201 return -1;
1202 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01001203 // New table must be large enough.
1204 assert(mp->ma_keys->dk_usable >= mp->ma_used);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001205 if (oldkeys->dk_lookup == lookdict)
1206 mp->ma_keys->dk_lookup = lookdict;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001207
1208 numentries = mp->ma_used;
1209 oldentries = DK_ENTRIES(oldkeys);
1210 newentries = DK_ENTRIES(mp->ma_keys);
1211 oldvalues = mp->ma_values;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001212 if (oldvalues != NULL) {
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001213 /* Convert split table into new combined table.
1214 * We must incref keys; we can transfer values.
1215 * Note that values of split table is always dense.
1216 */
1217 for (Py_ssize_t i = 0; i < numentries; i++) {
1218 assert(oldvalues[i] != NULL);
1219 PyDictKeyEntry *ep = &oldentries[i];
1220 PyObject *key = ep->me_key;
1221 Py_INCREF(key);
1222 newentries[i].me_key = key;
1223 newentries[i].me_hash = ep->me_hash;
1224 newentries[i].me_value = oldvalues[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001226
INADA Naokia7576492018-11-14 18:39:27 +09001227 dictkeys_decref(oldkeys);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001228 mp->ma_values = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001229 if (oldvalues != empty_values) {
1230 free_values(oldvalues);
1231 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001232 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001233 else { // combined table.
1234 if (oldkeys->dk_nentries == numentries) {
1235 memcpy(newentries, oldentries, numentries * sizeof(PyDictKeyEntry));
1236 }
1237 else {
1238 PyDictKeyEntry *ep = oldentries;
1239 for (Py_ssize_t i = 0; i < numentries; i++) {
1240 while (ep->me_value == NULL)
1241 ep++;
1242 newentries[i] = *ep++;
1243 }
1244 }
1245
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001246 assert(oldkeys->dk_lookup != lookdict_split);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001247 assert(oldkeys->dk_refcnt == 1);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001248 if (oldkeys->dk_size == PyDict_MINSIZE &&
1249 numfreekeys < PyDict_MAXFREELIST) {
INADA Naokia7576492018-11-14 18:39:27 +09001250 _Py_DEC_REFTOTAL;
1251 keys_free_list[numfreekeys++] = oldkeys;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001252 }
1253 else {
INADA Naokia7576492018-11-14 18:39:27 +09001254 _Py_DEC_REFTOTAL;
1255 PyObject_FREE(oldkeys);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001256 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001257 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001258
1259 build_indices(mp->ma_keys, newentries, numentries);
1260 mp->ma_keys->dk_usable -= numentries;
1261 mp->ma_keys->dk_nentries = numentries;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001263}
1264
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001265/* Returns NULL if unable to split table.
1266 * A NULL return does not necessarily indicate an error */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001267static PyDictKeysObject *
1268make_keys_shared(PyObject *op)
1269{
1270 Py_ssize_t i;
1271 Py_ssize_t size;
1272 PyDictObject *mp = (PyDictObject *)op;
1273
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001274 if (!PyDict_CheckExact(op))
1275 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001276 if (!_PyDict_HasSplitTable(mp)) {
1277 PyDictKeyEntry *ep0;
1278 PyObject **values;
1279 assert(mp->ma_keys->dk_refcnt == 1);
1280 if (mp->ma_keys->dk_lookup == lookdict) {
1281 return NULL;
1282 }
1283 else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
1284 /* Remove dummy keys */
1285 if (dictresize(mp, DK_SIZE(mp->ma_keys)))
1286 return NULL;
1287 }
1288 assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
1289 /* Copy values into a new array */
Victor Stinner742da042016-09-07 17:40:12 -07001290 ep0 = DK_ENTRIES(mp->ma_keys);
1291 size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001292 values = new_values(size);
1293 if (values == NULL) {
1294 PyErr_SetString(PyExc_MemoryError,
1295 "Not enough memory to allocate new values array");
1296 return NULL;
1297 }
1298 for (i = 0; i < size; i++) {
1299 values[i] = ep0[i].me_value;
1300 ep0[i].me_value = NULL;
1301 }
1302 mp->ma_keys->dk_lookup = lookdict_split;
1303 mp->ma_values = values;
1304 }
INADA Naokia7576492018-11-14 18:39:27 +09001305 dictkeys_incref(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001306 return mp->ma_keys;
1307}
Christian Heimes99170a52007-12-19 02:07:34 +00001308
1309PyObject *
1310_PyDict_NewPresized(Py_ssize_t minused)
1311{
INADA Naoki92c50ee2016-11-22 00:57:02 +09001312 const Py_ssize_t max_presize = 128 * 1024;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001313 Py_ssize_t newsize;
1314 PyDictKeysObject *new_keys;
INADA Naoki92c50ee2016-11-22 00:57:02 +09001315
Inada Naoki2ddc7f62019-03-18 20:38:33 +09001316 if (minused <= USABLE_FRACTION(PyDict_MINSIZE)) {
Inada Naokif2a18672019-03-12 17:25:44 +09001317 return PyDict_New();
1318 }
INADA Naoki92c50ee2016-11-22 00:57:02 +09001319 /* There are no strict guarantee that returned dict can contain minused
1320 * items without resize. So we create medium size dict instead of very
1321 * large dict or MemoryError.
1322 */
1323 if (minused > USABLE_FRACTION(max_presize)) {
1324 newsize = max_presize;
1325 }
1326 else {
1327 Py_ssize_t minsize = ESTIMATE_SIZE(minused);
Inada Naoki2ddc7f62019-03-18 20:38:33 +09001328 newsize = PyDict_MINSIZE*2;
INADA Naoki92c50ee2016-11-22 00:57:02 +09001329 while (newsize < minsize) {
1330 newsize <<= 1;
1331 }
1332 }
1333 assert(IS_POWER_OF_2(newsize));
1334
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001335 new_keys = new_keys_object(newsize);
1336 if (new_keys == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001338 return new_dict(new_keys, NULL);
Christian Heimes99170a52007-12-19 02:07:34 +00001339}
1340
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001341/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
1342 * that may occur (originally dicts supported only string keys, and exceptions
1343 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001344 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001345 * (suppressed) occurred while computing the key's hash, or that some error
1346 * (suppressed) occurred when comparing keys in the dict's internal probe
1347 * sequence. A nasty example of the latter is when a Python-coded comparison
1348 * function hits a stack-depth error, which can cause this to return NULL
1349 * even if the key is present.
1350 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001351PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001352PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001353{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001354 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001355 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 PyDictObject *mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 PyThreadState *tstate;
INADA Naokiba609772016-12-07 20:41:42 +09001358 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 if (!PyDict_Check(op))
1361 return NULL;
1362 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001363 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 {
1365 hash = PyObject_Hash(key);
1366 if (hash == -1) {
1367 PyErr_Clear();
1368 return NULL;
1369 }
1370 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 /* We can arrive here with a NULL tstate during initialization: try
1373 running "python -Wi" for an example related to string interning.
1374 Let's just hope that no exception occurs then... This must be
Victor Stinner50b48572018-11-01 01:51:40 +01001375 _PyThreadState_GET() and not PyThreadState_Get() because the latter
Victor Stinner9204fb82018-10-30 15:13:17 +01001376 abort Python if tstate is NULL. */
Victor Stinner50b48572018-11-01 01:51:40 +01001377 tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 if (tstate != NULL && tstate->curexc_type != NULL) {
1379 /* preserve the existing exception */
1380 PyObject *err_type, *err_value, *err_tb;
1381 PyErr_Fetch(&err_type, &err_value, &err_tb);
INADA Naoki778928b2017-08-03 23:45:15 +09001382 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 /* ignore errors */
1384 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001385 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 return NULL;
1387 }
1388 else {
INADA Naoki778928b2017-08-03 23:45:15 +09001389 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001390 if (ix < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 PyErr_Clear();
1392 return NULL;
1393 }
1394 }
INADA Naokiba609772016-12-07 20:41:42 +09001395 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001396}
1397
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001398/* Same as PyDict_GetItemWithError() but with hash supplied by caller.
1399 This returns NULL *with* an exception set if an exception occurred.
1400 It returns NULL *without* an exception set if the key wasn't present.
1401*/
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001402PyObject *
1403_PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1404{
Victor Stinner742da042016-09-07 17:40:12 -07001405 Py_ssize_t ix;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001406 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001407 PyObject *value;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001408
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001409 if (!PyDict_Check(op)) {
1410 PyErr_BadInternalCall();
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001411 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001412 }
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001413
INADA Naoki778928b2017-08-03 23:45:15 +09001414 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001415 if (ix < 0) {
1416 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001417 }
INADA Naokiba609772016-12-07 20:41:42 +09001418 return value;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001419}
1420
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001421/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
1422 This returns NULL *with* an exception set if an exception occurred.
1423 It returns NULL *without* an exception set if the key wasn't present.
1424*/
1425PyObject *
1426PyDict_GetItemWithError(PyObject *op, PyObject *key)
1427{
Victor Stinner742da042016-09-07 17:40:12 -07001428 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001429 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 PyDictObject*mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001431 PyObject *value;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 if (!PyDict_Check(op)) {
1434 PyErr_BadInternalCall();
1435 return NULL;
1436 }
1437 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001438 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 {
1440 hash = PyObject_Hash(key);
1441 if (hash == -1) {
1442 return NULL;
1443 }
1444 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001445
INADA Naoki778928b2017-08-03 23:45:15 +09001446 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001447 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001449 return value;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001450}
1451
Brett Cannonfd074152012-04-14 14:10:13 -04001452PyObject *
1453_PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
1454{
1455 PyObject *kv;
1456 kv = _PyUnicode_FromId(key); /* borrowed */
1457 if (kv == NULL)
1458 return NULL;
1459 return PyDict_GetItemWithError(dp, kv);
1460}
1461
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001462PyObject *
1463_PyDict_GetItemStringWithError(PyObject *v, const char *key)
1464{
1465 PyObject *kv, *rv;
1466 kv = PyUnicode_FromString(key);
1467 if (kv == NULL) {
1468 return NULL;
1469 }
1470 rv = PyDict_GetItemWithError(v, kv);
1471 Py_DECREF(kv);
1472 return rv;
1473}
1474
Victor Stinnerb4efc962015-11-20 09:24:02 +01001475/* Fast version of global value lookup (LOAD_GLOBAL).
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001476 * Lookup in globals, then builtins.
Victor Stinnerb4efc962015-11-20 09:24:02 +01001477 *
1478 * Raise an exception and return NULL if an error occurred (ex: computing the
1479 * key hash failed, key comparison failed, ...). Return NULL if the key doesn't
1480 * exist. Return the value if the key exists.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001481 */
1482PyObject *
1483_PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001484{
Victor Stinner742da042016-09-07 17:40:12 -07001485 Py_ssize_t ix;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001486 Py_hash_t hash;
INADA Naokiba609772016-12-07 20:41:42 +09001487 PyObject *value;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001488
1489 if (!PyUnicode_CheckExact(key) ||
1490 (hash = ((PyASCIIObject *) key)->hash) == -1)
1491 {
1492 hash = PyObject_Hash(key);
1493 if (hash == -1)
1494 return NULL;
Antoine Pitroue965d972012-02-27 00:45:12 +01001495 }
Victor Stinnerb4efc962015-11-20 09:24:02 +01001496
1497 /* namespace 1: globals */
INADA Naoki778928b2017-08-03 23:45:15 +09001498 ix = globals->ma_keys->dk_lookup(globals, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001499 if (ix == DKIX_ERROR)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001500 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001501 if (ix != DKIX_EMPTY && value != NULL)
1502 return value;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001503
1504 /* namespace 2: builtins */
INADA Naoki778928b2017-08-03 23:45:15 +09001505 ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001506 if (ix < 0)
Victor Stinnerb4efc962015-11-20 09:24:02 +01001507 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001508 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001509}
1510
Antoine Pitroue965d972012-02-27 00:45:12 +01001511/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
1512 * dictionary if it's merely replacing the value for an existing key.
1513 * This means that it's safe to loop over a dictionary with PyDict_Next()
1514 * and occasionally replace a value -- but you can't insert new keys or
1515 * remove them.
1516 */
1517int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001518PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001519{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001520 PyDictObject *mp;
1521 Py_hash_t hash;
Antoine Pitroue965d972012-02-27 00:45:12 +01001522 if (!PyDict_Check(op)) {
1523 PyErr_BadInternalCall();
1524 return -1;
1525 }
1526 assert(key);
1527 assert(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001528 mp = (PyDictObject *)op;
1529 if (!PyUnicode_CheckExact(key) ||
1530 (hash = ((PyASCIIObject *) key)->hash) == -1)
1531 {
Antoine Pitroue965d972012-02-27 00:45:12 +01001532 hash = PyObject_Hash(key);
1533 if (hash == -1)
1534 return -1;
1535 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001536
Inada Naoki2ddc7f62019-03-18 20:38:33 +09001537 if (mp->ma_keys == Py_EMPTY_KEYS) {
1538 return insert_to_emptydict(mp, key, hash, value);
1539 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001540 /* insertdict() handles any resizing that might be necessary */
1541 return insertdict(mp, key, hash, value);
Antoine Pitroue965d972012-02-27 00:45:12 +01001542}
1543
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001544int
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001545_PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
1546 Py_hash_t hash)
1547{
1548 PyDictObject *mp;
1549
1550 if (!PyDict_Check(op)) {
1551 PyErr_BadInternalCall();
1552 return -1;
1553 }
1554 assert(key);
1555 assert(value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001556 assert(hash != -1);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001557 mp = (PyDictObject *)op;
1558
Inada Naoki2ddc7f62019-03-18 20:38:33 +09001559 if (mp->ma_keys == Py_EMPTY_KEYS) {
1560 return insert_to_emptydict(mp, key, hash, value);
1561 }
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001562 /* insertdict() handles any resizing that might be necessary */
1563 return insertdict(mp, key, hash, value);
1564}
1565
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001566static int
INADA Naoki778928b2017-08-03 23:45:15 +09001567delitem_common(PyDictObject *mp, Py_hash_t hash, Py_ssize_t ix,
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001568 PyObject *old_value)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001569{
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001570 PyObject *old_key;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001571 PyDictKeyEntry *ep;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001572
INADA Naoki778928b2017-08-03 23:45:15 +09001573 Py_ssize_t hashpos = lookdict_index(mp->ma_keys, hash, ix);
1574 assert(hashpos >= 0);
1575
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001576 mp->ma_used--;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001577 mp->ma_version_tag = DICT_NEXT_VERSION();
1578 ep = &DK_ENTRIES(mp->ma_keys)[ix];
INADA Naokia7576492018-11-14 18:39:27 +09001579 dictkeys_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001580 ENSURE_ALLOWS_DELETIONS(mp);
1581 old_key = ep->me_key;
1582 ep->me_key = NULL;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001583 ep->me_value = NULL;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001584 Py_DECREF(old_key);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001585 Py_DECREF(old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001586
Victor Stinner0fc91ee2019-04-12 21:51:34 +02001587 ASSERT_CONSISTENT(mp);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001588 return 0;
1589}
1590
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001591int
Tim Peters1f5871e2000-07-04 17:44:48 +00001592PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001593{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001594 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 assert(key);
1596 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001597 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 hash = PyObject_Hash(key);
1599 if (hash == -1)
1600 return -1;
1601 }
Victor Stinner742da042016-09-07 17:40:12 -07001602
1603 return _PyDict_DelItem_KnownHash(op, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001604}
1605
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001606int
1607_PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1608{
INADA Naoki778928b2017-08-03 23:45:15 +09001609 Py_ssize_t ix;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001610 PyDictObject *mp;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001611 PyObject *old_value;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001612
1613 if (!PyDict_Check(op)) {
1614 PyErr_BadInternalCall();
1615 return -1;
1616 }
1617 assert(key);
1618 assert(hash != -1);
1619 mp = (PyDictObject *)op;
INADA Naoki778928b2017-08-03 23:45:15 +09001620 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner742da042016-09-07 17:40:12 -07001621 if (ix == DKIX_ERROR)
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001622 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09001623 if (ix == DKIX_EMPTY || old_value == NULL) {
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001624 _PyErr_SetKeyError(key);
1625 return -1;
1626 }
Victor Stinner78601a32016-09-09 19:28:36 -07001627
1628 // Split table doesn't allow deletion. Combine it.
1629 if (_PyDict_HasSplitTable(mp)) {
1630 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1631 return -1;
1632 }
INADA Naoki778928b2017-08-03 23:45:15 +09001633 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner78601a32016-09-09 19:28:36 -07001634 assert(ix >= 0);
1635 }
1636
INADA Naoki778928b2017-08-03 23:45:15 +09001637 return delitem_common(mp, hash, ix, old_value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001638}
1639
Antoine Pitroud741ed42016-12-27 14:23:43 +01001640/* This function promises that the predicate -> deletion sequence is atomic
1641 * (i.e. protected by the GIL), assuming the predicate itself doesn't
1642 * release the GIL.
1643 */
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001644int
1645_PyDict_DelItemIf(PyObject *op, PyObject *key,
1646 int (*predicate)(PyObject *value))
1647{
Antoine Pitroud741ed42016-12-27 14:23:43 +01001648 Py_ssize_t hashpos, ix;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001649 PyDictObject *mp;
1650 Py_hash_t hash;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001651 PyObject *old_value;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001652 int res;
1653
1654 if (!PyDict_Check(op)) {
1655 PyErr_BadInternalCall();
1656 return -1;
1657 }
1658 assert(key);
1659 hash = PyObject_Hash(key);
1660 if (hash == -1)
1661 return -1;
1662 mp = (PyDictObject *)op;
INADA Naoki778928b2017-08-03 23:45:15 +09001663 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001664 if (ix == DKIX_ERROR)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001665 return -1;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001666 if (ix == DKIX_EMPTY || old_value == NULL) {
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001667 _PyErr_SetKeyError(key);
1668 return -1;
1669 }
Antoine Pitroud741ed42016-12-27 14:23:43 +01001670
1671 // Split table doesn't allow deletion. Combine it.
1672 if (_PyDict_HasSplitTable(mp)) {
1673 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1674 return -1;
1675 }
INADA Naoki778928b2017-08-03 23:45:15 +09001676 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001677 assert(ix >= 0);
1678 }
1679
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001680 res = predicate(old_value);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001681 if (res == -1)
1682 return -1;
INADA Naoki778928b2017-08-03 23:45:15 +09001683
1684 hashpos = lookdict_index(mp->ma_keys, hash, ix);
1685 assert(hashpos >= 0);
1686
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001687 if (res > 0)
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001688 return delitem_common(mp, hashpos, ix, old_value);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001689 else
1690 return 0;
1691}
1692
1693
Guido van Rossum25831651993-05-19 14:50:45 +00001694void
Tim Peters1f5871e2000-07-04 17:44:48 +00001695PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 PyDictObject *mp;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001698 PyDictKeysObject *oldkeys;
1699 PyObject **oldvalues;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 if (!PyDict_Check(op))
1703 return;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001704 mp = ((PyDictObject *)op);
1705 oldkeys = mp->ma_keys;
1706 oldvalues = mp->ma_values;
1707 if (oldvalues == empty_values)
1708 return;
1709 /* Empty the dict... */
INADA Naokia7576492018-11-14 18:39:27 +09001710 dictkeys_incref(Py_EMPTY_KEYS);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001711 mp->ma_keys = Py_EMPTY_KEYS;
1712 mp->ma_values = empty_values;
1713 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001714 mp->ma_version_tag = DICT_NEXT_VERSION();
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001715 /* ...then clear the keys and values */
1716 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001717 n = oldkeys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001718 for (i = 0; i < n; i++)
1719 Py_CLEAR(oldvalues[i]);
1720 free_values(oldvalues);
INADA Naokia7576492018-11-14 18:39:27 +09001721 dictkeys_decref(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001722 }
1723 else {
1724 assert(oldkeys->dk_refcnt == 1);
INADA Naokia7576492018-11-14 18:39:27 +09001725 dictkeys_decref(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001726 }
Victor Stinner0fc91ee2019-04-12 21:51:34 +02001727 ASSERT_CONSISTENT(mp);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001728}
1729
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001730/* Internal version of PyDict_Next that returns a hash value in addition
1731 * to the key and value.
1732 * Return 1 on success, return 0 when the reached the end of the dictionary
1733 * (or if op is not a dictionary)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001734 */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001735int
1736_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
1737 PyObject **pvalue, Py_hash_t *phash)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001738{
INADA Naokica2d8be2016-11-04 16:59:10 +09001739 Py_ssize_t i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001740 PyDictObject *mp;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001741 PyDictKeyEntry *entry_ptr;
1742 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001743
1744 if (!PyDict_Check(op))
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001745 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 mp = (PyDictObject *)op;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001747 i = *ppos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001748 if (mp->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09001749 if (i < 0 || i >= mp->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001750 return 0;
INADA Naokica2d8be2016-11-04 16:59:10 +09001751 /* values of split table is always dense */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001752 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
INADA Naokica2d8be2016-11-04 16:59:10 +09001753 value = mp->ma_values[i];
1754 assert(value != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001756 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09001757 Py_ssize_t n = mp->ma_keys->dk_nentries;
1758 if (i < 0 || i >= n)
1759 return 0;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001760 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
1761 while (i < n && entry_ptr->me_value == NULL) {
1762 entry_ptr++;
1763 i++;
Victor Stinner742da042016-09-07 17:40:12 -07001764 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001765 if (i >= n)
1766 return 0;
1767 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001769 *ppos = i+1;
1770 if (pkey)
1771 *pkey = entry_ptr->me_key;
1772 if (phash)
1773 *phash = entry_ptr->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001774 if (pvalue)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001775 *pvalue = value;
1776 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001777}
1778
Tim Peters080c88b2003-02-15 03:01:11 +00001779/*
1780 * Iterate over a dict. Use like so:
1781 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001782 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +00001783 * PyObject *key, *value;
1784 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +00001785 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001786 * Refer to borrowed references in key and value.
Tim Peters080c88b2003-02-15 03:01:11 +00001787 * }
1788 *
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001789 * Return 1 on success, return 0 when the reached the end of the dictionary
1790 * (or if op is not a dictionary)
1791 *
Tim Peters080c88b2003-02-15 03:01:11 +00001792 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +00001793 * mutates the dict. One exception: it is safe if the loop merely changes
1794 * the values associated with the keys (but doesn't insert new keys or
1795 * delete keys), via PyDict_SetItem().
1796 */
Guido van Rossum25831651993-05-19 14:50:45 +00001797int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001798PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001799{
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001800 return _PyDict_Next(op, ppos, pkey, pvalue, NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00001801}
1802
Eric Snow96c6af92015-05-29 22:21:39 -06001803/* Internal version of dict.pop(). */
1804PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001805_PyDict_Pop_KnownHash(PyObject *dict, PyObject *key, Py_hash_t hash, PyObject *deflt)
Eric Snow96c6af92015-05-29 22:21:39 -06001806{
Victor Stinner742da042016-09-07 17:40:12 -07001807 Py_ssize_t ix, hashpos;
Eric Snow96c6af92015-05-29 22:21:39 -06001808 PyObject *old_value, *old_key;
1809 PyDictKeyEntry *ep;
Yury Selivanov684ef2c2016-10-28 19:01:21 -04001810 PyDictObject *mp;
1811
1812 assert(PyDict_Check(dict));
1813 mp = (PyDictObject *)dict;
Eric Snow96c6af92015-05-29 22:21:39 -06001814
1815 if (mp->ma_used == 0) {
1816 if (deflt) {
1817 Py_INCREF(deflt);
1818 return deflt;
1819 }
1820 _PyErr_SetKeyError(key);
1821 return NULL;
1822 }
INADA Naoki778928b2017-08-03 23:45:15 +09001823 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner742da042016-09-07 17:40:12 -07001824 if (ix == DKIX_ERROR)
Eric Snow96c6af92015-05-29 22:21:39 -06001825 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001826 if (ix == DKIX_EMPTY || old_value == NULL) {
Eric Snow96c6af92015-05-29 22:21:39 -06001827 if (deflt) {
1828 Py_INCREF(deflt);
1829 return deflt;
1830 }
1831 _PyErr_SetKeyError(key);
1832 return NULL;
1833 }
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001834
Victor Stinner78601a32016-09-09 19:28:36 -07001835 // Split table doesn't allow deletion. Combine it.
1836 if (_PyDict_HasSplitTable(mp)) {
1837 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1838 return NULL;
1839 }
INADA Naoki778928b2017-08-03 23:45:15 +09001840 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner78601a32016-09-09 19:28:36 -07001841 assert(ix >= 0);
1842 }
1843
INADA Naoki778928b2017-08-03 23:45:15 +09001844 hashpos = lookdict_index(mp->ma_keys, hash, ix);
1845 assert(hashpos >= 0);
Victor Stinner78601a32016-09-09 19:28:36 -07001846 assert(old_value != NULL);
Eric Snow96c6af92015-05-29 22:21:39 -06001847 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001848 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naokia7576492018-11-14 18:39:27 +09001849 dictkeys_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
Victor Stinner78601a32016-09-09 19:28:36 -07001850 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1851 ENSURE_ALLOWS_DELETIONS(mp);
1852 old_key = ep->me_key;
1853 ep->me_key = NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001854 ep->me_value = NULL;
Victor Stinner78601a32016-09-09 19:28:36 -07001855 Py_DECREF(old_key);
Victor Stinner611b0fa2016-09-14 15:02:01 +02001856
Victor Stinner0fc91ee2019-04-12 21:51:34 +02001857 ASSERT_CONSISTENT(mp);
Eric Snow96c6af92015-05-29 22:21:39 -06001858 return old_value;
1859}
1860
Serhiy Storchaka67796522017-01-12 18:34:33 +02001861PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001862_PyDict_Pop(PyObject *dict, PyObject *key, PyObject *deflt)
Serhiy Storchaka67796522017-01-12 18:34:33 +02001863{
1864 Py_hash_t hash;
1865
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001866 if (((PyDictObject *)dict)->ma_used == 0) {
Serhiy Storchaka67796522017-01-12 18:34:33 +02001867 if (deflt) {
1868 Py_INCREF(deflt);
1869 return deflt;
1870 }
1871 _PyErr_SetKeyError(key);
1872 return NULL;
1873 }
1874 if (!PyUnicode_CheckExact(key) ||
1875 (hash = ((PyASCIIObject *) key)->hash) == -1) {
1876 hash = PyObject_Hash(key);
1877 if (hash == -1)
1878 return NULL;
1879 }
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001880 return _PyDict_Pop_KnownHash(dict, key, hash, deflt);
Serhiy Storchaka67796522017-01-12 18:34:33 +02001881}
1882
Eric Snow96c6af92015-05-29 22:21:39 -06001883/* Internal version of dict.from_keys(). It is subclass-friendly. */
1884PyObject *
1885_PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
1886{
1887 PyObject *it; /* iter(iterable) */
1888 PyObject *key;
1889 PyObject *d;
1890 int status;
1891
Victor Stinnera5ed5f02016-12-06 18:45:50 +01001892 d = _PyObject_CallNoArg(cls);
Eric Snow96c6af92015-05-29 22:21:39 -06001893 if (d == NULL)
1894 return NULL;
1895
1896 if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
1897 if (PyDict_CheckExact(iterable)) {
1898 PyDictObject *mp = (PyDictObject *)d;
1899 PyObject *oldvalue;
1900 Py_ssize_t pos = 0;
1901 PyObject *key;
1902 Py_hash_t hash;
1903
Serhiy Storchakac61ac162017-03-21 08:52:38 +02001904 if (dictresize(mp, ESTIMATE_SIZE(PyDict_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001905 Py_DECREF(d);
1906 return NULL;
1907 }
1908
1909 while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
1910 if (insertdict(mp, key, hash, value)) {
1911 Py_DECREF(d);
1912 return NULL;
1913 }
1914 }
1915 return d;
1916 }
1917 if (PyAnySet_CheckExact(iterable)) {
1918 PyDictObject *mp = (PyDictObject *)d;
1919 Py_ssize_t pos = 0;
1920 PyObject *key;
1921 Py_hash_t hash;
1922
Victor Stinner742da042016-09-07 17:40:12 -07001923 if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001924 Py_DECREF(d);
1925 return NULL;
1926 }
1927
1928 while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
1929 if (insertdict(mp, key, hash, value)) {
1930 Py_DECREF(d);
1931 return NULL;
1932 }
1933 }
1934 return d;
1935 }
1936 }
1937
1938 it = PyObject_GetIter(iterable);
1939 if (it == NULL){
1940 Py_DECREF(d);
1941 return NULL;
1942 }
1943
1944 if (PyDict_CheckExact(d)) {
1945 while ((key = PyIter_Next(it)) != NULL) {
1946 status = PyDict_SetItem(d, key, value);
1947 Py_DECREF(key);
1948 if (status < 0)
1949 goto Fail;
1950 }
1951 } else {
1952 while ((key = PyIter_Next(it)) != NULL) {
1953 status = PyObject_SetItem(d, key, value);
1954 Py_DECREF(key);
1955 if (status < 0)
1956 goto Fail;
1957 }
1958 }
1959
1960 if (PyErr_Occurred())
1961 goto Fail;
1962 Py_DECREF(it);
1963 return d;
1964
1965Fail:
1966 Py_DECREF(it);
1967 Py_DECREF(d);
1968 return NULL;
1969}
1970
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001971/* Methods */
1972
1973static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001974dict_dealloc(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001975{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001976 PyObject **values = mp->ma_values;
1977 PyDictKeysObject *keys = mp->ma_keys;
1978 Py_ssize_t i, n;
INADA Naokia6296d32017-08-24 14:55:17 +09001979
1980 /* bpo-31095: UnTrack is needed before calling any callbacks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 PyObject_GC_UnTrack(mp);
Jeroen Demeyer351c6742019-05-10 19:21:11 +02001982 Py_TRASHCAN_BEGIN(mp, dict_dealloc)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001983 if (values != NULL) {
1984 if (values != empty_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001985 for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001986 Py_XDECREF(values[i]);
1987 }
1988 free_values(values);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 }
INADA Naokia7576492018-11-14 18:39:27 +09001990 dictkeys_decref(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 }
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02001992 else if (keys != NULL) {
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001993 assert(keys->dk_refcnt == 1);
INADA Naokia7576492018-11-14 18:39:27 +09001994 dictkeys_decref(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001995 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
1997 free_list[numfree++] = mp;
1998 else
1999 Py_TYPE(mp)->tp_free((PyObject *)mp);
Jeroen Demeyer351c6742019-05-10 19:21:11 +02002000 Py_TRASHCAN_END
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002001}
2002
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002004static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002005dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 Py_ssize_t i;
Victor Stinnerf91929b2013-11-19 13:07:38 +01002008 PyObject *key = NULL, *value = NULL;
2009 _PyUnicodeWriter writer;
2010 int first;
Guido van Rossum255443b1998-04-10 22:47:14 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 i = Py_ReprEnter((PyObject *)mp);
2013 if (i != 0) {
2014 return i > 0 ? PyUnicode_FromString("{...}") : NULL;
2015 }
Guido van Rossum255443b1998-04-10 22:47:14 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 if (mp->ma_used == 0) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01002018 Py_ReprLeave((PyObject *)mp);
2019 return PyUnicode_FromString("{}");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 }
Tim Petersa7259592001-06-16 05:11:17 +00002021
Victor Stinnerf91929b2013-11-19 13:07:38 +01002022 _PyUnicodeWriter_Init(&writer);
2023 writer.overallocate = 1;
2024 /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
2025 writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +00002026
Victor Stinnerf91929b2013-11-19 13:07:38 +01002027 if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
2028 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 /* Do repr() on each key+value pair, and insert ": " between them.
2031 Note that repr may mutate the dict. */
2032 i = 0;
Victor Stinnerf91929b2013-11-19 13:07:38 +01002033 first = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01002035 PyObject *s;
2036 int res;
2037
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002038 /* Prevent repr from deleting key or value during key format. */
2039 Py_INCREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 Py_INCREF(value);
Victor Stinnerf97dfd72013-07-18 01:00:45 +02002041
Victor Stinnerf91929b2013-11-19 13:07:38 +01002042 if (!first) {
2043 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
2044 goto error;
2045 }
2046 first = 0;
2047
2048 s = PyObject_Repr(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 if (s == NULL)
Victor Stinnerf91929b2013-11-19 13:07:38 +01002050 goto error;
2051 res = _PyUnicodeWriter_WriteStr(&writer, s);
2052 Py_DECREF(s);
2053 if (res < 0)
2054 goto error;
2055
2056 if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
2057 goto error;
2058
2059 s = PyObject_Repr(value);
2060 if (s == NULL)
2061 goto error;
2062 res = _PyUnicodeWriter_WriteStr(&writer, s);
2063 Py_DECREF(s);
2064 if (res < 0)
2065 goto error;
2066
2067 Py_CLEAR(key);
2068 Py_CLEAR(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 }
Tim Petersa7259592001-06-16 05:11:17 +00002070
Victor Stinnerf91929b2013-11-19 13:07:38 +01002071 writer.overallocate = 0;
2072 if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
2073 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 Py_ReprLeave((PyObject *)mp);
Victor Stinnerf91929b2013-11-19 13:07:38 +01002076
2077 return _PyUnicodeWriter_Finish(&writer);
2078
2079error:
2080 Py_ReprLeave((PyObject *)mp);
2081 _PyUnicodeWriter_Dealloc(&writer);
2082 Py_XDECREF(key);
2083 Py_XDECREF(value);
2084 return NULL;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002085}
2086
Martin v. Löwis18e16552006-02-15 17:27:45 +00002087static Py_ssize_t
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002088dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 return mp->ma_used;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002091}
2092
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002093static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002094dict_subscript(PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002095{
Victor Stinner742da042016-09-07 17:40:12 -07002096 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002097 Py_hash_t hash;
INADA Naokiba609772016-12-07 20:41:42 +09002098 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002101 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 hash = PyObject_Hash(key);
2103 if (hash == -1)
2104 return NULL;
2105 }
INADA Naoki778928b2017-08-03 23:45:15 +09002106 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002107 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002109 if (ix == DKIX_EMPTY || value == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 if (!PyDict_CheckExact(mp)) {
2111 /* Look up __missing__ method if we're a subclass. */
2112 PyObject *missing, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05002113 _Py_IDENTIFIER(__missing__);
2114 missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 if (missing != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002116 res = PyObject_CallFunctionObjArgs(missing,
2117 key, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 Py_DECREF(missing);
2119 return res;
2120 }
2121 else if (PyErr_Occurred())
2122 return NULL;
2123 }
Raymond Hettinger69492da2013-09-02 15:59:26 -07002124 _PyErr_SetKeyError(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 return NULL;
2126 }
INADA Naokiba609772016-12-07 20:41:42 +09002127 Py_INCREF(value);
2128 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002129}
2130
2131static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002132dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 if (w == NULL)
2135 return PyDict_DelItem((PyObject *)mp, v);
2136 else
2137 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002138}
2139
Guido van Rossuma9e7a811997-05-13 21:02:11 +00002140static PyMappingMethods dict_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 (lenfunc)dict_length, /*mp_length*/
2142 (binaryfunc)dict_subscript, /*mp_subscript*/
2143 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002144};
2145
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002146static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002147dict_keys(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002148{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002149 PyObject *v;
2150 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002151 PyDictKeyEntry *ep;
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002152 Py_ssize_t n, offset;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002153 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002154
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002155 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 n = mp->ma_used;
2157 v = PyList_New(n);
2158 if (v == NULL)
2159 return NULL;
2160 if (n != mp->ma_used) {
2161 /* Durnit. The allocations caused the dict to resize.
2162 * Just start over, this shouldn't normally happen.
2163 */
2164 Py_DECREF(v);
2165 goto again;
2166 }
Victor Stinner742da042016-09-07 17:40:12 -07002167 ep = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002168 if (mp->ma_values) {
2169 value_ptr = mp->ma_values;
2170 offset = sizeof(PyObject *);
2171 }
2172 else {
2173 value_ptr = &ep[0].me_value;
2174 offset = sizeof(PyDictKeyEntry);
2175 }
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002176 for (i = 0, j = 0; j < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002177 if (*value_ptr != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 PyObject *key = ep[i].me_key;
2179 Py_INCREF(key);
2180 PyList_SET_ITEM(v, j, key);
2181 j++;
2182 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002183 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 }
2185 assert(j == n);
2186 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002187}
2188
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002189static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002190dict_values(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002191{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002192 PyObject *v;
2193 Py_ssize_t i, j;
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002194 PyDictKeyEntry *ep;
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002195 Py_ssize_t n, offset;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002196 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002197
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002198 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 n = mp->ma_used;
2200 v = PyList_New(n);
2201 if (v == NULL)
2202 return NULL;
2203 if (n != mp->ma_used) {
2204 /* Durnit. The allocations caused the dict to resize.
2205 * Just start over, this shouldn't normally happen.
2206 */
2207 Py_DECREF(v);
2208 goto again;
2209 }
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002210 ep = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002211 if (mp->ma_values) {
2212 value_ptr = mp->ma_values;
2213 offset = sizeof(PyObject *);
2214 }
2215 else {
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002216 value_ptr = &ep[0].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002217 offset = sizeof(PyDictKeyEntry);
2218 }
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002219 for (i = 0, j = 0; j < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002220 PyObject *value = *value_ptr;
2221 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2222 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 Py_INCREF(value);
2224 PyList_SET_ITEM(v, j, value);
2225 j++;
2226 }
2227 }
2228 assert(j == n);
2229 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002230}
2231
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002232static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002233dict_items(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002234{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002235 PyObject *v;
2236 Py_ssize_t i, j, n;
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002237 Py_ssize_t offset;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002238 PyObject *item, *key;
2239 PyDictKeyEntry *ep;
2240 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 /* Preallocate the list of tuples, to avoid allocations during
2243 * the loop over the items, which could trigger GC, which
2244 * could resize the dict. :-(
2245 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002246 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 n = mp->ma_used;
2248 v = PyList_New(n);
2249 if (v == NULL)
2250 return NULL;
2251 for (i = 0; i < n; i++) {
2252 item = PyTuple_New(2);
2253 if (item == NULL) {
2254 Py_DECREF(v);
2255 return NULL;
2256 }
2257 PyList_SET_ITEM(v, i, item);
2258 }
2259 if (n != mp->ma_used) {
2260 /* Durnit. The allocations caused the dict to resize.
2261 * Just start over, this shouldn't normally happen.
2262 */
2263 Py_DECREF(v);
2264 goto again;
2265 }
2266 /* Nothing we do below makes any function calls. */
Victor Stinner742da042016-09-07 17:40:12 -07002267 ep = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002268 if (mp->ma_values) {
2269 value_ptr = mp->ma_values;
2270 offset = sizeof(PyObject *);
2271 }
2272 else {
2273 value_ptr = &ep[0].me_value;
2274 offset = sizeof(PyDictKeyEntry);
2275 }
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002276 for (i = 0, j = 0; j < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002277 PyObject *value = *value_ptr;
2278 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2279 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 key = ep[i].me_key;
2281 item = PyList_GET_ITEM(v, j);
2282 Py_INCREF(key);
2283 PyTuple_SET_ITEM(item, 0, key);
2284 Py_INCREF(value);
2285 PyTuple_SET_ITEM(item, 1, value);
2286 j++;
2287 }
2288 }
2289 assert(j == n);
2290 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002291}
2292
Larry Hastings5c661892014-01-24 06:17:25 -08002293/*[clinic input]
2294@classmethod
2295dict.fromkeys
Larry Hastings5c661892014-01-24 06:17:25 -08002296 iterable: object
2297 value: object=None
2298 /
2299
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002300Create a new dictionary with keys from iterable and values set to value.
Larry Hastings5c661892014-01-24 06:17:25 -08002301[clinic start generated code]*/
2302
Larry Hastings5c661892014-01-24 06:17:25 -08002303static PyObject *
2304dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002305/*[clinic end generated code: output=8fb98e4b10384999 input=382ba4855d0f74c3]*/
Larry Hastings5c661892014-01-24 06:17:25 -08002306{
Eric Snow96c6af92015-05-29 22:21:39 -06002307 return _PyDict_FromKeys((PyObject *)type, iterable, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002308}
2309
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002310static int
Victor Stinner742da042016-09-07 17:40:12 -07002311dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
2312 const char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 PyObject *arg = NULL;
2315 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002316
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002317 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 result = -1;
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002319 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 else if (arg != NULL) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02002321 _Py_IDENTIFIER(keys);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002322 PyObject *func;
2323 if (_PyObject_LookupAttrId(arg, &PyId_keys, &func) < 0) {
2324 result = -1;
2325 }
2326 else if (func != NULL) {
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002327 Py_DECREF(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 result = PyDict_Merge(self, arg, 1);
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002329 }
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002330 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002331 result = PyDict_MergeFromSeq2(self, arg, 1);
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002332 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 }
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 if (result == 0 && kwds != NULL) {
2336 if (PyArg_ValidateKeywordArguments(kwds))
2337 result = PyDict_Merge(self, kwds, 1);
2338 else
2339 result = -1;
2340 }
2341 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002342}
2343
Victor Stinner91f0d4a2017-01-19 12:45:06 +01002344/* Note: dict.update() uses the METH_VARARGS|METH_KEYWORDS calling convention.
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002345 Using METH_FASTCALL|METH_KEYWORDS would make dict.update(**dict2) calls
2346 slower, see the issue #29312. */
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002347static PyObject *
2348dict_update(PyObject *self, PyObject *args, PyObject *kwds)
2349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 if (dict_update_common(self, args, kwds, "update") != -1)
2351 Py_RETURN_NONE;
2352 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002353}
2354
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002355/* Update unconditionally replaces existing items.
2356 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00002357 otherwise it leaves existing items unchanged.
2358
2359 PyDict_{Update,Merge} update/merge from a mapping object.
2360
Tim Petersf582b822001-12-11 18:51:08 +00002361 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00002362 producing iterable objects of length 2.
2363*/
2364
Tim Petersf582b822001-12-11 18:51:08 +00002365int
Tim Peters1fc240e2001-10-26 05:06:50 +00002366PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
2367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 PyObject *it; /* iter(seq2) */
2369 Py_ssize_t i; /* index into seq2 of current element */
2370 PyObject *item; /* seq2[i] */
2371 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 assert(d != NULL);
2374 assert(PyDict_Check(d));
2375 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 it = PyObject_GetIter(seq2);
2378 if (it == NULL)
2379 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 for (i = 0; ; ++i) {
2382 PyObject *key, *value;
2383 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 fast = NULL;
2386 item = PyIter_Next(it);
2387 if (item == NULL) {
2388 if (PyErr_Occurred())
2389 goto Fail;
2390 break;
2391 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 /* Convert item to sequence, and verify length 2. */
2394 fast = PySequence_Fast(item, "");
2395 if (fast == NULL) {
2396 if (PyErr_ExceptionMatches(PyExc_TypeError))
2397 PyErr_Format(PyExc_TypeError,
2398 "cannot convert dictionary update "
2399 "sequence element #%zd to a sequence",
2400 i);
2401 goto Fail;
2402 }
2403 n = PySequence_Fast_GET_SIZE(fast);
2404 if (n != 2) {
2405 PyErr_Format(PyExc_ValueError,
2406 "dictionary update sequence element #%zd "
2407 "has length %zd; 2 is required",
2408 i, n);
2409 goto Fail;
2410 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 /* Update/merge with this (key, value) pair. */
2413 key = PySequence_Fast_GET_ITEM(fast, 0);
2414 value = PySequence_Fast_GET_ITEM(fast, 1);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002415 Py_INCREF(key);
2416 Py_INCREF(value);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002417 if (override) {
2418 if (PyDict_SetItem(d, key, value) < 0) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002419 Py_DECREF(key);
2420 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 goto Fail;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002422 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002424 else if (PyDict_GetItemWithError(d, key) == NULL) {
2425 if (PyErr_Occurred() || PyDict_SetItem(d, key, value) < 0) {
2426 Py_DECREF(key);
2427 Py_DECREF(value);
2428 goto Fail;
2429 }
2430 }
2431
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002432 Py_DECREF(key);
2433 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 Py_DECREF(fast);
2435 Py_DECREF(item);
2436 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 i = 0;
Victor Stinner0fc91ee2019-04-12 21:51:34 +02002439 ASSERT_CONSISTENT(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00002441Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 Py_XDECREF(item);
2443 Py_XDECREF(fast);
2444 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002445Return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 Py_DECREF(it);
2447 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00002448}
2449
doko@ubuntu.comc96df682016-10-11 08:04:02 +02002450static int
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002451dict_merge(PyObject *a, PyObject *b, int override)
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002452{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002453 PyDictObject *mp, *other;
2454 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -07002455 PyDictKeyEntry *entry, *ep0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002456
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002457 assert(0 <= override && override <= 2);
2458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 /* We accept for the argument either a concrete dictionary object,
2460 * or an abstract "mapping" object. For the former, we can do
2461 * things quite efficiently. For the latter, we only require that
2462 * PyMapping_Keys() and PyObject_GetItem() be supported.
2463 */
2464 if (a == NULL || !PyDict_Check(a) || b == NULL) {
2465 PyErr_BadInternalCall();
2466 return -1;
2467 }
2468 mp = (PyDictObject*)a;
INADA Naoki2aaf98c2018-09-26 12:59:00 +09002469 if (PyDict_Check(b) && (Py_TYPE(b)->tp_iter == (getiterfunc)dict_iter)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 other = (PyDictObject*)b;
2471 if (other == mp || other->ma_used == 0)
2472 /* a.update(a) or a.update({}); nothing to do */
2473 return 0;
2474 if (mp->ma_used == 0)
2475 /* Since the target dict is empty, PyDict_GetItem()
2476 * always returns NULL. Setting override to 1
2477 * skips the unnecessary test.
2478 */
2479 override = 1;
2480 /* Do one big resize at the start, rather than
2481 * incrementally resizing as we insert new items. Expect
2482 * that there will be no (or few) overlapping keys.
2483 */
INADA Naokib1152be2016-10-27 19:26:50 +09002484 if (USABLE_FRACTION(mp->ma_keys->dk_size) < other->ma_used) {
2485 if (dictresize(mp, ESTIMATE_SIZE(mp->ma_used + other->ma_used))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 return -1;
INADA Naokib1152be2016-10-27 19:26:50 +09002487 }
2488 }
Victor Stinner742da042016-09-07 17:40:12 -07002489 ep0 = DK_ENTRIES(other->ma_keys);
2490 for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002491 PyObject *key, *value;
2492 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002493 entry = &ep0[i];
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002494 key = entry->me_key;
2495 hash = entry->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002496 if (other->ma_values)
2497 value = other->ma_values[i];
2498 else
2499 value = entry->me_value;
2500
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002501 if (value != NULL) {
2502 int err = 0;
2503 Py_INCREF(key);
2504 Py_INCREF(value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002505 if (override == 1)
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002506 err = insertdict(mp, key, hash, value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002507 else if (_PyDict_GetItem_KnownHash(a, key, hash) == NULL) {
2508 if (PyErr_Occurred()) {
2509 Py_DECREF(value);
2510 Py_DECREF(key);
2511 return -1;
2512 }
2513 err = insertdict(mp, key, hash, value);
2514 }
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002515 else if (override != 0) {
2516 _PyErr_SetKeyError(key);
2517 Py_DECREF(value);
2518 Py_DECREF(key);
2519 return -1;
2520 }
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002521 Py_DECREF(value);
2522 Py_DECREF(key);
2523 if (err != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 return -1;
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002525
Victor Stinner742da042016-09-07 17:40:12 -07002526 if (n != other->ma_keys->dk_nentries) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002527 PyErr_SetString(PyExc_RuntimeError,
2528 "dict mutated during update");
2529 return -1;
2530 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 }
2532 }
2533 }
2534 else {
2535 /* Do it the generic, slower way */
2536 PyObject *keys = PyMapping_Keys(b);
2537 PyObject *iter;
2538 PyObject *key, *value;
2539 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 if (keys == NULL)
2542 /* Docstring says this is equivalent to E.keys() so
2543 * if E doesn't have a .keys() method we want
2544 * AttributeError to percolate up. Might as well
2545 * do the same for any other error.
2546 */
2547 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 iter = PyObject_GetIter(keys);
2550 Py_DECREF(keys);
2551 if (iter == NULL)
2552 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002555 if (override != 1) {
2556 if (PyDict_GetItemWithError(a, key) != NULL) {
2557 if (override != 0) {
2558 _PyErr_SetKeyError(key);
2559 Py_DECREF(key);
2560 Py_DECREF(iter);
2561 return -1;
2562 }
2563 Py_DECREF(key);
2564 continue;
2565 }
2566 else if (PyErr_Occurred()) {
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002567 Py_DECREF(key);
2568 Py_DECREF(iter);
2569 return -1;
2570 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 }
2572 value = PyObject_GetItem(b, key);
2573 if (value == NULL) {
2574 Py_DECREF(iter);
2575 Py_DECREF(key);
2576 return -1;
2577 }
2578 status = PyDict_SetItem(a, key, value);
2579 Py_DECREF(key);
2580 Py_DECREF(value);
2581 if (status < 0) {
2582 Py_DECREF(iter);
2583 return -1;
2584 }
2585 }
2586 Py_DECREF(iter);
2587 if (PyErr_Occurred())
2588 /* Iterator completed, via error */
2589 return -1;
2590 }
Victor Stinner0fc91ee2019-04-12 21:51:34 +02002591 ASSERT_CONSISTENT(a);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002593}
2594
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002595int
2596PyDict_Update(PyObject *a, PyObject *b)
2597{
2598 return dict_merge(a, b, 1);
2599}
2600
2601int
2602PyDict_Merge(PyObject *a, PyObject *b, int override)
2603{
2604 /* XXX Deprecate override not in (0, 1). */
2605 return dict_merge(a, b, override != 0);
2606}
2607
2608int
2609_PyDict_MergeEx(PyObject *a, PyObject *b, int override)
2610{
2611 return dict_merge(a, b, override);
2612}
2613
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002614static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302615dict_copy(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002618}
2619
2620PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002621PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 PyObject *copy;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002624 PyDictObject *mp;
2625 Py_ssize_t i, n;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 if (o == NULL || !PyDict_Check(o)) {
2628 PyErr_BadInternalCall();
2629 return NULL;
2630 }
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002631
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002632 mp = (PyDictObject *)o;
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002633 if (mp->ma_used == 0) {
2634 /* The dict is empty; just return a new dict. */
2635 return PyDict_New();
2636 }
2637
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002638 if (_PyDict_HasSplitTable(mp)) {
2639 PyDictObject *split_copy;
Victor Stinner742da042016-09-07 17:40:12 -07002640 Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
2641 PyObject **newvalues;
2642 newvalues = new_values(size);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002643 if (newvalues == NULL)
2644 return PyErr_NoMemory();
2645 split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
2646 if (split_copy == NULL) {
2647 free_values(newvalues);
2648 return NULL;
2649 }
2650 split_copy->ma_values = newvalues;
2651 split_copy->ma_keys = mp->ma_keys;
2652 split_copy->ma_used = mp->ma_used;
INADA Naokid1c82c52018-04-03 11:43:53 +09002653 split_copy->ma_version_tag = DICT_NEXT_VERSION();
INADA Naokia7576492018-11-14 18:39:27 +09002654 dictkeys_incref(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002655 for (i = 0, n = size; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002656 PyObject *value = mp->ma_values[i];
2657 Py_XINCREF(value);
2658 split_copy->ma_values[i] = value;
2659 }
Benjamin Peterson7ce67e42012-04-24 10:32:57 -04002660 if (_PyObject_GC_IS_TRACKED(mp))
2661 _PyObject_GC_TRACK(split_copy);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002662 return (PyObject *)split_copy;
2663 }
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002664
2665 if (PyDict_CheckExact(mp) && mp->ma_values == NULL &&
2666 (mp->ma_used >= (mp->ma_keys->dk_nentries * 2) / 3))
2667 {
2668 /* Use fast-copy if:
2669
2670 (1) 'mp' is an instance of a subclassed dict; and
2671
2672 (2) 'mp' is not a split-dict; and
2673
2674 (3) if 'mp' is non-compact ('del' operation does not resize dicts),
2675 do fast-copy only if it has at most 1/3 non-used keys.
2676
Ville Skyttä61f82e02018-04-20 23:08:45 +03002677 The last condition (3) is important to guard against a pathological
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002678 case when a large dict is almost emptied with multiple del/pop
2679 operations and copied after that. In cases like this, we defer to
2680 PyDict_Merge, which produces a compacted copy.
2681 */
2682 return clone_combined_dict(mp);
2683 }
2684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 copy = PyDict_New();
2686 if (copy == NULL)
2687 return NULL;
2688 if (PyDict_Merge(copy, o, 1) == 0)
2689 return copy;
2690 Py_DECREF(copy);
2691 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002692}
2693
Martin v. Löwis18e16552006-02-15 17:27:45 +00002694Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00002695PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00002696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 if (mp == NULL || !PyDict_Check(mp)) {
2698 PyErr_BadInternalCall();
2699 return -1;
2700 }
2701 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00002702}
2703
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002704PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002705PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 if (mp == NULL || !PyDict_Check(mp)) {
2708 PyErr_BadInternalCall();
2709 return NULL;
2710 }
2711 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002712}
2713
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002714PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002715PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 if (mp == NULL || !PyDict_Check(mp)) {
2718 PyErr_BadInternalCall();
2719 return NULL;
2720 }
2721 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002722}
2723
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002724PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002725PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 if (mp == NULL || !PyDict_Check(mp)) {
2728 PyErr_BadInternalCall();
2729 return NULL;
2730 }
2731 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002732}
2733
Tim Peterse63415e2001-05-08 04:38:29 +00002734/* Return 1 if dicts equal, 0 if not, -1 if error.
2735 * Gets out as soon as any difference is detected.
2736 * Uses only Py_EQ comparison.
2737 */
2738static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002739dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00002740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00002742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 if (a->ma_used != b->ma_used)
2744 /* can't be equal if # of entries differ */
2745 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Victor Stinner742da042016-09-07 17:40:12 -07002747 for (i = 0; i < a->ma_keys->dk_nentries; i++) {
2748 PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002749 PyObject *aval;
2750 if (a->ma_values)
2751 aval = a->ma_values[i];
2752 else
2753 aval = ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 if (aval != NULL) {
2755 int cmp;
2756 PyObject *bval;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002757 PyObject *key = ep->me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 /* temporarily bump aval's refcount to ensure it stays
2759 alive until we're done with it */
2760 Py_INCREF(aval);
2761 /* ditto for key */
2762 Py_INCREF(key);
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002763 /* reuse the known hash value */
INADA Naoki778928b2017-08-03 23:45:15 +09002764 b->ma_keys->dk_lookup(b, key, ep->me_hash, &bval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 if (bval == NULL) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002766 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 Py_DECREF(aval);
2768 if (PyErr_Occurred())
2769 return -1;
2770 return 0;
2771 }
2772 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002773 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 Py_DECREF(aval);
2775 if (cmp <= 0) /* error or not equal */
2776 return cmp;
2777 }
2778 }
2779 return 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002780}
Tim Peterse63415e2001-05-08 04:38:29 +00002781
2782static PyObject *
2783dict_richcompare(PyObject *v, PyObject *w, int op)
2784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 int cmp;
2786 PyObject *res;
Tim Peterse63415e2001-05-08 04:38:29 +00002787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 if (!PyDict_Check(v) || !PyDict_Check(w)) {
2789 res = Py_NotImplemented;
2790 }
2791 else if (op == Py_EQ || op == Py_NE) {
2792 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
2793 if (cmp < 0)
2794 return NULL;
2795 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
2796 }
2797 else
2798 res = Py_NotImplemented;
2799 Py_INCREF(res);
2800 return res;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002801}
Tim Peterse63415e2001-05-08 04:38:29 +00002802
Larry Hastings61272b72014-01-07 12:41:53 -08002803/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002804
2805@coexist
2806dict.__contains__
2807
2808 key: object
2809 /
2810
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002811True if the dictionary has the specified key, else False.
Larry Hastings61272b72014-01-07 12:41:53 -08002812[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002813
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002814static PyObject *
Larry Hastingsc2047262014-01-25 20:43:29 -08002815dict___contains__(PyDictObject *self, PyObject *key)
Serhiy Storchaka19d25972017-02-04 08:05:07 +02002816/*[clinic end generated code: output=a3d03db709ed6e6b input=fe1cb42ad831e820]*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002817{
Larry Hastingsc2047262014-01-25 20:43:29 -08002818 register PyDictObject *mp = self;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002819 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002820 Py_ssize_t ix;
INADA Naokiba609772016-12-07 20:41:42 +09002821 PyObject *value;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002824 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 hash = PyObject_Hash(key);
2826 if (hash == -1)
2827 return NULL;
2828 }
INADA Naoki778928b2017-08-03 23:45:15 +09002829 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002830 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002832 if (ix == DKIX_EMPTY || value == NULL)
Victor Stinner742da042016-09-07 17:40:12 -07002833 Py_RETURN_FALSE;
2834 Py_RETURN_TRUE;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002835}
2836
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002837/*[clinic input]
2838dict.get
2839
2840 key: object
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002841 default: object = None
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002842 /
2843
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002844Return the value for key if key is in the dictionary, else default.
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002845[clinic start generated code]*/
2846
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002847static PyObject *
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002848dict_get_impl(PyDictObject *self, PyObject *key, PyObject *default_value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002849/*[clinic end generated code: output=bba707729dee05bf input=279ddb5790b6b107]*/
Barry Warsawc38c5da1997-10-06 17:49:20 +00002850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002852 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002853 Py_ssize_t ix;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002856 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 hash = PyObject_Hash(key);
2858 if (hash == -1)
2859 return NULL;
2860 }
INADA Naoki778928b2017-08-03 23:45:15 +09002861 ix = (self->ma_keys->dk_lookup) (self, key, hash, &val);
Victor Stinner742da042016-09-07 17:40:12 -07002862 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002864 if (ix == DKIX_EMPTY || val == NULL) {
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002865 val = default_value;
INADA Naokiba609772016-12-07 20:41:42 +09002866 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 Py_INCREF(val);
2868 return val;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002869}
2870
Benjamin Peterson00e98862013-03-07 22:16:29 -05002871PyObject *
2872PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
Guido van Rossum164452c2000-08-08 16:12:54 +00002873{
Benjamin Peterson00e98862013-03-07 22:16:29 -05002874 PyDictObject *mp = (PyDictObject *)d;
INADA Naoki93f26f72016-11-02 18:45:16 +09002875 PyObject *value;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002876 Py_hash_t hash;
Guido van Rossum164452c2000-08-08 16:12:54 +00002877
Benjamin Peterson00e98862013-03-07 22:16:29 -05002878 if (!PyDict_Check(d)) {
2879 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 return NULL;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002881 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002884 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 hash = PyObject_Hash(key);
2886 if (hash == -1)
2887 return NULL;
2888 }
Inada Naoki2ddc7f62019-03-18 20:38:33 +09002889 if (mp->ma_keys == Py_EMPTY_KEYS) {
2890 if (insert_to_emptydict(mp, key, hash, defaultobj) < 0) {
2891 return NULL;
2892 }
2893 return defaultobj;
2894 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002895
2896 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
2897 if (insertion_resize(mp) < 0)
2898 return NULL;
2899 }
2900
INADA Naoki778928b2017-08-03 23:45:15 +09002901 Py_ssize_t ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002902 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 return NULL;
INADA Naoki93f26f72016-11-02 18:45:16 +09002904
2905 if (_PyDict_HasSplitTable(mp) &&
INADA Naokiba609772016-12-07 20:41:42 +09002906 ((ix >= 0 && value == NULL && mp->ma_used != ix) ||
INADA Naoki93f26f72016-11-02 18:45:16 +09002907 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
2908 if (insertion_resize(mp) < 0) {
2909 return NULL;
2910 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002911 ix = DKIX_EMPTY;
2912 }
2913
2914 if (ix == DKIX_EMPTY) {
2915 PyDictKeyEntry *ep, *ep0;
2916 value = defaultobj;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002917 if (mp->ma_keys->dk_usable <= 0) {
Victor Stinner3c336c52016-09-12 14:17:40 +02002918 if (insertion_resize(mp) < 0) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002919 return NULL;
Victor Stinner3c336c52016-09-12 14:17:40 +02002920 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002921 }
INADA Naoki778928b2017-08-03 23:45:15 +09002922 Py_ssize_t hashpos = find_empty_slot(mp->ma_keys, hash);
INADA Naoki93f26f72016-11-02 18:45:16 +09002923 ep0 = DK_ENTRIES(mp->ma_keys);
2924 ep = &ep0[mp->ma_keys->dk_nentries];
INADA Naokia7576492018-11-14 18:39:27 +09002925 dictkeys_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
Benjamin Petersonb1efa532013-03-04 09:47:50 -05002926 Py_INCREF(key);
INADA Naoki93f26f72016-11-02 18:45:16 +09002927 Py_INCREF(value);
2928 MAINTAIN_TRACKING(mp, key, value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002929 ep->me_key = key;
2930 ep->me_hash = hash;
INADA Naokiba609772016-12-07 20:41:42 +09002931 if (_PyDict_HasSplitTable(mp)) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002932 assert(mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
2933 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Victor Stinner742da042016-09-07 17:40:12 -07002934 }
2935 else {
INADA Naoki93f26f72016-11-02 18:45:16 +09002936 ep->me_value = value;
Victor Stinner742da042016-09-07 17:40:12 -07002937 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002938 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07002939 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naoki93f26f72016-11-02 18:45:16 +09002940 mp->ma_keys->dk_usable--;
2941 mp->ma_keys->dk_nentries++;
2942 assert(mp->ma_keys->dk_usable >= 0);
2943 }
INADA Naokiba609772016-12-07 20:41:42 +09002944 else if (value == NULL) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002945 value = defaultobj;
2946 assert(_PyDict_HasSplitTable(mp));
2947 assert(ix == mp->ma_used);
2948 Py_INCREF(value);
2949 MAINTAIN_TRACKING(mp, key, value);
INADA Naokiba609772016-12-07 20:41:42 +09002950 mp->ma_values[ix] = value;
INADA Naoki93f26f72016-11-02 18:45:16 +09002951 mp->ma_used++;
2952 mp->ma_version_tag = DICT_NEXT_VERSION();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002954
Victor Stinner0fc91ee2019-04-12 21:51:34 +02002955 ASSERT_CONSISTENT(mp);
INADA Naoki93f26f72016-11-02 18:45:16 +09002956 return value;
Guido van Rossum164452c2000-08-08 16:12:54 +00002957}
2958
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002959/*[clinic input]
2960dict.setdefault
2961
2962 key: object
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002963 default: object = None
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002964 /
2965
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002966Insert key with a value of default if key is not in the dictionary.
2967
2968Return the value for key if key is in the dictionary, else default.
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002969[clinic start generated code]*/
2970
Benjamin Peterson00e98862013-03-07 22:16:29 -05002971static PyObject *
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002972dict_setdefault_impl(PyDictObject *self, PyObject *key,
2973 PyObject *default_value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002974/*[clinic end generated code: output=f8c1101ebf69e220 input=0f063756e815fd9d]*/
Benjamin Peterson00e98862013-03-07 22:16:29 -05002975{
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002976 PyObject *val;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002977
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002978 val = PyDict_SetDefault((PyObject *)self, key, default_value);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002979 Py_XINCREF(val);
2980 return val;
2981}
Guido van Rossum164452c2000-08-08 16:12:54 +00002982
2983static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302984dict_clear(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 PyDict_Clear((PyObject *)mp);
2987 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002988}
2989
Inada Naokid4c66472019-07-02 20:32:43 +09002990/*
2991We don't use Argument Clinic for dict.pop because it doesn't support
2992custom signature for now.
2993*/
2994PyDoc_STRVAR(dict_pop__doc__,
2995"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\
2996If key is not found, d is returned if given, otherwise KeyError is raised");
Inada Naoki9e4f2f32019-04-12 16:11:28 +09002997
Inada Naokid4c66472019-07-02 20:32:43 +09002998#define DICT_POP_METHODDEF \
2999 {"pop", (PyCFunction)(void(*)(void))dict_pop, METH_FASTCALL, dict_pop__doc__},
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003000
Guido van Rossumba6ab842000-12-12 22:02:18 +00003001static PyObject *
Inada Naokid4c66472019-07-02 20:32:43 +09003002dict_pop(PyDictObject *self, PyObject *const *args, Py_ssize_t nargs)
Guido van Rossume027d982002-04-12 15:11:59 +00003003{
Inada Naokid4c66472019-07-02 20:32:43 +09003004 PyObject *return_value = NULL;
3005 PyObject *key;
3006 PyObject *default_value = NULL;
3007
3008 if (!_PyArg_CheckPositional("pop", nargs, 1, 2)) {
3009 goto exit;
3010 }
3011 key = args[0];
3012 if (nargs < 2) {
3013 goto skip_optional;
3014 }
3015 default_value = args[1];
3016skip_optional:
3017 return_value = _PyDict_Pop((PyObject*)self, key, default_value);
3018
3019exit:
3020 return return_value;
Guido van Rossume027d982002-04-12 15:11:59 +00003021}
3022
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003023/*[clinic input]
3024dict.popitem
3025
3026Remove and return a (key, value) pair as a 2-tuple.
3027
3028Pairs are returned in LIFO (last-in, first-out) order.
3029Raises KeyError if the dict is empty.
3030[clinic start generated code]*/
3031
Guido van Rossume027d982002-04-12 15:11:59 +00003032static PyObject *
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003033dict_popitem_impl(PyDictObject *self)
3034/*[clinic end generated code: output=e65fcb04420d230d input=1c38a49f21f64941]*/
Guido van Rossumba6ab842000-12-12 22:02:18 +00003035{
Victor Stinner742da042016-09-07 17:40:12 -07003036 Py_ssize_t i, j;
3037 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 PyObject *res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00003039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 /* Allocate the result tuple before checking the size. Believe it
3041 * or not, this allocation could trigger a garbage collection which
3042 * could empty the dict, so if we checked the size first and that
3043 * happened, the result would be an infinite loop (searching for an
3044 * entry that no longer exists). Note that the usual popitem()
3045 * idiom is "while d: k, v = d.popitem()". so needing to throw the
3046 * tuple away if the dict *is* empty isn't a significant
3047 * inefficiency -- possible, but unlikely in practice.
3048 */
3049 res = PyTuple_New(2);
3050 if (res == NULL)
3051 return NULL;
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003052 if (self->ma_used == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 Py_DECREF(res);
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003054 PyErr_SetString(PyExc_KeyError, "popitem(): dictionary is empty");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 return NULL;
3056 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003057 /* Convert split table to combined table */
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003058 if (self->ma_keys->dk_lookup == lookdict_split) {
3059 if (dictresize(self, DK_SIZE(self->ma_keys))) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003060 Py_DECREF(res);
3061 return NULL;
3062 }
3063 }
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003064 ENSURE_ALLOWS_DELETIONS(self);
Victor Stinner742da042016-09-07 17:40:12 -07003065
3066 /* Pop last item */
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003067 ep0 = DK_ENTRIES(self->ma_keys);
3068 i = self->ma_keys->dk_nentries - 1;
Victor Stinner742da042016-09-07 17:40:12 -07003069 while (i >= 0 && ep0[i].me_value == NULL) {
3070 i--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 }
Victor Stinner742da042016-09-07 17:40:12 -07003072 assert(i >= 0);
3073
3074 ep = &ep0[i];
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003075 j = lookdict_index(self->ma_keys, ep->me_hash, i);
Victor Stinner742da042016-09-07 17:40:12 -07003076 assert(j >= 0);
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003077 assert(dictkeys_get_index(self->ma_keys, j) == i);
3078 dictkeys_set_index(self->ma_keys, j, DKIX_DUMMY);
Victor Stinner742da042016-09-07 17:40:12 -07003079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 PyTuple_SET_ITEM(res, 0, ep->me_key);
3081 PyTuple_SET_ITEM(res, 1, ep->me_value);
Victor Stinner742da042016-09-07 17:40:12 -07003082 ep->me_key = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 ep->me_value = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07003084 /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003085 self->ma_keys->dk_nentries = i;
3086 self->ma_used--;
3087 self->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner0fc91ee2019-04-12 21:51:34 +02003088 ASSERT_CONSISTENT(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 return res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00003090}
3091
Jeremy Hylton8caad492000-06-23 14:18:11 +00003092static int
3093dict_traverse(PyObject *op, visitproc visit, void *arg)
3094{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003095 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson55f44522016-09-05 12:12:59 -07003096 PyDictKeysObject *keys = mp->ma_keys;
Serhiy Storchaka46825d22016-09-26 21:29:34 +03003097 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Victor Stinner742da042016-09-07 17:40:12 -07003098 Py_ssize_t i, n = keys->dk_nentries;
3099
Benjamin Peterson55f44522016-09-05 12:12:59 -07003100 if (keys->dk_lookup == lookdict) {
3101 for (i = 0; i < n; i++) {
3102 if (entries[i].me_value != NULL) {
3103 Py_VISIT(entries[i].me_value);
3104 Py_VISIT(entries[i].me_key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003105 }
3106 }
Victor Stinner742da042016-09-07 17:40:12 -07003107 }
3108 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003109 if (mp->ma_values != NULL) {
Benjamin Peterson55f44522016-09-05 12:12:59 -07003110 for (i = 0; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003111 Py_VISIT(mp->ma_values[i]);
3112 }
3113 }
3114 else {
Benjamin Peterson55f44522016-09-05 12:12:59 -07003115 for (i = 0; i < n; i++) {
3116 Py_VISIT(entries[i].me_value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003117 }
3118 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 }
3120 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00003121}
3122
3123static int
3124dict_tp_clear(PyObject *op)
3125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 PyDict_Clear(op);
3127 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00003128}
3129
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003130static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003131
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003132Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003133_PyDict_SizeOf(PyDictObject *mp)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003134{
Victor Stinner742da042016-09-07 17:40:12 -07003135 Py_ssize_t size, usable, res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003136
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003137 size = DK_SIZE(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07003138 usable = USABLE_FRACTION(size);
3139
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02003140 res = _PyObject_SIZE(Py_TYPE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003141 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07003142 res += usable * sizeof(PyObject*);
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003143 /* If the dictionary is split, the keys portion is accounted-for
3144 in the type object. */
3145 if (mp->ma_keys->dk_refcnt == 1)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003146 res += (sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003147 + DK_IXSIZE(mp->ma_keys) * size
3148 + sizeof(PyDictKeyEntry) * usable);
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003149 return res;
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003150}
3151
3152Py_ssize_t
3153_PyDict_KeysSize(PyDictKeysObject *keys)
3154{
Victor Stinner98ee9d52016-09-08 09:33:56 -07003155 return (sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003156 + DK_IXSIZE(keys) * DK_SIZE(keys)
3157 + USABLE_FRACTION(DK_SIZE(keys)) * sizeof(PyDictKeyEntry));
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003158}
3159
doko@ubuntu.com17210f52016-01-14 14:04:59 +01003160static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303161dict_sizeof(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003162{
3163 return PyLong_FromSsize_t(_PyDict_SizeOf(mp));
3164}
3165
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003166PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
3167
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003168PyDoc_STRVAR(sizeof__doc__,
3169"D.__sizeof__() -> size of D in memory, in bytes");
3170
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003171PyDoc_STRVAR(update__doc__,
Brett Cannonf2754162013-05-11 14:46:48 -04003172"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n\
3173If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]\n\
3174If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n\
3175In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00003176
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003177PyDoc_STRVAR(clear__doc__,
3178"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00003179
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003180PyDoc_STRVAR(copy__doc__,
3181"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00003182
Guido van Rossumb90c8482007-02-10 01:11:45 +00003183/* Forward */
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303184static PyObject *dictkeys_new(PyObject *, PyObject *);
3185static PyObject *dictitems_new(PyObject *, PyObject *);
3186static PyObject *dictvalues_new(PyObject *, PyObject *);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003187
Guido van Rossum45c85d12007-07-27 16:31:40 +00003188PyDoc_STRVAR(keys__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 "D.keys() -> a set-like object providing a view on D's keys");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003190PyDoc_STRVAR(items__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 "D.items() -> a set-like object providing a view on D's items");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003192PyDoc_STRVAR(values__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 "D.values() -> an object providing a view on D's values");
Guido van Rossumb90c8482007-02-10 01:11:45 +00003194
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003195static PyMethodDef mapp_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -07003196 DICT___CONTAINS___METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003197 {"__getitem__", (PyCFunction)(void(*)(void))dict_subscript, METH_O | METH_COEXIST,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 getitem__doc__},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003199 {"__sizeof__", (PyCFunction)(void(*)(void))dict_sizeof, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 sizeof__doc__},
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01003201 DICT_GET_METHODDEF
3202 DICT_SETDEFAULT_METHODDEF
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003203 DICT_POP_METHODDEF
3204 DICT_POPITEM_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303205 {"keys", dictkeys_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 keys__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303207 {"items", dictitems_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 items__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303209 {"values", dictvalues_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 values__doc__},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003211 {"update", (PyCFunction)(void(*)(void))dict_update, METH_VARARGS | METH_KEYWORDS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 update__doc__},
Larry Hastings5c661892014-01-24 06:17:25 -08003213 DICT_FROMKEYS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
3215 clear__doc__},
3216 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
3217 copy__doc__},
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003218 DICT___REVERSED___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003220};
3221
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00003222/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00003223int
3224PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003225{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003226 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07003227 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09003229 PyObject *value;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003232 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 hash = PyObject_Hash(key);
3234 if (hash == -1)
3235 return -1;
3236 }
INADA Naoki778928b2017-08-03 23:45:15 +09003237 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07003238 if (ix == DKIX_ERROR)
3239 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09003240 return (ix != DKIX_EMPTY && value != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003241}
3242
Thomas Wouterscf297e42007-02-23 15:07:44 +00003243/* Internal version of PyDict_Contains used when the hash value is already known */
3244int
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003245_PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00003246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09003248 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -07003249 Py_ssize_t ix;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003250
INADA Naoki778928b2017-08-03 23:45:15 +09003251 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07003252 if (ix == DKIX_ERROR)
3253 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09003254 return (ix != DKIX_EMPTY && value != NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00003255}
3256
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003257/* Hack to implement "key in dict" */
3258static PySequenceMethods dict_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 0, /* sq_length */
3260 0, /* sq_concat */
3261 0, /* sq_repeat */
3262 0, /* sq_item */
3263 0, /* sq_slice */
3264 0, /* sq_ass_item */
3265 0, /* sq_ass_slice */
3266 PyDict_Contains, /* sq_contains */
3267 0, /* sq_inplace_concat */
3268 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003269};
3270
Guido van Rossum09e563a2001-05-01 12:10:21 +00003271static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003272dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 PyObject *self;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003275 PyDictObject *d;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 assert(type != NULL && type->tp_alloc != NULL);
3278 self = type->tp_alloc(type, 0);
Victor Stinnera9f61a52013-07-16 22:17:26 +02003279 if (self == NULL)
3280 return NULL;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003281 d = (PyDictObject *)self;
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003282
Victor Stinnera9f61a52013-07-16 22:17:26 +02003283 /* The object has been implicitly tracked by tp_alloc */
3284 if (type == &PyDict_Type)
3285 _PyObject_GC_UNTRACK(d);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003286
3287 d->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07003288 d->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07003289 d->ma_keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003290 if (d->ma_keys == NULL) {
3291 Py_DECREF(self);
3292 return NULL;
3293 }
Victor Stinner0fc91ee2019-04-12 21:51:34 +02003294 ASSERT_CONSISTENT(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 return self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003296}
3297
Tim Peters25786c02001-09-02 08:22:48 +00003298static int
3299dict_init(PyObject *self, PyObject *args, PyObject *kwds)
3300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003301 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00003302}
3303
Tim Peters6d6c1a32001-08-02 04:15:00 +00003304static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003305dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00003306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003308}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003309
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003310PyDoc_STRVAR(dictionary_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00003311"dict() -> new empty dictionary\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00003312"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003313" (key, value) pairs\n"
3314"dict(iterable) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00003315" d = {}\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003316" for k, v in iterable:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00003317" d[k] = v\n"
3318"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
3319" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00003320
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003321PyTypeObject PyDict_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3323 "dict",
3324 sizeof(PyDictObject),
3325 0,
3326 (destructor)dict_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003327 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 0, /* tp_getattr */
3329 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003330 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 (reprfunc)dict_repr, /* tp_repr */
3332 0, /* tp_as_number */
3333 &dict_as_sequence, /* tp_as_sequence */
3334 &dict_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003335 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 0, /* tp_call */
3337 0, /* tp_str */
3338 PyObject_GenericGetAttr, /* tp_getattro */
3339 0, /* tp_setattro */
3340 0, /* tp_as_buffer */
3341 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3342 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
3343 dictionary_doc, /* tp_doc */
3344 dict_traverse, /* tp_traverse */
3345 dict_tp_clear, /* tp_clear */
3346 dict_richcompare, /* tp_richcompare */
3347 0, /* tp_weaklistoffset */
3348 (getiterfunc)dict_iter, /* tp_iter */
3349 0, /* tp_iternext */
3350 mapp_methods, /* tp_methods */
3351 0, /* tp_members */
3352 0, /* tp_getset */
3353 0, /* tp_base */
3354 0, /* tp_dict */
3355 0, /* tp_descr_get */
3356 0, /* tp_descr_set */
3357 0, /* tp_dictoffset */
3358 dict_init, /* tp_init */
3359 PyType_GenericAlloc, /* tp_alloc */
3360 dict_new, /* tp_new */
3361 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003362};
3363
Victor Stinner3c1e4812012-03-26 22:10:51 +02003364PyObject *
3365_PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
3366{
3367 PyObject *kv;
3368 kv = _PyUnicode_FromId(key); /* borrowed */
Victor Stinner5b3b1002013-07-22 23:50:57 +02003369 if (kv == NULL) {
3370 PyErr_Clear();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003371 return NULL;
Victor Stinner5b3b1002013-07-22 23:50:57 +02003372 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003373 return PyDict_GetItem(dp, kv);
3374}
3375
Guido van Rossum3cca2451997-05-16 14:23:33 +00003376/* For backward compatibility with old dictionary interface */
3377
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003378PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003379PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 PyObject *kv, *rv;
3382 kv = PyUnicode_FromString(key);
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003383 if (kv == NULL) {
3384 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 return NULL;
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003386 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 rv = PyDict_GetItem(v, kv);
3388 Py_DECREF(kv);
3389 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003390}
3391
3392int
Victor Stinner3c1e4812012-03-26 22:10:51 +02003393_PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
3394{
3395 PyObject *kv;
3396 kv = _PyUnicode_FromId(key); /* borrowed */
3397 if (kv == NULL)
3398 return -1;
3399 return PyDict_SetItem(v, kv, item);
3400}
3401
3402int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003403PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 PyObject *kv;
3406 int err;
3407 kv = PyUnicode_FromString(key);
3408 if (kv == NULL)
3409 return -1;
3410 PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
3411 err = PyDict_SetItem(v, kv, item);
3412 Py_DECREF(kv);
3413 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003414}
3415
3416int
Victor Stinner5fd2e5a2013-11-06 18:58:22 +01003417_PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
3418{
3419 PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
3420 if (kv == NULL)
3421 return -1;
3422 return PyDict_DelItem(v, kv);
3423}
3424
3425int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003426PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 PyObject *kv;
3429 int err;
3430 kv = PyUnicode_FromString(key);
3431 if (kv == NULL)
3432 return -1;
3433 err = PyDict_DelItem(v, kv);
3434 Py_DECREF(kv);
3435 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003436}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003437
Raymond Hettinger019a1482004-03-18 02:41:19 +00003438/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003439
3440typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 PyObject_HEAD
3442 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
3443 Py_ssize_t di_used;
3444 Py_ssize_t di_pos;
3445 PyObject* di_result; /* reusable result tuple for iteritems */
3446 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003447} dictiterobject;
3448
3449static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003450dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 dictiterobject *di;
3453 di = PyObject_GC_New(dictiterobject, itertype);
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003454 if (di == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 return NULL;
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003456 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 Py_INCREF(dict);
3458 di->di_dict = dict;
3459 di->di_used = dict->ma_used;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 di->len = dict->ma_used;
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003461 if ((itertype == &PyDictRevIterKey_Type ||
3462 itertype == &PyDictRevIterItem_Type ||
3463 itertype == &PyDictRevIterValue_Type) && dict->ma_used) {
3464 di->di_pos = dict->ma_keys->dk_nentries - 1;
3465 }
3466 else {
3467 di->di_pos = 0;
3468 }
3469 if (itertype == &PyDictIterItem_Type ||
3470 itertype == &PyDictRevIterItem_Type) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
3472 if (di->di_result == NULL) {
3473 Py_DECREF(di);
3474 return NULL;
3475 }
3476 }
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003477 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 di->di_result = NULL;
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003479 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480 _PyObject_GC_TRACK(di);
3481 return (PyObject *)di;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003482}
3483
3484static void
3485dictiter_dealloc(dictiterobject *di)
3486{
INADA Naokia6296d32017-08-24 14:55:17 +09003487 /* bpo-31095: UnTrack is needed before calling any callbacks */
3488 _PyObject_GC_UNTRACK(di);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 Py_XDECREF(di->di_dict);
3490 Py_XDECREF(di->di_result);
3491 PyObject_GC_Del(di);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003492}
3493
3494static int
3495dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
3496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 Py_VISIT(di->di_dict);
3498 Py_VISIT(di->di_result);
3499 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003500}
3501
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003502static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303503dictiter_len(dictiterobject *di, PyObject *Py_UNUSED(ignored))
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 Py_ssize_t len = 0;
3506 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
3507 len = di->len;
3508 return PyLong_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003509}
3510
Guido van Rossumb90c8482007-02-10 01:11:45 +00003511PyDoc_STRVAR(length_hint_doc,
3512 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003513
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003514static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303515dictiter_reduce(dictiterobject *di, PyObject *Py_UNUSED(ignored));
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003516
3517PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3518
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003519static PyMethodDef dictiter_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003520 {"__length_hint__", (PyCFunction)(void(*)(void))dictiter_len, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 length_hint_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003522 {"__reduce__", (PyCFunction)(void(*)(void))dictiter_reduce, METH_NOARGS,
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003523 reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003525};
3526
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003527static PyObject*
3528dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00003529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 PyObject *key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003531 Py_ssize_t i;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003532 PyDictKeysObject *k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003533 PyDictObject *d = di->di_dict;
Guido van Rossum213c7a62001-04-23 14:08:49 +00003534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 if (d == NULL)
3536 return NULL;
3537 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00003538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 if (di->di_used != d->ma_used) {
3540 PyErr_SetString(PyExc_RuntimeError,
3541 "dictionary changed size during iteration");
3542 di->di_used = -1; /* Make this state sticky */
3543 return NULL;
3544 }
Guido van Rossum2147df72002-07-16 20:30:22 +00003545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 i = di->di_pos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003547 k = d->ma_keys;
INADA Naokica2d8be2016-11-04 16:59:10 +09003548 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003549 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003550 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003551 goto fail;
3552 key = DK_ENTRIES(k)[i].me_key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003553 assert(d->ma_values[i] != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003554 }
3555 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003556 Py_ssize_t n = k->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003557 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
3558 while (i < n && entry_ptr->me_value == NULL) {
3559 entry_ptr++;
3560 i++;
3561 }
3562 if (i >= n)
3563 goto fail;
3564 key = entry_ptr->me_key;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003565 }
Thomas Perl796cc6e2019-03-28 07:03:25 +01003566 // We found an element (key), but did not expect it
3567 if (di->len == 0) {
3568 PyErr_SetString(PyExc_RuntimeError,
3569 "dictionary keys changed during iteration");
3570 goto fail;
3571 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 di->di_pos = i+1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 di->len--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 Py_INCREF(key);
3575 return key;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003576
3577fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003579 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003581}
3582
Raymond Hettinger019a1482004-03-18 02:41:19 +00003583PyTypeObject PyDictIterKey_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3585 "dict_keyiterator", /* tp_name */
3586 sizeof(dictiterobject), /* tp_basicsize */
3587 0, /* tp_itemsize */
3588 /* methods */
3589 (destructor)dictiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003590 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 0, /* tp_getattr */
3592 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003593 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 0, /* tp_repr */
3595 0, /* tp_as_number */
3596 0, /* tp_as_sequence */
3597 0, /* tp_as_mapping */
3598 0, /* tp_hash */
3599 0, /* tp_call */
3600 0, /* tp_str */
3601 PyObject_GenericGetAttr, /* tp_getattro */
3602 0, /* tp_setattro */
3603 0, /* tp_as_buffer */
3604 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3605 0, /* tp_doc */
3606 (traverseproc)dictiter_traverse, /* tp_traverse */
3607 0, /* tp_clear */
3608 0, /* tp_richcompare */
3609 0, /* tp_weaklistoffset */
3610 PyObject_SelfIter, /* tp_iter */
3611 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
3612 dictiter_methods, /* tp_methods */
3613 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003614};
3615
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003616static PyObject *
3617dictiter_iternextvalue(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 PyObject *value;
INADA Naokica2d8be2016-11-04 16:59:10 +09003620 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003623 if (d == NULL)
3624 return NULL;
3625 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003627 if (di->di_used != d->ma_used) {
3628 PyErr_SetString(PyExc_RuntimeError,
3629 "dictionary changed size during iteration");
3630 di->di_used = -1; /* Make this state sticky */
3631 return NULL;
3632 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 i = di->di_pos;
INADA Naokica2d8be2016-11-04 16:59:10 +09003635 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003636 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003637 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003638 goto fail;
INADA Naokica2d8be2016-11-04 16:59:10 +09003639 value = d->ma_values[i];
3640 assert(value != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003641 }
3642 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003643 Py_ssize_t n = d->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003644 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3645 while (i < n && entry_ptr->me_value == NULL) {
3646 entry_ptr++;
3647 i++;
3648 }
3649 if (i >= n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 goto fail;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003651 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 }
Thomas Perlb8311cf2019-04-02 11:30:10 +02003653 // We found an element, but did not expect it
3654 if (di->len == 0) {
3655 PyErr_SetString(PyExc_RuntimeError,
3656 "dictionary keys changed during iteration");
3657 goto fail;
3658 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 di->di_pos = i+1;
3660 di->len--;
3661 Py_INCREF(value);
3662 return value;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003663
3664fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003666 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003668}
3669
3670PyTypeObject PyDictIterValue_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3672 "dict_valueiterator", /* tp_name */
3673 sizeof(dictiterobject), /* tp_basicsize */
3674 0, /* tp_itemsize */
3675 /* methods */
3676 (destructor)dictiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003677 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 0, /* tp_getattr */
3679 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003680 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 0, /* tp_repr */
3682 0, /* tp_as_number */
3683 0, /* tp_as_sequence */
3684 0, /* tp_as_mapping */
3685 0, /* tp_hash */
3686 0, /* tp_call */
3687 0, /* tp_str */
3688 PyObject_GenericGetAttr, /* tp_getattro */
3689 0, /* tp_setattro */
3690 0, /* tp_as_buffer */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003691 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692 0, /* tp_doc */
3693 (traverseproc)dictiter_traverse, /* tp_traverse */
3694 0, /* tp_clear */
3695 0, /* tp_richcompare */
3696 0, /* tp_weaklistoffset */
3697 PyObject_SelfIter, /* tp_iter */
3698 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
3699 dictiter_methods, /* tp_methods */
3700 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003701};
3702
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003703static PyObject *
3704dictiter_iternextitem(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003705{
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003706 PyObject *key, *value, *result;
INADA Naokica2d8be2016-11-04 16:59:10 +09003707 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003710 if (d == NULL)
3711 return NULL;
3712 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714 if (di->di_used != d->ma_used) {
3715 PyErr_SetString(PyExc_RuntimeError,
3716 "dictionary changed size during iteration");
3717 di->di_used = -1; /* Make this state sticky */
3718 return NULL;
3719 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003721 i = di->di_pos;
INADA Naokica2d8be2016-11-04 16:59:10 +09003722 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003723 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003724 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003725 goto fail;
3726 key = DK_ENTRIES(d->ma_keys)[i].me_key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003727 value = d->ma_values[i];
3728 assert(value != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003729 }
3730 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003731 Py_ssize_t n = d->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003732 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3733 while (i < n && entry_ptr->me_value == NULL) {
3734 entry_ptr++;
3735 i++;
3736 }
3737 if (i >= n)
3738 goto fail;
3739 key = entry_ptr->me_key;
3740 value = entry_ptr->me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003741 }
Thomas Perlb8311cf2019-04-02 11:30:10 +02003742 // We found an element, but did not expect it
3743 if (di->len == 0) {
3744 PyErr_SetString(PyExc_RuntimeError,
3745 "dictionary keys changed during iteration");
3746 goto fail;
3747 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 di->di_pos = i+1;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003749 di->len--;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003750 Py_INCREF(key);
3751 Py_INCREF(value);
3752 result = di->di_result;
3753 if (Py_REFCNT(result) == 1) {
3754 PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
3755 PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
3756 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3757 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 Py_INCREF(result);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003759 Py_DECREF(oldkey);
3760 Py_DECREF(oldvalue);
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003761 }
3762 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 result = PyTuple_New(2);
3764 if (result == NULL)
3765 return NULL;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003766 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3767 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003770
3771fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003773 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003774 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003775}
3776
3777PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3779 "dict_itemiterator", /* tp_name */
3780 sizeof(dictiterobject), /* tp_basicsize */
3781 0, /* tp_itemsize */
3782 /* methods */
3783 (destructor)dictiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003784 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003785 0, /* tp_getattr */
3786 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003787 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 0, /* tp_repr */
3789 0, /* tp_as_number */
3790 0, /* tp_as_sequence */
3791 0, /* tp_as_mapping */
3792 0, /* tp_hash */
3793 0, /* tp_call */
3794 0, /* tp_str */
3795 PyObject_GenericGetAttr, /* tp_getattro */
3796 0, /* tp_setattro */
3797 0, /* tp_as_buffer */
3798 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3799 0, /* tp_doc */
3800 (traverseproc)dictiter_traverse, /* tp_traverse */
3801 0, /* tp_clear */
3802 0, /* tp_richcompare */
3803 0, /* tp_weaklistoffset */
3804 PyObject_SelfIter, /* tp_iter */
3805 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
3806 dictiter_methods, /* tp_methods */
3807 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003808};
Guido van Rossumb90c8482007-02-10 01:11:45 +00003809
3810
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003811/* dictreviter */
3812
3813static PyObject *
3814dictreviter_iternext(dictiterobject *di)
3815{
3816 PyDictObject *d = di->di_dict;
3817
3818 if (d == NULL) {
3819 return NULL;
3820 }
3821 assert (PyDict_Check(d));
3822
3823 if (di->di_used != d->ma_used) {
3824 PyErr_SetString(PyExc_RuntimeError,
3825 "dictionary changed size during iteration");
3826 di->di_used = -1; /* Make this state sticky */
3827 return NULL;
3828 }
3829
3830 Py_ssize_t i = di->di_pos;
3831 PyDictKeysObject *k = d->ma_keys;
3832 PyObject *key, *value, *result;
3833
3834 if (d->ma_values) {
3835 if (i < 0) {
3836 goto fail;
3837 }
3838 key = DK_ENTRIES(k)[i].me_key;
3839 value = d->ma_values[i];
3840 assert (value != NULL);
3841 }
3842 else {
3843 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
3844 while (i >= 0 && entry_ptr->me_value == NULL) {
3845 entry_ptr--;
3846 i--;
3847 }
3848 if (i < 0) {
3849 goto fail;
3850 }
3851 key = entry_ptr->me_key;
3852 value = entry_ptr->me_value;
3853 }
3854 di->di_pos = i-1;
3855 di->len--;
3856
3857 if (Py_TYPE(di) == &PyDictRevIterKey_Type) {
3858 Py_INCREF(key);
3859 return key;
3860 }
3861 else if (Py_TYPE(di) == &PyDictRevIterValue_Type) {
3862 Py_INCREF(value);
3863 return value;
3864 }
3865 else if (Py_TYPE(di) == &PyDictRevIterItem_Type) {
3866 Py_INCREF(key);
3867 Py_INCREF(value);
3868 result = di->di_result;
3869 if (Py_REFCNT(result) == 1) {
3870 PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
3871 PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
3872 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3873 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
3874 Py_INCREF(result);
3875 Py_DECREF(oldkey);
3876 Py_DECREF(oldvalue);
3877 }
3878 else {
3879 result = PyTuple_New(2);
3880 if (result == NULL) {
3881 return NULL;
3882 }
3883 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3884 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
3885 }
3886 return result;
3887 }
3888 else {
3889 Py_UNREACHABLE();
3890 }
3891
3892fail:
3893 di->di_dict = NULL;
3894 Py_DECREF(d);
3895 return NULL;
3896}
3897
3898PyTypeObject PyDictRevIterKey_Type = {
3899 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3900 "dict_reversekeyiterator",
3901 sizeof(dictiterobject),
3902 .tp_dealloc = (destructor)dictiter_dealloc,
3903 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3904 .tp_traverse = (traverseproc)dictiter_traverse,
3905 .tp_iter = PyObject_SelfIter,
3906 .tp_iternext = (iternextfunc)dictreviter_iternext,
3907 .tp_methods = dictiter_methods
3908};
3909
3910
3911/*[clinic input]
3912dict.__reversed__
3913
3914Return a reverse iterator over the dict keys.
3915[clinic start generated code]*/
3916
3917static PyObject *
3918dict___reversed___impl(PyDictObject *self)
3919/*[clinic end generated code: output=e674483336d1ed51 input=23210ef3477d8c4d]*/
3920{
3921 assert (PyDict_Check(self));
3922 return dictiter_new(self, &PyDictRevIterKey_Type);
3923}
3924
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003925static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303926dictiter_reduce(dictiterobject *di, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003927{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003928 _Py_IDENTIFIER(iter);
Sergey Fedoseev63958442018-10-20 05:43:33 +05003929 /* copy the iterator state */
3930 dictiterobject tmp = *di;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003931 Py_XINCREF(tmp.di_dict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003932
Sergey Fedoseev63958442018-10-20 05:43:33 +05003933 PyObject *list = PySequence_List((PyObject*)&tmp);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003934 Py_XDECREF(tmp.di_dict);
Sergey Fedoseev63958442018-10-20 05:43:33 +05003935 if (list == NULL) {
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003936 return NULL;
3937 }
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003938 return Py_BuildValue("N(N)", _PyEval_GetBuiltinId(&PyId_iter), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003939}
3940
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003941PyTypeObject PyDictRevIterItem_Type = {
3942 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3943 "dict_reverseitemiterator",
3944 sizeof(dictiterobject),
3945 .tp_dealloc = (destructor)dictiter_dealloc,
3946 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3947 .tp_traverse = (traverseproc)dictiter_traverse,
3948 .tp_iter = PyObject_SelfIter,
3949 .tp_iternext = (iternextfunc)dictreviter_iternext,
3950 .tp_methods = dictiter_methods
3951};
3952
3953PyTypeObject PyDictRevIterValue_Type = {
3954 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3955 "dict_reversevalueiterator",
3956 sizeof(dictiterobject),
3957 .tp_dealloc = (destructor)dictiter_dealloc,
3958 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3959 .tp_traverse = (traverseproc)dictiter_traverse,
3960 .tp_iter = PyObject_SelfIter,
3961 .tp_iternext = (iternextfunc)dictreviter_iternext,
3962 .tp_methods = dictiter_methods
3963};
3964
Guido van Rossum3ac67412007-02-10 18:55:06 +00003965/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003966/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00003967/***********************************************/
3968
Guido van Rossumb90c8482007-02-10 01:11:45 +00003969/* The instance lay-out is the same for all three; but the type differs. */
3970
Guido van Rossumb90c8482007-02-10 01:11:45 +00003971static void
Eric Snow96c6af92015-05-29 22:21:39 -06003972dictview_dealloc(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003973{
INADA Naokia6296d32017-08-24 14:55:17 +09003974 /* bpo-31095: UnTrack is needed before calling any callbacks */
3975 _PyObject_GC_UNTRACK(dv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 Py_XDECREF(dv->dv_dict);
3977 PyObject_GC_Del(dv);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003978}
3979
3980static int
Eric Snow96c6af92015-05-29 22:21:39 -06003981dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003983 Py_VISIT(dv->dv_dict);
3984 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003985}
3986
Guido van Rossum83825ac2007-02-10 04:54:19 +00003987static Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003988dictview_len(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003990 Py_ssize_t len = 0;
3991 if (dv->dv_dict != NULL)
3992 len = dv->dv_dict->ma_used;
3993 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003994}
3995
Eric Snow96c6af92015-05-29 22:21:39 -06003996PyObject *
3997_PyDictView_New(PyObject *dict, PyTypeObject *type)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003998{
Eric Snow96c6af92015-05-29 22:21:39 -06003999 _PyDictViewObject *dv;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004000 if (dict == NULL) {
4001 PyErr_BadInternalCall();
4002 return NULL;
4003 }
4004 if (!PyDict_Check(dict)) {
4005 /* XXX Get rid of this restriction later */
4006 PyErr_Format(PyExc_TypeError,
4007 "%s() requires a dict argument, not '%s'",
4008 type->tp_name, dict->ob_type->tp_name);
4009 return NULL;
4010 }
Eric Snow96c6af92015-05-29 22:21:39 -06004011 dv = PyObject_GC_New(_PyDictViewObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004012 if (dv == NULL)
4013 return NULL;
4014 Py_INCREF(dict);
4015 dv->dv_dict = (PyDictObject *)dict;
4016 _PyObject_GC_TRACK(dv);
4017 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00004018}
4019
Neal Norwitze36f2ba2007-02-26 23:12:28 +00004020/* TODO(guido): The views objects are not complete:
4021
4022 * support more set operations
4023 * support arbitrary mappings?
4024 - either these should be static or exported in dictobject.h
4025 - if public then they should probably be in builtins
4026*/
4027
Guido van Rossumaac530c2007-08-24 22:33:45 +00004028/* Return 1 if self is a subset of other, iterating over self;
4029 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00004030static int
4031all_contained_in(PyObject *self, PyObject *other)
4032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004033 PyObject *iter = PyObject_GetIter(self);
4034 int ok = 1;
Guido van Rossumd9214d12007-02-12 02:23:40 +00004035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004036 if (iter == NULL)
4037 return -1;
4038 for (;;) {
4039 PyObject *next = PyIter_Next(iter);
4040 if (next == NULL) {
4041 if (PyErr_Occurred())
4042 ok = -1;
4043 break;
4044 }
4045 ok = PySequence_Contains(other, next);
4046 Py_DECREF(next);
4047 if (ok <= 0)
4048 break;
4049 }
4050 Py_DECREF(iter);
4051 return ok;
Guido van Rossumd9214d12007-02-12 02:23:40 +00004052}
4053
4054static PyObject *
4055dictview_richcompare(PyObject *self, PyObject *other, int op)
4056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 Py_ssize_t len_self, len_other;
4058 int ok;
4059 PyObject *result;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 assert(self != NULL);
4062 assert(PyDictViewSet_Check(self));
4063 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00004064
Brian Curtindfc80e32011-08-10 20:28:54 -05004065 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
4066 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 len_self = PyObject_Size(self);
4069 if (len_self < 0)
4070 return NULL;
4071 len_other = PyObject_Size(other);
4072 if (len_other < 0)
4073 return NULL;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004075 ok = 0;
4076 switch(op) {
Guido van Rossumaac530c2007-08-24 22:33:45 +00004077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 case Py_NE:
4079 case Py_EQ:
4080 if (len_self == len_other)
4081 ok = all_contained_in(self, other);
4082 if (op == Py_NE && ok >= 0)
4083 ok = !ok;
4084 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 case Py_LT:
4087 if (len_self < len_other)
4088 ok = all_contained_in(self, other);
4089 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004091 case Py_LE:
4092 if (len_self <= len_other)
4093 ok = all_contained_in(self, other);
4094 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 case Py_GT:
4097 if (len_self > len_other)
4098 ok = all_contained_in(other, self);
4099 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004101 case Py_GE:
4102 if (len_self >= len_other)
4103 ok = all_contained_in(other, self);
4104 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 }
4107 if (ok < 0)
4108 return NULL;
4109 result = ok ? Py_True : Py_False;
4110 Py_INCREF(result);
4111 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00004112}
4113
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00004114static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004115dictview_repr(_PyDictViewObject *dv)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00004116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004117 PyObject *seq;
bennorthd7773d92018-01-26 15:46:01 +00004118 PyObject *result = NULL;
4119 Py_ssize_t rc;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00004120
bennorthd7773d92018-01-26 15:46:01 +00004121 rc = Py_ReprEnter((PyObject *)dv);
4122 if (rc != 0) {
4123 return rc > 0 ? PyUnicode_FromString("...") : NULL;
4124 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004125 seq = PySequence_List((PyObject *)dv);
bennorthd7773d92018-01-26 15:46:01 +00004126 if (seq == NULL) {
4127 goto Done;
4128 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004129 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
4130 Py_DECREF(seq);
bennorthd7773d92018-01-26 15:46:01 +00004131
4132Done:
4133 Py_ReprLeave((PyObject *)dv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 return result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00004135}
4136
Guido van Rossum3ac67412007-02-10 18:55:06 +00004137/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004138
4139static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004140dictkeys_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004142 if (dv->dv_dict == NULL) {
4143 Py_RETURN_NONE;
4144 }
4145 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00004146}
4147
4148static int
Eric Snow96c6af92015-05-29 22:21:39 -06004149dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00004150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004151 if (dv->dv_dict == NULL)
4152 return 0;
4153 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004154}
4155
Guido van Rossum83825ac2007-02-10 04:54:19 +00004156static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157 (lenfunc)dictview_len, /* sq_length */
4158 0, /* sq_concat */
4159 0, /* sq_repeat */
4160 0, /* sq_item */
4161 0, /* sq_slice */
4162 0, /* sq_ass_item */
4163 0, /* sq_ass_slice */
4164 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004165};
4166
Guido van Rossum523259b2007-08-24 23:41:22 +00004167static PyObject*
4168dictviews_sub(PyObject* self, PyObject *other)
4169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004170 PyObject *result = PySet_New(self);
4171 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004172 _Py_IDENTIFIER(difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004174 if (result == NULL)
4175 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004176
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08004177 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 if (tmp == NULL) {
4179 Py_DECREF(result);
4180 return NULL;
4181 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004183 Py_DECREF(tmp);
4184 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004185}
4186
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004187PyObject*
4188_PyDictView_Intersect(PyObject* self, PyObject *other)
Guido van Rossum523259b2007-08-24 23:41:22 +00004189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 PyObject *result = PySet_New(self);
4191 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004192 _Py_IDENTIFIER(intersection_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004194 if (result == NULL)
4195 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004196
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08004197 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_intersection_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004198 if (tmp == NULL) {
4199 Py_DECREF(result);
4200 return NULL;
4201 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004203 Py_DECREF(tmp);
4204 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004205}
4206
4207static PyObject*
4208dictviews_or(PyObject* self, PyObject *other)
4209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 PyObject *result = PySet_New(self);
4211 PyObject *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02004212 _Py_IDENTIFIER(update);
Victor Stinnerd1a9cc22011-10-13 22:51:17 +02004213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214 if (result == NULL)
4215 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004216
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08004217 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 if (tmp == NULL) {
4219 Py_DECREF(result);
4220 return NULL;
4221 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004223 Py_DECREF(tmp);
4224 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004225}
4226
4227static PyObject*
4228dictviews_xor(PyObject* self, PyObject *other)
4229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004230 PyObject *result = PySet_New(self);
4231 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004232 _Py_IDENTIFIER(symmetric_difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004234 if (result == NULL)
4235 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004236
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08004237 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_symmetric_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004238 if (tmp == NULL) {
4239 Py_DECREF(result);
4240 return NULL;
4241 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243 Py_DECREF(tmp);
4244 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004245}
4246
4247static PyNumberMethods dictviews_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 0, /*nb_add*/
4249 (binaryfunc)dictviews_sub, /*nb_subtract*/
4250 0, /*nb_multiply*/
4251 0, /*nb_remainder*/
4252 0, /*nb_divmod*/
4253 0, /*nb_power*/
4254 0, /*nb_negative*/
4255 0, /*nb_positive*/
4256 0, /*nb_absolute*/
4257 0, /*nb_bool*/
4258 0, /*nb_invert*/
4259 0, /*nb_lshift*/
4260 0, /*nb_rshift*/
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004261 (binaryfunc)_PyDictView_Intersect, /*nb_and*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 (binaryfunc)dictviews_xor, /*nb_xor*/
4263 (binaryfunc)dictviews_or, /*nb_or*/
Guido van Rossum523259b2007-08-24 23:41:22 +00004264};
4265
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004266static PyObject*
4267dictviews_isdisjoint(PyObject *self, PyObject *other)
4268{
4269 PyObject *it;
4270 PyObject *item = NULL;
4271
4272 if (self == other) {
Eric Snow96c6af92015-05-29 22:21:39 -06004273 if (dictview_len((_PyDictViewObject *)self) == 0)
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004274 Py_RETURN_TRUE;
4275 else
4276 Py_RETURN_FALSE;
4277 }
4278
4279 /* Iterate over the shorter object (only if other is a set,
4280 * because PySequence_Contains may be expensive otherwise): */
4281 if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
Eric Snow96c6af92015-05-29 22:21:39 -06004282 Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004283 Py_ssize_t len_other = PyObject_Size(other);
4284 if (len_other == -1)
4285 return NULL;
4286
4287 if ((len_other > len_self)) {
4288 PyObject *tmp = other;
4289 other = self;
4290 self = tmp;
4291 }
4292 }
4293
4294 it = PyObject_GetIter(other);
4295 if (it == NULL)
4296 return NULL;
4297
4298 while ((item = PyIter_Next(it)) != NULL) {
4299 int contains = PySequence_Contains(self, item);
4300 Py_DECREF(item);
4301 if (contains == -1) {
4302 Py_DECREF(it);
4303 return NULL;
4304 }
4305
4306 if (contains) {
4307 Py_DECREF(it);
4308 Py_RETURN_FALSE;
4309 }
4310 }
4311 Py_DECREF(it);
4312 if (PyErr_Occurred())
4313 return NULL; /* PyIter_Next raised an exception. */
4314 Py_RETURN_TRUE;
4315}
4316
4317PyDoc_STRVAR(isdisjoint_doc,
4318"Return True if the view and the given iterable have a null intersection.");
4319
Serhiy Storchaka81524022018-11-27 13:05:02 +02004320static PyObject* dictkeys_reversed(_PyDictViewObject *dv, PyObject *Py_UNUSED(ignored));
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004321
4322PyDoc_STRVAR(reversed_keys_doc,
4323"Return a reverse iterator over the dict keys.");
4324
Guido van Rossumb90c8482007-02-10 01:11:45 +00004325static PyMethodDef dictkeys_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004326 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4327 isdisjoint_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02004328 {"__reversed__", (PyCFunction)(void(*)(void))dictkeys_reversed, METH_NOARGS,
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004329 reversed_keys_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004330 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004331};
4332
4333PyTypeObject PyDictKeys_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4335 "dict_keys", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004336 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004337 0, /* tp_itemsize */
4338 /* methods */
4339 (destructor)dictview_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004340 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 0, /* tp_getattr */
4342 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004343 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344 (reprfunc)dictview_repr, /* tp_repr */
4345 &dictviews_as_number, /* tp_as_number */
4346 &dictkeys_as_sequence, /* tp_as_sequence */
4347 0, /* tp_as_mapping */
4348 0, /* tp_hash */
4349 0, /* tp_call */
4350 0, /* tp_str */
4351 PyObject_GenericGetAttr, /* tp_getattro */
4352 0, /* tp_setattro */
4353 0, /* tp_as_buffer */
4354 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4355 0, /* tp_doc */
4356 (traverseproc)dictview_traverse, /* tp_traverse */
4357 0, /* tp_clear */
4358 dictview_richcompare, /* tp_richcompare */
4359 0, /* tp_weaklistoffset */
4360 (getiterfunc)dictkeys_iter, /* tp_iter */
4361 0, /* tp_iternext */
4362 dictkeys_methods, /* tp_methods */
4363 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004364};
4365
4366static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304367dictkeys_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004368{
Eric Snow96c6af92015-05-29 22:21:39 -06004369 return _PyDictView_New(dict, &PyDictKeys_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004370}
4371
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004372static PyObject *
Serhiy Storchaka81524022018-11-27 13:05:02 +02004373dictkeys_reversed(_PyDictViewObject *dv, PyObject *Py_UNUSED(ignored))
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004374{
4375 if (dv->dv_dict == NULL) {
4376 Py_RETURN_NONE;
4377 }
4378 return dictiter_new(dv->dv_dict, &PyDictRevIterKey_Type);
4379}
4380
Guido van Rossum3ac67412007-02-10 18:55:06 +00004381/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004382
4383static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004384dictitems_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004386 if (dv->dv_dict == NULL) {
4387 Py_RETURN_NONE;
4388 }
4389 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00004390}
4391
4392static int
Eric Snow96c6af92015-05-29 22:21:39 -06004393dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00004394{
Serhiy Storchaka753bca32017-05-20 12:30:02 +03004395 int result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 PyObject *key, *value, *found;
4397 if (dv->dv_dict == NULL)
4398 return 0;
4399 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
4400 return 0;
4401 key = PyTuple_GET_ITEM(obj, 0);
4402 value = PyTuple_GET_ITEM(obj, 1);
Raymond Hettinger6692f012016-09-18 21:46:08 -07004403 found = PyDict_GetItemWithError((PyObject *)dv->dv_dict, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004404 if (found == NULL) {
4405 if (PyErr_Occurred())
4406 return -1;
4407 return 0;
4408 }
Serhiy Storchaka753bca32017-05-20 12:30:02 +03004409 Py_INCREF(found);
4410 result = PyObject_RichCompareBool(value, found, Py_EQ);
4411 Py_DECREF(found);
4412 return result;
Guido van Rossumb90c8482007-02-10 01:11:45 +00004413}
4414
Guido van Rossum83825ac2007-02-10 04:54:19 +00004415static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 (lenfunc)dictview_len, /* sq_length */
4417 0, /* sq_concat */
4418 0, /* sq_repeat */
4419 0, /* sq_item */
4420 0, /* sq_slice */
4421 0, /* sq_ass_item */
4422 0, /* sq_ass_slice */
4423 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004424};
4425
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004426static PyObject* dictitems_reversed(_PyDictViewObject *dv);
4427
4428PyDoc_STRVAR(reversed_items_doc,
4429"Return a reverse iterator over the dict items.");
4430
Guido van Rossumb90c8482007-02-10 01:11:45 +00004431static PyMethodDef dictitems_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004432 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4433 isdisjoint_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02004434 {"__reversed__", (PyCFunction)(void(*)(void))dictitems_reversed, METH_NOARGS,
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004435 reversed_items_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004437};
4438
4439PyTypeObject PyDictItems_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4441 "dict_items", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004442 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 0, /* tp_itemsize */
4444 /* methods */
4445 (destructor)dictview_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004446 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004447 0, /* tp_getattr */
4448 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004449 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 (reprfunc)dictview_repr, /* tp_repr */
4451 &dictviews_as_number, /* tp_as_number */
4452 &dictitems_as_sequence, /* tp_as_sequence */
4453 0, /* tp_as_mapping */
4454 0, /* tp_hash */
4455 0, /* tp_call */
4456 0, /* tp_str */
4457 PyObject_GenericGetAttr, /* tp_getattro */
4458 0, /* tp_setattro */
4459 0, /* tp_as_buffer */
4460 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4461 0, /* tp_doc */
4462 (traverseproc)dictview_traverse, /* tp_traverse */
4463 0, /* tp_clear */
4464 dictview_richcompare, /* tp_richcompare */
4465 0, /* tp_weaklistoffset */
4466 (getiterfunc)dictitems_iter, /* tp_iter */
4467 0, /* tp_iternext */
4468 dictitems_methods, /* tp_methods */
4469 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004470};
4471
4472static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304473dictitems_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004474{
Eric Snow96c6af92015-05-29 22:21:39 -06004475 return _PyDictView_New(dict, &PyDictItems_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004476}
4477
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004478static PyObject *
4479dictitems_reversed(_PyDictViewObject *dv)
4480{
4481 if (dv->dv_dict == NULL) {
4482 Py_RETURN_NONE;
4483 }
4484 return dictiter_new(dv->dv_dict, &PyDictRevIterItem_Type);
4485}
4486
Guido van Rossum3ac67412007-02-10 18:55:06 +00004487/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004488
4489static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004490dictvalues_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004492 if (dv->dv_dict == NULL) {
4493 Py_RETURN_NONE;
4494 }
4495 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004496}
4497
Guido van Rossum83825ac2007-02-10 04:54:19 +00004498static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004499 (lenfunc)dictview_len, /* sq_length */
4500 0, /* sq_concat */
4501 0, /* sq_repeat */
4502 0, /* sq_item */
4503 0, /* sq_slice */
4504 0, /* sq_ass_item */
4505 0, /* sq_ass_slice */
4506 (objobjproc)0, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004507};
4508
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004509static PyObject* dictvalues_reversed(_PyDictViewObject *dv);
4510
4511PyDoc_STRVAR(reversed_values_doc,
4512"Return a reverse iterator over the dict values.");
4513
Guido van Rossumb90c8482007-02-10 01:11:45 +00004514static PyMethodDef dictvalues_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02004515 {"__reversed__", (PyCFunction)(void(*)(void))dictvalues_reversed, METH_NOARGS,
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004516 reversed_values_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004518};
4519
4520PyTypeObject PyDictValues_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004521 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4522 "dict_values", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004523 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004524 0, /* tp_itemsize */
4525 /* methods */
4526 (destructor)dictview_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004527 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 0, /* tp_getattr */
4529 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004530 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004531 (reprfunc)dictview_repr, /* tp_repr */
4532 0, /* tp_as_number */
4533 &dictvalues_as_sequence, /* tp_as_sequence */
4534 0, /* tp_as_mapping */
4535 0, /* tp_hash */
4536 0, /* tp_call */
4537 0, /* tp_str */
4538 PyObject_GenericGetAttr, /* tp_getattro */
4539 0, /* tp_setattro */
4540 0, /* tp_as_buffer */
4541 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4542 0, /* tp_doc */
4543 (traverseproc)dictview_traverse, /* tp_traverse */
4544 0, /* tp_clear */
4545 0, /* tp_richcompare */
4546 0, /* tp_weaklistoffset */
4547 (getiterfunc)dictvalues_iter, /* tp_iter */
4548 0, /* tp_iternext */
4549 dictvalues_methods, /* tp_methods */
4550 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004551};
4552
4553static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304554dictvalues_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004555{
Eric Snow96c6af92015-05-29 22:21:39 -06004556 return _PyDictView_New(dict, &PyDictValues_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004557}
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004558
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004559static PyObject *
4560dictvalues_reversed(_PyDictViewObject *dv)
4561{
4562 if (dv->dv_dict == NULL) {
4563 Py_RETURN_NONE;
4564 }
4565 return dictiter_new(dv->dv_dict, &PyDictRevIterValue_Type);
4566}
4567
4568
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004569/* Returns NULL if cannot allocate a new PyDictKeysObject,
4570 but does not set an error */
4571PyDictKeysObject *
4572_PyDict_NewKeysForClass(void)
4573{
Victor Stinner742da042016-09-07 17:40:12 -07004574 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004575 if (keys == NULL)
4576 PyErr_Clear();
4577 else
4578 keys->dk_lookup = lookdict_split;
4579 return keys;
4580}
4581
4582#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
4583
4584PyObject *
4585PyObject_GenericGetDict(PyObject *obj, void *context)
4586{
4587 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
4588 if (dictptr == NULL) {
4589 PyErr_SetString(PyExc_AttributeError,
4590 "This object has no __dict__");
4591 return NULL;
4592 }
4593 dict = *dictptr;
4594 if (dict == NULL) {
4595 PyTypeObject *tp = Py_TYPE(obj);
4596 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
INADA Naokia7576492018-11-14 18:39:27 +09004597 dictkeys_incref(CACHED_KEYS(tp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004598 *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
4599 }
4600 else {
4601 *dictptr = dict = PyDict_New();
4602 }
4603 }
4604 Py_XINCREF(dict);
4605 return dict;
4606}
4607
4608int
4609_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
Victor Stinner742da042016-09-07 17:40:12 -07004610 PyObject *key, PyObject *value)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004611{
4612 PyObject *dict;
4613 int res;
4614 PyDictKeysObject *cached;
4615
4616 assert(dictptr != NULL);
4617 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
4618 assert(dictptr != NULL);
4619 dict = *dictptr;
4620 if (dict == NULL) {
INADA Naokia7576492018-11-14 18:39:27 +09004621 dictkeys_incref(cached);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004622 dict = new_dict_with_shared_keys(cached);
4623 if (dict == NULL)
4624 return -1;
4625 *dictptr = dict;
4626 }
4627 if (value == NULL) {
4628 res = PyDict_DelItem(dict, key);
INADA Naoki2294f3a2017-02-12 13:51:30 +09004629 // Since key sharing dict doesn't allow deletion, PyDict_DelItem()
4630 // always converts dict to combined form.
4631 if ((cached = CACHED_KEYS(tp)) != NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004632 CACHED_KEYS(tp) = NULL;
INADA Naokia7576492018-11-14 18:39:27 +09004633 dictkeys_decref(cached);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004634 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01004635 }
4636 else {
INADA Naoki2294f3a2017-02-12 13:51:30 +09004637 int was_shared = (cached == ((PyDictObject *)dict)->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004638 res = PyDict_SetItem(dict, key, value);
INADA Naoki2294f3a2017-02-12 13:51:30 +09004639 if (was_shared &&
4640 (cached = CACHED_KEYS(tp)) != NULL &&
4641 cached != ((PyDictObject *)dict)->ma_keys) {
Victor Stinner3d3f2642016-12-15 17:21:23 +01004642 /* PyDict_SetItem() may call dictresize and convert split table
4643 * into combined table. In such case, convert it to split
4644 * table again and update type's shared key only when this is
4645 * the only dict sharing key with the type.
4646 *
4647 * This is to allow using shared key in class like this:
4648 *
4649 * class C:
4650 * def __init__(self):
4651 * # one dict resize happens
4652 * self.a, self.b, self.c = 1, 2, 3
4653 * self.d, self.e, self.f = 4, 5, 6
4654 * a = C()
4655 */
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004656 if (cached->dk_refcnt == 1) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004657 CACHED_KEYS(tp) = make_keys_shared(dict);
Victor Stinner742da042016-09-07 17:40:12 -07004658 }
4659 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004660 CACHED_KEYS(tp) = NULL;
4661 }
INADA Naokia7576492018-11-14 18:39:27 +09004662 dictkeys_decref(cached);
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004663 if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
4664 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004665 }
4666 }
4667 } else {
4668 dict = *dictptr;
4669 if (dict == NULL) {
4670 dict = PyDict_New();
4671 if (dict == NULL)
4672 return -1;
4673 *dictptr = dict;
4674 }
4675 if (value == NULL) {
4676 res = PyDict_DelItem(dict, key);
4677 } else {
4678 res = PyDict_SetItem(dict, key, value);
4679 }
4680 }
4681 return res;
4682}
4683
4684void
4685_PyDictKeys_DecRef(PyDictKeysObject *keys)
4686{
INADA Naokia7576492018-11-14 18:39:27 +09004687 dictkeys_decref(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004688}