blob: 164fe2a273b1d27b027cc4d6f05155d8d14fb4c7 [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
dalgarno359143c2019-09-10 10:45:07 +010042dk_entries is array of PyDictKeyEntry. Its size is USABLE_FRACTION(dk_size).
Victor Stinner742da042016-09-07 17:40:12 -070043DK_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
Victor Stinnerbed48172019-08-27 00:12:32 +0200285_PyDict_Fini(void)
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100286{
287 PyDict_ClearFreeList();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000288}
289
Victor Stinner742da042016-09-07 17:40:12 -0700290#define DK_SIZE(dk) ((dk)->dk_size)
291#if SIZEOF_VOID_P > 4
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700292#define DK_IXSIZE(dk) \
293 (DK_SIZE(dk) <= 0xff ? \
294 1 : DK_SIZE(dk) <= 0xffff ? \
295 2 : DK_SIZE(dk) <= 0xffffffff ? \
Benjamin Peterson3c569292016-09-08 13:16:41 -0700296 4 : sizeof(int64_t))
Victor Stinner742da042016-09-07 17:40:12 -0700297#else
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700298#define DK_IXSIZE(dk) \
299 (DK_SIZE(dk) <= 0xff ? \
300 1 : DK_SIZE(dk) <= 0xffff ? \
Benjamin Peterson3c569292016-09-08 13:16:41 -0700301 2 : sizeof(int32_t))
Victor Stinner742da042016-09-07 17:40:12 -0700302#endif
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700303#define DK_ENTRIES(dk) \
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700304 ((PyDictKeyEntry*)(&((int8_t*)((dk)->dk_indices))[DK_SIZE(dk) * DK_IXSIZE(dk)]))
Victor Stinner742da042016-09-07 17:40:12 -0700305
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400306#define DK_MASK(dk) (((dk)->dk_size)-1)
307#define IS_POWER_OF_2(x) (((x) & (x-1)) == 0)
308
INADA Naokia7576492018-11-14 18:39:27 +0900309static void free_keys_object(PyDictKeysObject *keys);
310
311static inline void
312dictkeys_incref(PyDictKeysObject *dk)
313{
314 _Py_INC_REFTOTAL;
315 dk->dk_refcnt++;
316}
317
318static inline void
319dictkeys_decref(PyDictKeysObject *dk)
320{
321 assert(dk->dk_refcnt > 0);
322 _Py_DEC_REFTOTAL;
323 if (--dk->dk_refcnt == 0) {
324 free_keys_object(dk);
325 }
326}
327
Victor Stinner742da042016-09-07 17:40:12 -0700328/* lookup indices. returns DKIX_EMPTY, DKIX_DUMMY, or ix >=0 */
Benjamin Peterson73222252016-09-08 09:58:47 -0700329static inline Py_ssize_t
INADA Naokia7576492018-11-14 18:39:27 +0900330dictkeys_get_index(PyDictKeysObject *keys, Py_ssize_t i)
Victor Stinner742da042016-09-07 17:40:12 -0700331{
332 Py_ssize_t s = DK_SIZE(keys);
Victor Stinner71211e32016-09-08 10:52:46 -0700333 Py_ssize_t ix;
334
Victor Stinner742da042016-09-07 17:40:12 -0700335 if (s <= 0xff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700336 int8_t *indices = (int8_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700337 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700338 }
339 else if (s <= 0xffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700340 int16_t *indices = (int16_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700341 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700342 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700343#if SIZEOF_VOID_P > 4
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300344 else if (s > 0xffffffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700345 int64_t *indices = (int64_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700346 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700347 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700348#endif
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300349 else {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700350 int32_t *indices = (int32_t*)(keys->dk_indices);
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300351 ix = indices[i];
352 }
Victor Stinner71211e32016-09-08 10:52:46 -0700353 assert(ix >= DKIX_DUMMY);
354 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700355}
356
357/* write to indices. */
Benjamin Peterson73222252016-09-08 09:58:47 -0700358static inline void
INADA Naokia7576492018-11-14 18:39:27 +0900359dictkeys_set_index(PyDictKeysObject *keys, Py_ssize_t i, Py_ssize_t ix)
Victor Stinner742da042016-09-07 17:40:12 -0700360{
361 Py_ssize_t s = DK_SIZE(keys);
Victor Stinner71211e32016-09-08 10:52:46 -0700362
363 assert(ix >= DKIX_DUMMY);
364
Victor Stinner742da042016-09-07 17:40:12 -0700365 if (s <= 0xff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700366 int8_t *indices = (int8_t*)(keys->dk_indices);
Victor Stinner71211e32016-09-08 10:52:46 -0700367 assert(ix <= 0x7f);
Victor Stinner208857e2016-09-08 11:35:46 -0700368 indices[i] = (char)ix;
Victor Stinner742da042016-09-07 17:40:12 -0700369 }
370 else if (s <= 0xffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700371 int16_t *indices = (int16_t*)(keys->dk_indices);
Victor Stinner71211e32016-09-08 10:52:46 -0700372 assert(ix <= 0x7fff);
Victor Stinner208857e2016-09-08 11:35:46 -0700373 indices[i] = (int16_t)ix;
Victor Stinner742da042016-09-07 17:40:12 -0700374 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700375#if SIZEOF_VOID_P > 4
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300376 else if (s > 0xffffffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700377 int64_t *indices = (int64_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700378 indices[i] = ix;
Victor Stinner742da042016-09-07 17:40:12 -0700379 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700380#endif
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300381 else {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700382 int32_t *indices = (int32_t*)(keys->dk_indices);
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300383 assert(ix <= 0x7fffffff);
384 indices[i] = (int32_t)ix;
385 }
Victor Stinner742da042016-09-07 17:40:12 -0700386}
387
388
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200389/* USABLE_FRACTION is the maximum dictionary load.
Victor Stinner742da042016-09-07 17:40:12 -0700390 * Increasing this ratio makes dictionaries more dense resulting in more
391 * collisions. Decreasing it improves sparseness at the expense of spreading
392 * indices over more cache lines and at the cost of total memory consumed.
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200393 *
394 * USABLE_FRACTION must obey the following:
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400395 * (0 < USABLE_FRACTION(n) < n) for all n >= 2
396 *
Victor Stinner742da042016-09-07 17:40:12 -0700397 * USABLE_FRACTION should be quick to calculate.
398 * Fractions around 1/2 to 2/3 seem to work well in practice.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400399 */
Victor Stinner742da042016-09-07 17:40:12 -0700400#define USABLE_FRACTION(n) (((n) << 1)/3)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400401
Victor Stinner742da042016-09-07 17:40:12 -0700402/* ESTIMATE_SIZE is reverse function of USABLE_FRACTION.
403 * This can be used to reserve enough size to insert n entries without
404 * resizing.
405 */
INADA Naoki92c50ee2016-11-22 00:57:02 +0900406#define ESTIMATE_SIZE(n) (((n)*3+1) >> 1)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400407
Victor Stinner742da042016-09-07 17:40:12 -0700408/* Alternative fraction that is otherwise close enough to 2n/3 to make
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400409 * little difference. 8 * 2/3 == 8 * 5/8 == 5. 16 * 2/3 == 16 * 5/8 == 10.
410 * 32 * 2/3 = 21, 32 * 5/8 = 20.
411 * Its advantage is that it is faster to compute on machines with slow division.
412 * #define USABLE_FRACTION(n) (((n) >> 1) + ((n) >> 2) - ((n) >> 3))
Victor Stinner742da042016-09-07 17:40:12 -0700413 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400414
Victor Stinnera9f61a52013-07-16 22:17:26 +0200415/* GROWTH_RATE. Growth rate upon hitting maximum load.
INADA Naoki5fbc5112018-04-17 15:53:34 +0900416 * Currently set to used*3.
Victor Stinnera9f61a52013-07-16 22:17:26 +0200417 * This means that dicts double in size when growing without deletions,
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700418 * but have more head room when the number of deletions is on a par with the
INADA Naoki5fbc5112018-04-17 15:53:34 +0900419 * number of insertions. See also bpo-17563 and bpo-33205.
420 *
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700421 * GROWTH_RATE was set to used*4 up to version 3.2.
422 * GROWTH_RATE was set to used*2 in version 3.3.0
INADA Naoki5fbc5112018-04-17 15:53:34 +0900423 * GROWTH_RATE was set to used*2 + capacity/2 in 3.4.0-3.6.0.
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200424 */
INADA Naoki5fbc5112018-04-17 15:53:34 +0900425#define GROWTH_RATE(d) ((d)->ma_used*3)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400426
427#define ENSURE_ALLOWS_DELETIONS(d) \
428 if ((d)->ma_keys->dk_lookup == lookdict_unicode_nodummy) { \
429 (d)->ma_keys->dk_lookup = lookdict_unicode; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400431
432/* This immutable, empty PyDictKeysObject is used for PyDict_Clear()
433 * (which cannot fail and thus can do no allocation).
434 */
435static PyDictKeysObject empty_keys_struct = {
Serhiy Storchaka97932e42016-09-26 23:01:23 +0300436 1, /* dk_refcnt */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400437 1, /* dk_size */
438 lookdict_split, /* dk_lookup */
439 0, /* dk_usable (immutable) */
Victor Stinner742da042016-09-07 17:40:12 -0700440 0, /* dk_nentries */
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700441 {DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY,
442 DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY}, /* dk_indices */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400443};
444
445static PyObject *empty_values[1] = { NULL };
446
447#define Py_EMPTY_KEYS &empty_keys_struct
448
Victor Stinner611b0fa2016-09-14 15:02:01 +0200449/* Uncomment to check the dict content in _PyDict_CheckConsistency() */
450/* #define DEBUG_PYDICT */
451
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200452#ifdef DEBUG_PYDICT
453# define ASSERT_CONSISTENT(op) assert(_PyDict_CheckConsistency((PyObject *)(op), 1))
454#else
455# define ASSERT_CONSISTENT(op) assert(_PyDict_CheckConsistency((PyObject *)(op), 0))
456#endif
Victor Stinner611b0fa2016-09-14 15:02:01 +0200457
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200458
459int
460_PyDict_CheckConsistency(PyObject *op, int check_content)
Victor Stinner611b0fa2016-09-14 15:02:01 +0200461{
Emmanuel Ariasa2fedd82019-05-10 07:08:08 -0300462#ifndef NDEBUG
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200463 _PyObject_ASSERT(op, PyDict_Check(op));
464 PyDictObject *mp = (PyDictObject *)op;
Victor Stinner50fe3f82018-10-26 18:47:15 +0200465
Victor Stinner611b0fa2016-09-14 15:02:01 +0200466 PyDictKeysObject *keys = mp->ma_keys;
467 int splitted = _PyDict_HasSplitTable(mp);
468 Py_ssize_t usable = USABLE_FRACTION(keys->dk_size);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200469
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200470 _PyObject_ASSERT(op, 0 <= mp->ma_used && mp->ma_used <= usable);
471 _PyObject_ASSERT(op, IS_POWER_OF_2(keys->dk_size));
472 _PyObject_ASSERT(op, 0 <= keys->dk_usable && keys->dk_usable <= usable);
473 _PyObject_ASSERT(op, 0 <= keys->dk_nentries && keys->dk_nentries <= usable);
474 _PyObject_ASSERT(op, keys->dk_usable + keys->dk_nentries <= usable);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200475
476 if (!splitted) {
477 /* combined table */
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200478 _PyObject_ASSERT(op, keys->dk_refcnt == 1);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200479 }
480
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200481 if (check_content) {
482 PyDictKeyEntry *entries = DK_ENTRIES(keys);
483 Py_ssize_t i;
Victor Stinner611b0fa2016-09-14 15:02:01 +0200484
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200485 for (i=0; i < keys->dk_size; i++) {
486 Py_ssize_t ix = dictkeys_get_index(keys, i);
487 _PyObject_ASSERT(op, DKIX_DUMMY <= ix && ix <= usable);
488 }
Victor Stinner611b0fa2016-09-14 15:02:01 +0200489
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200490 for (i=0; i < usable; i++) {
491 PyDictKeyEntry *entry = &entries[i];
492 PyObject *key = entry->me_key;
493
494 if (key != NULL) {
495 if (PyUnicode_CheckExact(key)) {
496 Py_hash_t hash = ((PyASCIIObject *)key)->hash;
497 _PyObject_ASSERT(op, hash != -1);
498 _PyObject_ASSERT(op, entry->me_hash == hash);
499 }
500 else {
501 /* test_dict fails if PyObject_Hash() is called again */
502 _PyObject_ASSERT(op, entry->me_hash != -1);
503 }
504 if (!splitted) {
505 _PyObject_ASSERT(op, entry->me_value != NULL);
506 }
Victor Stinner611b0fa2016-09-14 15:02:01 +0200507 }
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200508
509 if (splitted) {
510 _PyObject_ASSERT(op, entry->me_value == NULL);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200511 }
512 }
513
514 if (splitted) {
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200515 /* splitted table */
516 for (i=0; i < mp->ma_used; i++) {
517 _PyObject_ASSERT(op, mp->ma_values[i] != NULL);
518 }
Victor Stinner611b0fa2016-09-14 15:02:01 +0200519 }
520 }
Emmanuel Ariasa2fedd82019-05-10 07:08:08 -0300521#endif
Victor Stinner611b0fa2016-09-14 15:02:01 +0200522 return 1;
523}
Victor Stinner611b0fa2016-09-14 15:02:01 +0200524
525
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400526static PyDictKeysObject *new_keys_object(Py_ssize_t size)
527{
528 PyDictKeysObject *dk;
Victor Stinner742da042016-09-07 17:40:12 -0700529 Py_ssize_t es, usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400530
Victor Stinner742da042016-09-07 17:40:12 -0700531 assert(size >= PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400532 assert(IS_POWER_OF_2(size));
Victor Stinner742da042016-09-07 17:40:12 -0700533
534 usable = USABLE_FRACTION(size);
535 if (size <= 0xff) {
536 es = 1;
537 }
538 else if (size <= 0xffff) {
539 es = 2;
540 }
541#if SIZEOF_VOID_P > 4
542 else if (size <= 0xffffffff) {
543 es = 4;
544 }
545#endif
546 else {
547 es = sizeof(Py_ssize_t);
548 }
549
550 if (size == PyDict_MINSIZE && numfreekeys > 0) {
551 dk = keys_free_list[--numfreekeys];
552 }
553 else {
Victor Stinner98ee9d52016-09-08 09:33:56 -0700554 dk = PyObject_MALLOC(sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -0700555 + es * size
556 + sizeof(PyDictKeyEntry) * usable);
Victor Stinner742da042016-09-07 17:40:12 -0700557 if (dk == NULL) {
558 PyErr_NoMemory();
559 return NULL;
560 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400561 }
INADA Naokia7576492018-11-14 18:39:27 +0900562 _Py_INC_REFTOTAL;
563 dk->dk_refcnt = 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400564 dk->dk_size = size;
Victor Stinner742da042016-09-07 17:40:12 -0700565 dk->dk_usable = usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400566 dk->dk_lookup = lookdict_unicode_nodummy;
Victor Stinner742da042016-09-07 17:40:12 -0700567 dk->dk_nentries = 0;
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700568 memset(&dk->dk_indices[0], 0xff, es * size);
Victor Stinner742da042016-09-07 17:40:12 -0700569 memset(DK_ENTRIES(dk), 0, sizeof(PyDictKeyEntry) * usable);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400570 return dk;
571}
572
573static void
574free_keys_object(PyDictKeysObject *keys)
575{
Victor Stinner742da042016-09-07 17:40:12 -0700576 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400577 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -0700578 for (i = 0, n = keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400579 Py_XDECREF(entries[i].me_key);
580 Py_XDECREF(entries[i].me_value);
581 }
Victor Stinner742da042016-09-07 17:40:12 -0700582 if (keys->dk_size == PyDict_MINSIZE && numfreekeys < PyDict_MAXFREELIST) {
583 keys_free_list[numfreekeys++] = keys;
584 return;
585 }
Raymond Hettingerce5179f2016-01-31 08:56:21 -0800586 PyObject_FREE(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400587}
588
589#define new_values(size) PyMem_NEW(PyObject *, size)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400590#define free_values(values) PyMem_FREE(values)
591
592/* Consumes a reference to the keys object */
593static PyObject *
594new_dict(PyDictKeysObject *keys, PyObject **values)
595{
596 PyDictObject *mp;
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200597 assert(keys != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 if (numfree) {
599 mp = free_list[--numfree];
600 assert (mp != NULL);
601 assert (Py_TYPE(mp) == &PyDict_Type);
602 _Py_NewReference((PyObject *)mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400604 else {
605 mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
606 if (mp == NULL) {
INADA Naokia7576492018-11-14 18:39:27 +0900607 dictkeys_decref(keys);
Zackery Spytz3d07c1e2019-03-23 20:23:29 -0600608 if (values != empty_values) {
609 free_values(values);
610 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400611 return NULL;
612 }
613 }
614 mp->ma_keys = keys;
615 mp->ma_values = values;
616 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -0700617 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200618 ASSERT_CONSISTENT(mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000620}
621
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400622/* Consumes a reference to the keys object */
623static PyObject *
624new_dict_with_shared_keys(PyDictKeysObject *keys)
625{
626 PyObject **values;
627 Py_ssize_t i, size;
628
Victor Stinner742da042016-09-07 17:40:12 -0700629 size = USABLE_FRACTION(DK_SIZE(keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400630 values = new_values(size);
631 if (values == NULL) {
INADA Naokia7576492018-11-14 18:39:27 +0900632 dictkeys_decref(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400633 return PyErr_NoMemory();
634 }
635 for (i = 0; i < size; i++) {
636 values[i] = NULL;
637 }
638 return new_dict(keys, values);
639}
640
Yury Selivanovb0a7a032018-01-22 11:54:41 -0500641
642static PyObject *
643clone_combined_dict(PyDictObject *orig)
644{
645 assert(PyDict_CheckExact(orig));
646 assert(orig->ma_values == NULL);
647 assert(orig->ma_keys->dk_refcnt == 1);
648
649 Py_ssize_t keys_size = _PyDict_KeysSize(orig->ma_keys);
650 PyDictKeysObject *keys = PyObject_Malloc(keys_size);
651 if (keys == NULL) {
652 PyErr_NoMemory();
653 return NULL;
654 }
655
656 memcpy(keys, orig->ma_keys, keys_size);
657
658 /* After copying key/value pairs, we need to incref all
659 keys and values and they are about to be co-owned by a
660 new dict object. */
661 PyDictKeyEntry *ep0 = DK_ENTRIES(keys);
662 Py_ssize_t n = keys->dk_nentries;
663 for (Py_ssize_t i = 0; i < n; i++) {
664 PyDictKeyEntry *entry = &ep0[i];
665 PyObject *value = entry->me_value;
666 if (value != NULL) {
667 Py_INCREF(value);
668 Py_INCREF(entry->me_key);
669 }
670 }
671
672 PyDictObject *new = (PyDictObject *)new_dict(keys, NULL);
673 if (new == NULL) {
674 /* In case of an error, `new_dict()` takes care of
675 cleaning up `keys`. */
676 return NULL;
677 }
678 new->ma_used = orig->ma_used;
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200679 ASSERT_CONSISTENT(new);
Yury Selivanovb0a7a032018-01-22 11:54:41 -0500680 if (_PyObject_GC_IS_TRACKED(orig)) {
681 /* Maintain tracking. */
682 _PyObject_GC_TRACK(new);
683 }
Yury Selivanov0b752282018-07-06 12:20:07 -0400684
685 /* Since we copied the keys table we now have an extra reference
686 in the system. Manually call _Py_INC_REFTOTAL to signal that
INADA Naokia7576492018-11-14 18:39:27 +0900687 we have it now; calling dictkeys_incref would be an error as
Yury Selivanov0b752282018-07-06 12:20:07 -0400688 keys->dk_refcnt is already set to 1 (after memcpy). */
689 _Py_INC_REFTOTAL;
690
Yury Selivanovb0a7a032018-01-22 11:54:41 -0500691 return (PyObject *)new;
692}
693
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400694PyObject *
695PyDict_New(void)
696{
Inada Naokif2a18672019-03-12 17:25:44 +0900697 dictkeys_incref(Py_EMPTY_KEYS);
698 return new_dict(Py_EMPTY_KEYS, empty_values);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400699}
700
Victor Stinner742da042016-09-07 17:40:12 -0700701/* Search index of hash table from offset of entry table */
702static Py_ssize_t
703lookdict_index(PyDictKeysObject *k, Py_hash_t hash, Py_ssize_t index)
704{
Victor Stinner742da042016-09-07 17:40:12 -0700705 size_t mask = DK_MASK(k);
INADA Naoki073ae482017-06-23 15:22:50 +0900706 size_t perturb = (size_t)hash;
707 size_t i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700708
INADA Naoki073ae482017-06-23 15:22:50 +0900709 for (;;) {
INADA Naokia7576492018-11-14 18:39:27 +0900710 Py_ssize_t ix = dictkeys_get_index(k, i);
Victor Stinner742da042016-09-07 17:40:12 -0700711 if (ix == index) {
712 return i;
713 }
714 if (ix == DKIX_EMPTY) {
715 return DKIX_EMPTY;
716 }
INADA Naoki073ae482017-06-23 15:22:50 +0900717 perturb >>= PERTURB_SHIFT;
718 i = mask & (i*5 + perturb + 1);
Victor Stinner742da042016-09-07 17:40:12 -0700719 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700720 Py_UNREACHABLE();
Victor Stinner742da042016-09-07 17:40:12 -0700721}
722
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000723/*
724The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000725This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000726Open addressing is preferred over chaining since the link overhead for
727chaining would be substantial (100% with typical malloc overhead).
728
Tim Peterseb28ef22001-06-02 05:27:19 +0000729The initial probe index is computed as hash mod the table size. Subsequent
730probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000731
732All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000733
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000734The details in this version are due to Tim Peters, building on many past
Tim Peterseb28ef22001-06-02 05:27:19 +0000735contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000736Christian Tismer.
Fred Drake1bff34a2000-08-31 19:31:38 +0000737
Victor Stinner742da042016-09-07 17:40:12 -0700738lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a
Victor Stinnera4348cc2016-09-08 12:01:25 -0700739comparison raises an exception.
Guido van Rossum89d8c602007-09-18 17:26:56 +0000740lookdict_unicode() below is specialized to string keys, comparison of which can
INADA Naoki1b8df102017-02-20 22:48:10 +0900741never raise an exception; that function can never return DKIX_ERROR when key
742is string. Otherwise, it falls back to lookdict().
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400743lookdict_unicode_nodummy is further specialized for string keys that cannot be
744the <dummy> value.
INADA Naoki778928b2017-08-03 23:45:15 +0900745For both, when the key isn't found a DKIX_EMPTY is returned.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000746*/
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100747static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400748lookdict(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900749 Py_hash_t hash, PyObject **value_addr)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000750{
INADA Naoki778928b2017-08-03 23:45:15 +0900751 size_t i, mask, perturb;
Victor Stinner742da042016-09-07 17:40:12 -0700752 PyDictKeysObject *dk;
INADA Naoki778928b2017-08-03 23:45:15 +0900753 PyDictKeyEntry *ep0;
Tim Peterseb28ef22001-06-02 05:27:19 +0000754
Antoine Pitrou9a234902012-05-13 20:48:01 +0200755top:
Victor Stinner742da042016-09-07 17:40:12 -0700756 dk = mp->ma_keys;
Victor Stinner742da042016-09-07 17:40:12 -0700757 ep0 = DK_ENTRIES(dk);
INADA Naoki778928b2017-08-03 23:45:15 +0900758 mask = DK_MASK(dk);
759 perturb = hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700761
INADA Naoki778928b2017-08-03 23:45:15 +0900762 for (;;) {
INADA Naokia7576492018-11-14 18:39:27 +0900763 Py_ssize_t ix = dictkeys_get_index(dk, i);
Victor Stinner742da042016-09-07 17:40:12 -0700764 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700765 *value_addr = NULL;
766 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400767 }
INADA Naoki778928b2017-08-03 23:45:15 +0900768 if (ix >= 0) {
769 PyDictKeyEntry *ep = &ep0[ix];
770 assert(ep->me_key != NULL);
771 if (ep->me_key == key) {
772 *value_addr = ep->me_value;
773 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700774 }
INADA Naoki778928b2017-08-03 23:45:15 +0900775 if (ep->me_hash == hash) {
776 PyObject *startkey = ep->me_key;
777 Py_INCREF(startkey);
778 int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
779 Py_DECREF(startkey);
780 if (cmp < 0) {
781 *value_addr = NULL;
782 return DKIX_ERROR;
783 }
784 if (dk == mp->ma_keys && ep->me_key == startkey) {
785 if (cmp > 0) {
786 *value_addr = ep->me_value;
787 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700788 }
INADA Naoki778928b2017-08-03 23:45:15 +0900789 }
790 else {
791 /* The dict was mutated, restart */
792 goto top;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400793 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 }
INADA Naoki778928b2017-08-03 23:45:15 +0900796 perturb >>= PERTURB_SHIFT;
797 i = (i*5 + perturb + 1) & mask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700799 Py_UNREACHABLE();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000800}
801
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400802/* Specialized version for string-only keys */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100803static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400804lookdict_unicode(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900805 Py_hash_t hash, PyObject **value_addr)
Fred Drake1bff34a2000-08-31 19:31:38 +0000806{
Victor Stinner742da042016-09-07 17:40:12 -0700807 assert(mp->ma_values == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 /* Make sure this function doesn't have to handle non-unicode keys,
809 including subclasses of str; e.g., one reason to subclass
810 unicodes is to override __eq__, and for speed we don't cater to
811 that here. */
812 if (!PyUnicode_CheckExact(key)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400813 mp->ma_keys->dk_lookup = lookdict;
INADA Naoki778928b2017-08-03 23:45:15 +0900814 return lookdict(mp, key, hash, value_addr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 }
Tim Peters15d49292001-05-27 07:39:22 +0000816
INADA Naoki778928b2017-08-03 23:45:15 +0900817 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
818 size_t mask = DK_MASK(mp->ma_keys);
819 size_t perturb = (size_t)hash;
820 size_t i = (size_t)hash & mask;
821
822 for (;;) {
INADA Naokia7576492018-11-14 18:39:27 +0900823 Py_ssize_t ix = dictkeys_get_index(mp->ma_keys, i);
Victor Stinner742da042016-09-07 17:40:12 -0700824 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700825 *value_addr = NULL;
826 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400827 }
INADA Naoki778928b2017-08-03 23:45:15 +0900828 if (ix >= 0) {
829 PyDictKeyEntry *ep = &ep0[ix];
830 assert(ep->me_key != NULL);
831 assert(PyUnicode_CheckExact(ep->me_key));
832 if (ep->me_key == key ||
833 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
834 *value_addr = ep->me_value;
835 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700836 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400837 }
INADA Naoki778928b2017-08-03 23:45:15 +0900838 perturb >>= PERTURB_SHIFT;
839 i = mask & (i*5 + perturb + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700841 Py_UNREACHABLE();
Fred Drake1bff34a2000-08-31 19:31:38 +0000842}
843
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400844/* Faster version of lookdict_unicode when it is known that no <dummy> keys
845 * will be present. */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100846static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400847lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900848 Py_hash_t hash, PyObject **value_addr)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400849{
Victor Stinner742da042016-09-07 17:40:12 -0700850 assert(mp->ma_values == NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400851 /* Make sure this function doesn't have to handle non-unicode keys,
852 including subclasses of str; e.g., one reason to subclass
853 unicodes is to override __eq__, and for speed we don't cater to
854 that here. */
855 if (!PyUnicode_CheckExact(key)) {
856 mp->ma_keys->dk_lookup = lookdict;
INADA Naoki778928b2017-08-03 23:45:15 +0900857 return lookdict(mp, key, hash, value_addr);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400858 }
INADA Naoki778928b2017-08-03 23:45:15 +0900859
860 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
861 size_t mask = DK_MASK(mp->ma_keys);
862 size_t perturb = (size_t)hash;
863 size_t i = (size_t)hash & mask;
864
865 for (;;) {
INADA Naokia7576492018-11-14 18:39:27 +0900866 Py_ssize_t ix = dictkeys_get_index(mp->ma_keys, i);
Victor Stinner742da042016-09-07 17:40:12 -0700867 assert (ix != DKIX_DUMMY);
868 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700869 *value_addr = NULL;
870 return DKIX_EMPTY;
871 }
INADA Naoki778928b2017-08-03 23:45:15 +0900872 PyDictKeyEntry *ep = &ep0[ix];
873 assert(ep->me_key != NULL);
874 assert(PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700875 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400876 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
INADA Naokiba609772016-12-07 20:41:42 +0900877 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700878 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400879 }
INADA Naoki778928b2017-08-03 23:45:15 +0900880 perturb >>= PERTURB_SHIFT;
881 i = mask & (i*5 + perturb + 1);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400882 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700883 Py_UNREACHABLE();
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400884}
885
886/* Version of lookdict for split tables.
887 * All split tables and only split tables use this lookup function.
888 * Split tables only contain unicode keys and no dummy keys,
889 * so algorithm is the same as lookdict_unicode_nodummy.
890 */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100891static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400892lookdict_split(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900893 Py_hash_t hash, PyObject **value_addr)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400894{
Victor Stinner742da042016-09-07 17:40:12 -0700895 /* mp must split table */
896 assert(mp->ma_values != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400897 if (!PyUnicode_CheckExact(key)) {
INADA Naoki778928b2017-08-03 23:45:15 +0900898 Py_ssize_t ix = lookdict(mp, key, hash, value_addr);
Victor Stinner742da042016-09-07 17:40:12 -0700899 if (ix >= 0) {
INADA Naokiba609772016-12-07 20:41:42 +0900900 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700901 }
902 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400903 }
Victor Stinner742da042016-09-07 17:40:12 -0700904
INADA Naoki778928b2017-08-03 23:45:15 +0900905 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
906 size_t mask = DK_MASK(mp->ma_keys);
907 size_t perturb = (size_t)hash;
908 size_t i = (size_t)hash & mask;
909
910 for (;;) {
INADA Naokia7576492018-11-14 18:39:27 +0900911 Py_ssize_t ix = dictkeys_get_index(mp->ma_keys, i);
INADA Naoki778928b2017-08-03 23:45:15 +0900912 assert (ix != DKIX_DUMMY);
Victor Stinner742da042016-09-07 17:40:12 -0700913 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700914 *value_addr = NULL;
915 return DKIX_EMPTY;
916 }
INADA Naoki778928b2017-08-03 23:45:15 +0900917 PyDictKeyEntry *ep = &ep0[ix];
918 assert(ep->me_key != NULL);
919 assert(PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700920 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400921 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
INADA Naokiba609772016-12-07 20:41:42 +0900922 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700923 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400924 }
INADA Naoki778928b2017-08-03 23:45:15 +0900925 perturb >>= PERTURB_SHIFT;
926 i = mask & (i*5 + perturb + 1);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400927 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700928 Py_UNREACHABLE();
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400929}
930
Benjamin Petersonfb886362010-04-24 18:21:17 +0000931int
932_PyDict_HasOnlyStringKeys(PyObject *dict)
933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 Py_ssize_t pos = 0;
935 PyObject *key, *value;
Benjamin Petersonf6096542010-11-17 22:33:12 +0000936 assert(PyDict_Check(dict));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 /* Shortcut */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400938 if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 return 1;
940 while (PyDict_Next(dict, &pos, &key, &value))
941 if (!PyUnicode_Check(key))
942 return 0;
943 return 1;
Benjamin Petersonfb886362010-04-24 18:21:17 +0000944}
945
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000946#define MAINTAIN_TRACKING(mp, key, value) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 do { \
948 if (!_PyObject_GC_IS_TRACKED(mp)) { \
949 if (_PyObject_GC_MAY_BE_TRACKED(key) || \
950 _PyObject_GC_MAY_BE_TRACKED(value)) { \
951 _PyObject_GC_TRACK(mp); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 } \
953 } \
954 } while(0)
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000955
956void
957_PyDict_MaybeUntrack(PyObject *op)
958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 PyDictObject *mp;
960 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -0700961 Py_ssize_t i, numentries;
962 PyDictKeyEntry *ep0;
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
965 return;
966
967 mp = (PyDictObject *) op;
Victor Stinner742da042016-09-07 17:40:12 -0700968 ep0 = DK_ENTRIES(mp->ma_keys);
969 numentries = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400970 if (_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -0700971 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400972 if ((value = mp->ma_values[i]) == NULL)
973 continue;
974 if (_PyObject_GC_MAY_BE_TRACKED(value)) {
Victor Stinner742da042016-09-07 17:40:12 -0700975 assert(!_PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400976 return;
977 }
978 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400980 else {
Victor Stinner742da042016-09-07 17:40:12 -0700981 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400982 if ((value = ep0[i].me_value) == NULL)
983 continue;
984 if (_PyObject_GC_MAY_BE_TRACKED(value) ||
985 _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
986 return;
987 }
988 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 _PyObject_GC_UNTRACK(op);
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000990}
991
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400992/* Internal function to find slot for an item from its hash
Victor Stinner3c336c52016-09-12 14:17:40 +0200993 when it is known that the key is not present in the dict.
994
995 The dict must be combined. */
INADA Naokiba609772016-12-07 20:41:42 +0900996static Py_ssize_t
INADA Naoki778928b2017-08-03 23:45:15 +0900997find_empty_slot(PyDictKeysObject *keys, Py_hash_t hash)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000998{
INADA Naoki778928b2017-08-03 23:45:15 +0900999 assert(keys != NULL);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001000
INADA Naoki778928b2017-08-03 23:45:15 +09001001 const size_t mask = DK_MASK(keys);
1002 size_t i = hash & mask;
INADA Naokia7576492018-11-14 18:39:27 +09001003 Py_ssize_t ix = dictkeys_get_index(keys, i);
INADA Naoki778928b2017-08-03 23:45:15 +09001004 for (size_t perturb = hash; ix >= 0;) {
INADA Naoki267941c2016-10-06 15:19:07 +09001005 perturb >>= PERTURB_SHIFT;
INADA Naoki778928b2017-08-03 23:45:15 +09001006 i = (i*5 + perturb + 1) & mask;
INADA Naokia7576492018-11-14 18:39:27 +09001007 ix = dictkeys_get_index(keys, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 }
INADA Naoki778928b2017-08-03 23:45:15 +09001009 return i;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001010}
1011
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001012static int
1013insertion_resize(PyDictObject *mp)
1014{
Raymond Hettinger36f74aa2013-05-17 03:01:13 -07001015 return dictresize(mp, GROWTH_RATE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001016}
Antoine Pitroue965d972012-02-27 00:45:12 +01001017
1018/*
1019Internal routine to insert a new item into the table.
1020Used both by the internal resize routine and by the public insert routine.
Antoine Pitroue965d972012-02-27 00:45:12 +01001021Returns -1 if an error occurred, or 0 on success.
1022*/
1023static int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001024insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001025{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001026 PyObject *old_value;
INADA Naokiba609772016-12-07 20:41:42 +09001027 PyDictKeyEntry *ep;
Antoine Pitroue965d972012-02-27 00:45:12 +01001028
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001029 Py_INCREF(key);
1030 Py_INCREF(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001031 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
1032 if (insertion_resize(mp) < 0)
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001033 goto Fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001034 }
1035
INADA Naoki778928b2017-08-03 23:45:15 +09001036 Py_ssize_t ix = mp->ma_keys->dk_lookup(mp, key, hash, &old_value);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001037 if (ix == DKIX_ERROR)
1038 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001039
Antoine Pitroud6967322014-10-18 00:35:00 +02001040 assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001041 MAINTAIN_TRACKING(mp, key, value);
Victor Stinner742da042016-09-07 17:40:12 -07001042
1043 /* When insertion order is different from shared key, we can't share
1044 * the key anymore. Convert this instance to combine table.
1045 */
1046 if (_PyDict_HasSplitTable(mp) &&
INADA Naokiba609772016-12-07 20:41:42 +09001047 ((ix >= 0 && old_value == NULL && mp->ma_used != ix) ||
Victor Stinner742da042016-09-07 17:40:12 -07001048 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001049 if (insertion_resize(mp) < 0)
1050 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001051 ix = DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001052 }
Victor Stinner742da042016-09-07 17:40:12 -07001053
1054 if (ix == DKIX_EMPTY) {
1055 /* Insert into new slot. */
INADA Naokiba609772016-12-07 20:41:42 +09001056 assert(old_value == NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001057 if (mp->ma_keys->dk_usable <= 0) {
1058 /* Need to resize. */
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001059 if (insertion_resize(mp) < 0)
1060 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001061 }
INADA Naoki778928b2017-08-03 23:45:15 +09001062 Py_ssize_t hashpos = find_empty_slot(mp->ma_keys, hash);
INADA Naokiba609772016-12-07 20:41:42 +09001063 ep = &DK_ENTRIES(mp->ma_keys)[mp->ma_keys->dk_nentries];
INADA Naokia7576492018-11-14 18:39:27 +09001064 dictkeys_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
Victor Stinner742da042016-09-07 17:40:12 -07001065 ep->me_key = key;
1066 ep->me_hash = hash;
1067 if (mp->ma_values) {
1068 assert (mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
1069 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001070 }
1071 else {
Victor Stinner742da042016-09-07 17:40:12 -07001072 ep->me_value = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001073 }
1074 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001075 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07001076 mp->ma_keys->dk_usable--;
1077 mp->ma_keys->dk_nentries++;
1078 assert(mp->ma_keys->dk_usable >= 0);
Victor Stinner0fc91ee2019-04-12 21:51:34 +02001079 ASSERT_CONSISTENT(mp);
Victor Stinner742da042016-09-07 17:40:12 -07001080 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001081 }
Victor Stinner742da042016-09-07 17:40:12 -07001082
Inada Naoki91234a12019-06-03 21:30:58 +09001083 if (old_value != value) {
1084 if (_PyDict_HasSplitTable(mp)) {
1085 mp->ma_values[ix] = value;
1086 if (old_value == NULL) {
1087 /* pending state */
1088 assert(ix == mp->ma_used);
1089 mp->ma_used++;
1090 }
INADA Naokiba609772016-12-07 20:41:42 +09001091 }
Inada Naoki91234a12019-06-03 21:30:58 +09001092 else {
1093 assert(old_value != NULL);
1094 DK_ENTRIES(mp->ma_keys)[ix].me_value = value;
1095 }
1096 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naokiba609772016-12-07 20:41:42 +09001097 }
INADA Naokiba609772016-12-07 20:41:42 +09001098 Py_XDECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
Victor Stinner0fc91ee2019-04-12 21:51:34 +02001099 ASSERT_CONSISTENT(mp);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001100 Py_DECREF(key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001101 return 0;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001102
1103Fail:
1104 Py_DECREF(value);
1105 Py_DECREF(key);
1106 return -1;
Antoine Pitroue965d972012-02-27 00:45:12 +01001107}
1108
Inada Naoki2ddc7f62019-03-18 20:38:33 +09001109// Same to insertdict but specialized for ma_keys = Py_EMPTY_KEYS.
1110static int
1111insert_to_emptydict(PyDictObject *mp, PyObject *key, Py_hash_t hash,
1112 PyObject *value)
1113{
1114 assert(mp->ma_keys == Py_EMPTY_KEYS);
1115
1116 PyDictKeysObject *newkeys = new_keys_object(PyDict_MINSIZE);
1117 if (newkeys == NULL) {
1118 return -1;
1119 }
1120 if (!PyUnicode_CheckExact(key)) {
1121 newkeys->dk_lookup = lookdict;
1122 }
1123 dictkeys_decref(Py_EMPTY_KEYS);
1124 mp->ma_keys = newkeys;
1125 mp->ma_values = NULL;
1126
1127 Py_INCREF(key);
1128 Py_INCREF(value);
1129 MAINTAIN_TRACKING(mp, key, value);
1130
1131 size_t hashpos = (size_t)hash & (PyDict_MINSIZE-1);
1132 PyDictKeyEntry *ep = &DK_ENTRIES(mp->ma_keys)[0];
1133 dictkeys_set_index(mp->ma_keys, hashpos, 0);
1134 ep->me_key = key;
1135 ep->me_hash = hash;
1136 ep->me_value = value;
1137 mp->ma_used++;
1138 mp->ma_version_tag = DICT_NEXT_VERSION();
1139 mp->ma_keys->dk_usable--;
1140 mp->ma_keys->dk_nentries++;
1141 return 0;
1142}
1143
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001144/*
luzpaza5293b42017-11-05 07:37:50 -06001145Internal routine used by dictresize() to build a hashtable of entries.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001146*/
1147static void
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001148build_indices(PyDictKeysObject *keys, PyDictKeyEntry *ep, Py_ssize_t n)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001149{
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001150 size_t mask = (size_t)DK_SIZE(keys) - 1;
1151 for (Py_ssize_t ix = 0; ix != n; ix++, ep++) {
1152 Py_hash_t hash = ep->me_hash;
1153 size_t i = hash & mask;
INADA Naokia7576492018-11-14 18:39:27 +09001154 for (size_t perturb = hash; dictkeys_get_index(keys, i) != DKIX_EMPTY;) {
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001155 perturb >>= PERTURB_SHIFT;
INADA Naoki870c2862017-06-24 09:03:19 +09001156 i = mask & (i*5 + perturb + 1);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001157 }
INADA Naokia7576492018-11-14 18:39:27 +09001158 dictkeys_set_index(keys, i, ix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001160}
1161
1162/*
1163Restructure the table by allocating a new table and reinserting all
1164items again. When entries have been deleted, the new table may
1165actually be smaller than the old one.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001166If a table is split (its keys and hashes are shared, its values are not),
1167then the values are temporarily copied into the table, it is resized as
1168a combined table, then the me_value slots in the old table are NULLed out.
1169After resizing a table is always combined,
1170but can be resplit by make_keys_shared().
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001171*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001172static int
Victor Stinner3d3f2642016-12-15 17:21:23 +01001173dictresize(PyDictObject *mp, Py_ssize_t minsize)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001174{
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001175 Py_ssize_t newsize, numentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001176 PyDictKeysObject *oldkeys;
1177 PyObject **oldvalues;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001178 PyDictKeyEntry *oldentries, *newentries;
Tim Peters91a364d2001-05-19 07:04:38 +00001179
Victor Stinner742da042016-09-07 17:40:12 -07001180 /* Find the smallest table size > minused. */
1181 for (newsize = PyDict_MINSIZE;
Victor Stinner3d3f2642016-12-15 17:21:23 +01001182 newsize < minsize && newsize > 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 newsize <<= 1)
1184 ;
1185 if (newsize <= 0) {
1186 PyErr_NoMemory();
1187 return -1;
1188 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001189
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001190 oldkeys = mp->ma_keys;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001191
1192 /* NOTE: Current odict checks mp->ma_keys to detect resize happen.
1193 * So we can't reuse oldkeys even if oldkeys->dk_size == newsize.
1194 * TODO: Try reusing oldkeys when reimplement odict.
1195 */
1196
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001197 /* Allocate a new table. */
1198 mp->ma_keys = new_keys_object(newsize);
1199 if (mp->ma_keys == NULL) {
1200 mp->ma_keys = oldkeys;
1201 return -1;
1202 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01001203 // New table must be large enough.
1204 assert(mp->ma_keys->dk_usable >= mp->ma_used);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001205 if (oldkeys->dk_lookup == lookdict)
1206 mp->ma_keys->dk_lookup = lookdict;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001207
1208 numentries = mp->ma_used;
1209 oldentries = DK_ENTRIES(oldkeys);
1210 newentries = DK_ENTRIES(mp->ma_keys);
1211 oldvalues = mp->ma_values;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001212 if (oldvalues != NULL) {
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001213 /* Convert split table into new combined table.
1214 * We must incref keys; we can transfer values.
1215 * Note that values of split table is always dense.
1216 */
1217 for (Py_ssize_t i = 0; i < numentries; i++) {
1218 assert(oldvalues[i] != NULL);
1219 PyDictKeyEntry *ep = &oldentries[i];
1220 PyObject *key = ep->me_key;
1221 Py_INCREF(key);
1222 newentries[i].me_key = key;
1223 newentries[i].me_hash = ep->me_hash;
1224 newentries[i].me_value = oldvalues[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001226
INADA Naokia7576492018-11-14 18:39:27 +09001227 dictkeys_decref(oldkeys);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001228 mp->ma_values = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001229 if (oldvalues != empty_values) {
1230 free_values(oldvalues);
1231 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001232 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001233 else { // combined table.
1234 if (oldkeys->dk_nentries == numentries) {
1235 memcpy(newentries, oldentries, numentries * sizeof(PyDictKeyEntry));
1236 }
1237 else {
1238 PyDictKeyEntry *ep = oldentries;
1239 for (Py_ssize_t i = 0; i < numentries; i++) {
1240 while (ep->me_value == NULL)
1241 ep++;
1242 newentries[i] = *ep++;
1243 }
1244 }
1245
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001246 assert(oldkeys->dk_lookup != lookdict_split);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001247 assert(oldkeys->dk_refcnt == 1);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001248 if (oldkeys->dk_size == PyDict_MINSIZE &&
1249 numfreekeys < PyDict_MAXFREELIST) {
INADA Naokia7576492018-11-14 18:39:27 +09001250 _Py_DEC_REFTOTAL;
1251 keys_free_list[numfreekeys++] = oldkeys;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001252 }
1253 else {
INADA Naokia7576492018-11-14 18:39:27 +09001254 _Py_DEC_REFTOTAL;
1255 PyObject_FREE(oldkeys);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001256 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001257 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001258
1259 build_indices(mp->ma_keys, newentries, numentries);
1260 mp->ma_keys->dk_usable -= numentries;
1261 mp->ma_keys->dk_nentries = numentries;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001263}
1264
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001265/* Returns NULL if unable to split table.
1266 * A NULL return does not necessarily indicate an error */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001267static PyDictKeysObject *
1268make_keys_shared(PyObject *op)
1269{
1270 Py_ssize_t i;
1271 Py_ssize_t size;
1272 PyDictObject *mp = (PyDictObject *)op;
1273
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001274 if (!PyDict_CheckExact(op))
1275 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001276 if (!_PyDict_HasSplitTable(mp)) {
1277 PyDictKeyEntry *ep0;
1278 PyObject **values;
1279 assert(mp->ma_keys->dk_refcnt == 1);
1280 if (mp->ma_keys->dk_lookup == lookdict) {
1281 return NULL;
1282 }
1283 else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
1284 /* Remove dummy keys */
1285 if (dictresize(mp, DK_SIZE(mp->ma_keys)))
1286 return NULL;
1287 }
1288 assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
1289 /* Copy values into a new array */
Victor Stinner742da042016-09-07 17:40:12 -07001290 ep0 = DK_ENTRIES(mp->ma_keys);
1291 size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001292 values = new_values(size);
1293 if (values == NULL) {
1294 PyErr_SetString(PyExc_MemoryError,
1295 "Not enough memory to allocate new values array");
1296 return NULL;
1297 }
1298 for (i = 0; i < size; i++) {
1299 values[i] = ep0[i].me_value;
1300 ep0[i].me_value = NULL;
1301 }
1302 mp->ma_keys->dk_lookup = lookdict_split;
1303 mp->ma_values = values;
1304 }
INADA Naokia7576492018-11-14 18:39:27 +09001305 dictkeys_incref(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001306 return mp->ma_keys;
1307}
Christian Heimes99170a52007-12-19 02:07:34 +00001308
1309PyObject *
1310_PyDict_NewPresized(Py_ssize_t minused)
1311{
INADA Naoki92c50ee2016-11-22 00:57:02 +09001312 const Py_ssize_t max_presize = 128 * 1024;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001313 Py_ssize_t newsize;
1314 PyDictKeysObject *new_keys;
INADA Naoki92c50ee2016-11-22 00:57:02 +09001315
Inada Naoki2ddc7f62019-03-18 20:38:33 +09001316 if (minused <= USABLE_FRACTION(PyDict_MINSIZE)) {
Inada Naokif2a18672019-03-12 17:25:44 +09001317 return PyDict_New();
1318 }
INADA Naoki92c50ee2016-11-22 00:57:02 +09001319 /* There are no strict guarantee that returned dict can contain minused
1320 * items without resize. So we create medium size dict instead of very
1321 * large dict or MemoryError.
1322 */
1323 if (minused > USABLE_FRACTION(max_presize)) {
1324 newsize = max_presize;
1325 }
1326 else {
1327 Py_ssize_t minsize = ESTIMATE_SIZE(minused);
Inada Naoki2ddc7f62019-03-18 20:38:33 +09001328 newsize = PyDict_MINSIZE*2;
INADA Naoki92c50ee2016-11-22 00:57:02 +09001329 while (newsize < minsize) {
1330 newsize <<= 1;
1331 }
1332 }
1333 assert(IS_POWER_OF_2(newsize));
1334
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001335 new_keys = new_keys_object(newsize);
1336 if (new_keys == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001338 return new_dict(new_keys, NULL);
Christian Heimes99170a52007-12-19 02:07:34 +00001339}
1340
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001341/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
1342 * that may occur (originally dicts supported only string keys, and exceptions
1343 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001344 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001345 * (suppressed) occurred while computing the key's hash, or that some error
1346 * (suppressed) occurred when comparing keys in the dict's internal probe
1347 * sequence. A nasty example of the latter is when a Python-coded comparison
1348 * function hits a stack-depth error, which can cause this to return NULL
1349 * even if the key is present.
1350 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001351PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001352PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001353{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001354 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001355 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 PyDictObject *mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 PyThreadState *tstate;
INADA Naokiba609772016-12-07 20:41:42 +09001358 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 if (!PyDict_Check(op))
1361 return NULL;
1362 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001363 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 {
1365 hash = PyObject_Hash(key);
1366 if (hash == -1) {
1367 PyErr_Clear();
1368 return NULL;
1369 }
1370 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 /* We can arrive here with a NULL tstate during initialization: try
1373 running "python -Wi" for an example related to string interning.
1374 Let's just hope that no exception occurs then... This must be
Victor Stinner50b48572018-11-01 01:51:40 +01001375 _PyThreadState_GET() and not PyThreadState_Get() because the latter
Victor Stinner9204fb82018-10-30 15:13:17 +01001376 abort Python if tstate is NULL. */
Victor Stinner50b48572018-11-01 01:51:40 +01001377 tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 if (tstate != NULL && tstate->curexc_type != NULL) {
1379 /* preserve the existing exception */
1380 PyObject *err_type, *err_value, *err_tb;
1381 PyErr_Fetch(&err_type, &err_value, &err_tb);
INADA Naoki778928b2017-08-03 23:45:15 +09001382 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 /* ignore errors */
1384 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001385 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 return NULL;
1387 }
1388 else {
INADA Naoki778928b2017-08-03 23:45:15 +09001389 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001390 if (ix < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 PyErr_Clear();
1392 return NULL;
1393 }
1394 }
INADA Naokiba609772016-12-07 20:41:42 +09001395 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001396}
1397
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001398/* Same as PyDict_GetItemWithError() but with hash supplied by caller.
1399 This returns NULL *with* an exception set if an exception occurred.
1400 It returns NULL *without* an exception set if the key wasn't present.
1401*/
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001402PyObject *
1403_PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1404{
Victor Stinner742da042016-09-07 17:40:12 -07001405 Py_ssize_t ix;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001406 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001407 PyObject *value;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001408
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001409 if (!PyDict_Check(op)) {
1410 PyErr_BadInternalCall();
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001411 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001412 }
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001413
INADA Naoki778928b2017-08-03 23:45:15 +09001414 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001415 if (ix < 0) {
1416 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001417 }
INADA Naokiba609772016-12-07 20:41:42 +09001418 return value;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001419}
1420
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001421/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
1422 This returns NULL *with* an exception set if an exception occurred.
1423 It returns NULL *without* an exception set if the key wasn't present.
1424*/
1425PyObject *
1426PyDict_GetItemWithError(PyObject *op, PyObject *key)
1427{
Victor Stinner742da042016-09-07 17:40:12 -07001428 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001429 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 PyDictObject*mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001431 PyObject *value;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 if (!PyDict_Check(op)) {
1434 PyErr_BadInternalCall();
1435 return NULL;
1436 }
1437 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001438 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 {
1440 hash = PyObject_Hash(key);
1441 if (hash == -1) {
1442 return NULL;
1443 }
1444 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001445
INADA Naoki778928b2017-08-03 23:45:15 +09001446 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001447 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001449 return value;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001450}
1451
Brett Cannonfd074152012-04-14 14:10:13 -04001452PyObject *
1453_PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
1454{
1455 PyObject *kv;
1456 kv = _PyUnicode_FromId(key); /* borrowed */
1457 if (kv == NULL)
1458 return NULL;
1459 return PyDict_GetItemWithError(dp, kv);
1460}
1461
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001462PyObject *
1463_PyDict_GetItemStringWithError(PyObject *v, const char *key)
1464{
1465 PyObject *kv, *rv;
1466 kv = PyUnicode_FromString(key);
1467 if (kv == NULL) {
1468 return NULL;
1469 }
1470 rv = PyDict_GetItemWithError(v, kv);
1471 Py_DECREF(kv);
1472 return rv;
1473}
1474
Victor Stinnerb4efc962015-11-20 09:24:02 +01001475/* Fast version of global value lookup (LOAD_GLOBAL).
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001476 * Lookup in globals, then builtins.
Victor Stinnerb4efc962015-11-20 09:24:02 +01001477 *
1478 * Raise an exception and return NULL if an error occurred (ex: computing the
1479 * key hash failed, key comparison failed, ...). Return NULL if the key doesn't
1480 * exist. Return the value if the key exists.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001481 */
1482PyObject *
1483_PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001484{
Victor Stinner742da042016-09-07 17:40:12 -07001485 Py_ssize_t ix;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001486 Py_hash_t hash;
INADA Naokiba609772016-12-07 20:41:42 +09001487 PyObject *value;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001488
1489 if (!PyUnicode_CheckExact(key) ||
1490 (hash = ((PyASCIIObject *) key)->hash) == -1)
1491 {
1492 hash = PyObject_Hash(key);
1493 if (hash == -1)
1494 return NULL;
Antoine Pitroue965d972012-02-27 00:45:12 +01001495 }
Victor Stinnerb4efc962015-11-20 09:24:02 +01001496
1497 /* namespace 1: globals */
INADA Naoki778928b2017-08-03 23:45:15 +09001498 ix = globals->ma_keys->dk_lookup(globals, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001499 if (ix == DKIX_ERROR)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001500 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001501 if (ix != DKIX_EMPTY && value != NULL)
1502 return value;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001503
1504 /* namespace 2: builtins */
INADA Naoki778928b2017-08-03 23:45:15 +09001505 ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001506 if (ix < 0)
Victor Stinnerb4efc962015-11-20 09:24:02 +01001507 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001508 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001509}
1510
Antoine Pitroue965d972012-02-27 00:45:12 +01001511/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
1512 * dictionary if it's merely replacing the value for an existing key.
1513 * This means that it's safe to loop over a dictionary with PyDict_Next()
1514 * and occasionally replace a value -- but you can't insert new keys or
1515 * remove them.
1516 */
1517int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001518PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001519{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001520 PyDictObject *mp;
1521 Py_hash_t hash;
Antoine Pitroue965d972012-02-27 00:45:12 +01001522 if (!PyDict_Check(op)) {
1523 PyErr_BadInternalCall();
1524 return -1;
1525 }
1526 assert(key);
1527 assert(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001528 mp = (PyDictObject *)op;
1529 if (!PyUnicode_CheckExact(key) ||
1530 (hash = ((PyASCIIObject *) key)->hash) == -1)
1531 {
Antoine Pitroue965d972012-02-27 00:45:12 +01001532 hash = PyObject_Hash(key);
1533 if (hash == -1)
1534 return -1;
1535 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001536
Inada Naoki2ddc7f62019-03-18 20:38:33 +09001537 if (mp->ma_keys == Py_EMPTY_KEYS) {
1538 return insert_to_emptydict(mp, key, hash, value);
1539 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001540 /* insertdict() handles any resizing that might be necessary */
1541 return insertdict(mp, key, hash, value);
Antoine Pitroue965d972012-02-27 00:45:12 +01001542}
1543
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001544int
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001545_PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
1546 Py_hash_t hash)
1547{
1548 PyDictObject *mp;
1549
1550 if (!PyDict_Check(op)) {
1551 PyErr_BadInternalCall();
1552 return -1;
1553 }
1554 assert(key);
1555 assert(value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001556 assert(hash != -1);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001557 mp = (PyDictObject *)op;
1558
Inada Naoki2ddc7f62019-03-18 20:38:33 +09001559 if (mp->ma_keys == Py_EMPTY_KEYS) {
1560 return insert_to_emptydict(mp, key, hash, value);
1561 }
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001562 /* insertdict() handles any resizing that might be necessary */
1563 return insertdict(mp, key, hash, value);
1564}
1565
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001566static int
INADA Naoki778928b2017-08-03 23:45:15 +09001567delitem_common(PyDictObject *mp, Py_hash_t hash, Py_ssize_t ix,
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001568 PyObject *old_value)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001569{
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001570 PyObject *old_key;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001571 PyDictKeyEntry *ep;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001572
INADA Naoki778928b2017-08-03 23:45:15 +09001573 Py_ssize_t hashpos = lookdict_index(mp->ma_keys, hash, ix);
1574 assert(hashpos >= 0);
1575
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001576 mp->ma_used--;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001577 mp->ma_version_tag = DICT_NEXT_VERSION();
1578 ep = &DK_ENTRIES(mp->ma_keys)[ix];
INADA Naokia7576492018-11-14 18:39:27 +09001579 dictkeys_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001580 ENSURE_ALLOWS_DELETIONS(mp);
1581 old_key = ep->me_key;
1582 ep->me_key = NULL;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001583 ep->me_value = NULL;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001584 Py_DECREF(old_key);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001585 Py_DECREF(old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001586
Victor Stinner0fc91ee2019-04-12 21:51:34 +02001587 ASSERT_CONSISTENT(mp);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001588 return 0;
1589}
1590
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001591int
Tim Peters1f5871e2000-07-04 17:44:48 +00001592PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001593{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001594 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 assert(key);
1596 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001597 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 hash = PyObject_Hash(key);
1599 if (hash == -1)
1600 return -1;
1601 }
Victor Stinner742da042016-09-07 17:40:12 -07001602
1603 return _PyDict_DelItem_KnownHash(op, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001604}
1605
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001606int
1607_PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1608{
INADA Naoki778928b2017-08-03 23:45:15 +09001609 Py_ssize_t ix;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001610 PyDictObject *mp;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001611 PyObject *old_value;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001612
1613 if (!PyDict_Check(op)) {
1614 PyErr_BadInternalCall();
1615 return -1;
1616 }
1617 assert(key);
1618 assert(hash != -1);
1619 mp = (PyDictObject *)op;
INADA Naoki778928b2017-08-03 23:45:15 +09001620 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner742da042016-09-07 17:40:12 -07001621 if (ix == DKIX_ERROR)
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001622 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09001623 if (ix == DKIX_EMPTY || old_value == NULL) {
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001624 _PyErr_SetKeyError(key);
1625 return -1;
1626 }
Victor Stinner78601a32016-09-09 19:28:36 -07001627
1628 // Split table doesn't allow deletion. Combine it.
1629 if (_PyDict_HasSplitTable(mp)) {
1630 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1631 return -1;
1632 }
INADA Naoki778928b2017-08-03 23:45:15 +09001633 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner78601a32016-09-09 19:28:36 -07001634 assert(ix >= 0);
1635 }
1636
INADA Naoki778928b2017-08-03 23:45:15 +09001637 return delitem_common(mp, hash, ix, old_value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001638}
1639
Antoine Pitroud741ed42016-12-27 14:23:43 +01001640/* This function promises that the predicate -> deletion sequence is atomic
1641 * (i.e. protected by the GIL), assuming the predicate itself doesn't
1642 * release the GIL.
1643 */
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001644int
1645_PyDict_DelItemIf(PyObject *op, PyObject *key,
1646 int (*predicate)(PyObject *value))
1647{
Antoine Pitroud741ed42016-12-27 14:23:43 +01001648 Py_ssize_t hashpos, ix;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001649 PyDictObject *mp;
1650 Py_hash_t hash;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001651 PyObject *old_value;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001652 int res;
1653
1654 if (!PyDict_Check(op)) {
1655 PyErr_BadInternalCall();
1656 return -1;
1657 }
1658 assert(key);
1659 hash = PyObject_Hash(key);
1660 if (hash == -1)
1661 return -1;
1662 mp = (PyDictObject *)op;
INADA Naoki778928b2017-08-03 23:45:15 +09001663 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001664 if (ix == DKIX_ERROR)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001665 return -1;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001666 if (ix == DKIX_EMPTY || old_value == NULL) {
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001667 _PyErr_SetKeyError(key);
1668 return -1;
1669 }
Antoine Pitroud741ed42016-12-27 14:23:43 +01001670
1671 // Split table doesn't allow deletion. Combine it.
1672 if (_PyDict_HasSplitTable(mp)) {
1673 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1674 return -1;
1675 }
INADA Naoki778928b2017-08-03 23:45:15 +09001676 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001677 assert(ix >= 0);
1678 }
1679
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001680 res = predicate(old_value);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001681 if (res == -1)
1682 return -1;
INADA Naoki778928b2017-08-03 23:45:15 +09001683
1684 hashpos = lookdict_index(mp->ma_keys, hash, ix);
1685 assert(hashpos >= 0);
1686
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001687 if (res > 0)
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001688 return delitem_common(mp, hashpos, ix, old_value);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001689 else
1690 return 0;
1691}
1692
1693
Guido van Rossum25831651993-05-19 14:50:45 +00001694void
Tim Peters1f5871e2000-07-04 17:44:48 +00001695PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 PyDictObject *mp;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001698 PyDictKeysObject *oldkeys;
1699 PyObject **oldvalues;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 if (!PyDict_Check(op))
1703 return;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001704 mp = ((PyDictObject *)op);
1705 oldkeys = mp->ma_keys;
1706 oldvalues = mp->ma_values;
1707 if (oldvalues == empty_values)
1708 return;
1709 /* Empty the dict... */
INADA Naokia7576492018-11-14 18:39:27 +09001710 dictkeys_incref(Py_EMPTY_KEYS);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001711 mp->ma_keys = Py_EMPTY_KEYS;
1712 mp->ma_values = empty_values;
1713 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001714 mp->ma_version_tag = DICT_NEXT_VERSION();
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001715 /* ...then clear the keys and values */
1716 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001717 n = oldkeys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001718 for (i = 0; i < n; i++)
1719 Py_CLEAR(oldvalues[i]);
1720 free_values(oldvalues);
INADA Naokia7576492018-11-14 18:39:27 +09001721 dictkeys_decref(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001722 }
1723 else {
1724 assert(oldkeys->dk_refcnt == 1);
INADA Naokia7576492018-11-14 18:39:27 +09001725 dictkeys_decref(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001726 }
Victor Stinner0fc91ee2019-04-12 21:51:34 +02001727 ASSERT_CONSISTENT(mp);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001728}
1729
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001730/* Internal version of PyDict_Next that returns a hash value in addition
1731 * to the key and value.
1732 * Return 1 on success, return 0 when the reached the end of the dictionary
1733 * (or if op is not a dictionary)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001734 */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001735int
1736_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
1737 PyObject **pvalue, Py_hash_t *phash)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001738{
INADA Naokica2d8be2016-11-04 16:59:10 +09001739 Py_ssize_t i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001740 PyDictObject *mp;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001741 PyDictKeyEntry *entry_ptr;
1742 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001743
1744 if (!PyDict_Check(op))
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001745 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 mp = (PyDictObject *)op;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001747 i = *ppos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001748 if (mp->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09001749 if (i < 0 || i >= mp->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001750 return 0;
INADA Naokica2d8be2016-11-04 16:59:10 +09001751 /* values of split table is always dense */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001752 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
INADA Naokica2d8be2016-11-04 16:59:10 +09001753 value = mp->ma_values[i];
1754 assert(value != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001756 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09001757 Py_ssize_t n = mp->ma_keys->dk_nentries;
1758 if (i < 0 || i >= n)
1759 return 0;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001760 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
1761 while (i < n && entry_ptr->me_value == NULL) {
1762 entry_ptr++;
1763 i++;
Victor Stinner742da042016-09-07 17:40:12 -07001764 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001765 if (i >= n)
1766 return 0;
1767 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001769 *ppos = i+1;
1770 if (pkey)
1771 *pkey = entry_ptr->me_key;
1772 if (phash)
1773 *phash = entry_ptr->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001774 if (pvalue)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001775 *pvalue = value;
1776 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001777}
1778
Tim Peters080c88b2003-02-15 03:01:11 +00001779/*
1780 * Iterate over a dict. Use like so:
1781 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001782 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +00001783 * PyObject *key, *value;
1784 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +00001785 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001786 * Refer to borrowed references in key and value.
Tim Peters080c88b2003-02-15 03:01:11 +00001787 * }
1788 *
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001789 * Return 1 on success, return 0 when the reached the end of the dictionary
1790 * (or if op is not a dictionary)
1791 *
Tim Peters080c88b2003-02-15 03:01:11 +00001792 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +00001793 * mutates the dict. One exception: it is safe if the loop merely changes
1794 * the values associated with the keys (but doesn't insert new keys or
1795 * delete keys), via PyDict_SetItem().
1796 */
Guido van Rossum25831651993-05-19 14:50:45 +00001797int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001798PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001799{
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001800 return _PyDict_Next(op, ppos, pkey, pvalue, NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00001801}
1802
Eric Snow96c6af92015-05-29 22:21:39 -06001803/* Internal version of dict.pop(). */
1804PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001805_PyDict_Pop_KnownHash(PyObject *dict, PyObject *key, Py_hash_t hash, PyObject *deflt)
Eric Snow96c6af92015-05-29 22:21:39 -06001806{
Victor Stinner742da042016-09-07 17:40:12 -07001807 Py_ssize_t ix, hashpos;
Eric Snow96c6af92015-05-29 22:21:39 -06001808 PyObject *old_value, *old_key;
1809 PyDictKeyEntry *ep;
Yury Selivanov684ef2c2016-10-28 19:01:21 -04001810 PyDictObject *mp;
1811
1812 assert(PyDict_Check(dict));
1813 mp = (PyDictObject *)dict;
Eric Snow96c6af92015-05-29 22:21:39 -06001814
1815 if (mp->ma_used == 0) {
1816 if (deflt) {
1817 Py_INCREF(deflt);
1818 return deflt;
1819 }
1820 _PyErr_SetKeyError(key);
1821 return NULL;
1822 }
INADA Naoki778928b2017-08-03 23:45:15 +09001823 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner742da042016-09-07 17:40:12 -07001824 if (ix == DKIX_ERROR)
Eric Snow96c6af92015-05-29 22:21:39 -06001825 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001826 if (ix == DKIX_EMPTY || old_value == NULL) {
Eric Snow96c6af92015-05-29 22:21:39 -06001827 if (deflt) {
1828 Py_INCREF(deflt);
1829 return deflt;
1830 }
1831 _PyErr_SetKeyError(key);
1832 return NULL;
1833 }
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001834
Victor Stinner78601a32016-09-09 19:28:36 -07001835 // Split table doesn't allow deletion. Combine it.
1836 if (_PyDict_HasSplitTable(mp)) {
1837 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1838 return NULL;
1839 }
INADA Naoki778928b2017-08-03 23:45:15 +09001840 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner78601a32016-09-09 19:28:36 -07001841 assert(ix >= 0);
1842 }
1843
INADA Naoki778928b2017-08-03 23:45:15 +09001844 hashpos = lookdict_index(mp->ma_keys, hash, ix);
1845 assert(hashpos >= 0);
Victor Stinner78601a32016-09-09 19:28:36 -07001846 assert(old_value != NULL);
Eric Snow96c6af92015-05-29 22:21:39 -06001847 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001848 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naokia7576492018-11-14 18:39:27 +09001849 dictkeys_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
Victor Stinner78601a32016-09-09 19:28:36 -07001850 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1851 ENSURE_ALLOWS_DELETIONS(mp);
1852 old_key = ep->me_key;
1853 ep->me_key = NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001854 ep->me_value = NULL;
Victor Stinner78601a32016-09-09 19:28:36 -07001855 Py_DECREF(old_key);
Victor Stinner611b0fa2016-09-14 15:02:01 +02001856
Victor Stinner0fc91ee2019-04-12 21:51:34 +02001857 ASSERT_CONSISTENT(mp);
Eric Snow96c6af92015-05-29 22:21:39 -06001858 return old_value;
1859}
1860
Serhiy Storchaka67796522017-01-12 18:34:33 +02001861PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001862_PyDict_Pop(PyObject *dict, PyObject *key, PyObject *deflt)
Serhiy Storchaka67796522017-01-12 18:34:33 +02001863{
1864 Py_hash_t hash;
1865
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001866 if (((PyDictObject *)dict)->ma_used == 0) {
Serhiy Storchaka67796522017-01-12 18:34:33 +02001867 if (deflt) {
1868 Py_INCREF(deflt);
1869 return deflt;
1870 }
1871 _PyErr_SetKeyError(key);
1872 return NULL;
1873 }
1874 if (!PyUnicode_CheckExact(key) ||
1875 (hash = ((PyASCIIObject *) key)->hash) == -1) {
1876 hash = PyObject_Hash(key);
1877 if (hash == -1)
1878 return NULL;
1879 }
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001880 return _PyDict_Pop_KnownHash(dict, key, hash, deflt);
Serhiy Storchaka67796522017-01-12 18:34:33 +02001881}
1882
Eric Snow96c6af92015-05-29 22:21:39 -06001883/* Internal version of dict.from_keys(). It is subclass-friendly. */
1884PyObject *
1885_PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
1886{
1887 PyObject *it; /* iter(iterable) */
1888 PyObject *key;
1889 PyObject *d;
1890 int status;
1891
Victor Stinnera5ed5f02016-12-06 18:45:50 +01001892 d = _PyObject_CallNoArg(cls);
Eric Snow96c6af92015-05-29 22:21:39 -06001893 if (d == NULL)
1894 return NULL;
1895
1896 if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
1897 if (PyDict_CheckExact(iterable)) {
1898 PyDictObject *mp = (PyDictObject *)d;
1899 PyObject *oldvalue;
1900 Py_ssize_t pos = 0;
1901 PyObject *key;
1902 Py_hash_t hash;
1903
Serhiy Storchakac61ac162017-03-21 08:52:38 +02001904 if (dictresize(mp, ESTIMATE_SIZE(PyDict_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001905 Py_DECREF(d);
1906 return NULL;
1907 }
1908
1909 while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
1910 if (insertdict(mp, key, hash, value)) {
1911 Py_DECREF(d);
1912 return NULL;
1913 }
1914 }
1915 return d;
1916 }
1917 if (PyAnySet_CheckExact(iterable)) {
1918 PyDictObject *mp = (PyDictObject *)d;
1919 Py_ssize_t pos = 0;
1920 PyObject *key;
1921 Py_hash_t hash;
1922
Victor Stinner742da042016-09-07 17:40:12 -07001923 if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001924 Py_DECREF(d);
1925 return NULL;
1926 }
1927
1928 while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
1929 if (insertdict(mp, key, hash, value)) {
1930 Py_DECREF(d);
1931 return NULL;
1932 }
1933 }
1934 return d;
1935 }
1936 }
1937
1938 it = PyObject_GetIter(iterable);
1939 if (it == NULL){
1940 Py_DECREF(d);
1941 return NULL;
1942 }
1943
1944 if (PyDict_CheckExact(d)) {
1945 while ((key = PyIter_Next(it)) != NULL) {
1946 status = PyDict_SetItem(d, key, value);
1947 Py_DECREF(key);
1948 if (status < 0)
1949 goto Fail;
1950 }
1951 } else {
1952 while ((key = PyIter_Next(it)) != NULL) {
1953 status = PyObject_SetItem(d, key, value);
1954 Py_DECREF(key);
1955 if (status < 0)
1956 goto Fail;
1957 }
1958 }
1959
1960 if (PyErr_Occurred())
1961 goto Fail;
1962 Py_DECREF(it);
1963 return d;
1964
1965Fail:
1966 Py_DECREF(it);
1967 Py_DECREF(d);
1968 return NULL;
1969}
1970
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001971/* Methods */
1972
1973static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001974dict_dealloc(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001975{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001976 PyObject **values = mp->ma_values;
1977 PyDictKeysObject *keys = mp->ma_keys;
1978 Py_ssize_t i, n;
INADA Naokia6296d32017-08-24 14:55:17 +09001979
1980 /* bpo-31095: UnTrack is needed before calling any callbacks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 PyObject_GC_UnTrack(mp);
Jeroen Demeyer351c6742019-05-10 19:21:11 +02001982 Py_TRASHCAN_BEGIN(mp, dict_dealloc)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001983 if (values != NULL) {
1984 if (values != empty_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001985 for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001986 Py_XDECREF(values[i]);
1987 }
1988 free_values(values);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 }
INADA Naokia7576492018-11-14 18:39:27 +09001990 dictkeys_decref(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 }
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02001992 else if (keys != NULL) {
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001993 assert(keys->dk_refcnt == 1);
INADA Naokia7576492018-11-14 18:39:27 +09001994 dictkeys_decref(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001995 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
1997 free_list[numfree++] = mp;
1998 else
1999 Py_TYPE(mp)->tp_free((PyObject *)mp);
Jeroen Demeyer351c6742019-05-10 19:21:11 +02002000 Py_TRASHCAN_END
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002001}
2002
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002004static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002005dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 Py_ssize_t i;
Victor Stinnerf91929b2013-11-19 13:07:38 +01002008 PyObject *key = NULL, *value = NULL;
2009 _PyUnicodeWriter writer;
2010 int first;
Guido van Rossum255443b1998-04-10 22:47:14 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 i = Py_ReprEnter((PyObject *)mp);
2013 if (i != 0) {
2014 return i > 0 ? PyUnicode_FromString("{...}") : NULL;
2015 }
Guido van Rossum255443b1998-04-10 22:47:14 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 if (mp->ma_used == 0) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01002018 Py_ReprLeave((PyObject *)mp);
2019 return PyUnicode_FromString("{}");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 }
Tim Petersa7259592001-06-16 05:11:17 +00002021
Victor Stinnerf91929b2013-11-19 13:07:38 +01002022 _PyUnicodeWriter_Init(&writer);
2023 writer.overallocate = 1;
2024 /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
2025 writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +00002026
Victor Stinnerf91929b2013-11-19 13:07:38 +01002027 if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
2028 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 /* Do repr() on each key+value pair, and insert ": " between them.
2031 Note that repr may mutate the dict. */
2032 i = 0;
Victor Stinnerf91929b2013-11-19 13:07:38 +01002033 first = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01002035 PyObject *s;
2036 int res;
2037
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002038 /* Prevent repr from deleting key or value during key format. */
2039 Py_INCREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 Py_INCREF(value);
Victor Stinnerf97dfd72013-07-18 01:00:45 +02002041
Victor Stinnerf91929b2013-11-19 13:07:38 +01002042 if (!first) {
2043 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
2044 goto error;
2045 }
2046 first = 0;
2047
2048 s = PyObject_Repr(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 if (s == NULL)
Victor Stinnerf91929b2013-11-19 13:07:38 +01002050 goto error;
2051 res = _PyUnicodeWriter_WriteStr(&writer, s);
2052 Py_DECREF(s);
2053 if (res < 0)
2054 goto error;
2055
2056 if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
2057 goto error;
2058
2059 s = PyObject_Repr(value);
2060 if (s == NULL)
2061 goto error;
2062 res = _PyUnicodeWriter_WriteStr(&writer, s);
2063 Py_DECREF(s);
2064 if (res < 0)
2065 goto error;
2066
2067 Py_CLEAR(key);
2068 Py_CLEAR(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 }
Tim Petersa7259592001-06-16 05:11:17 +00002070
Victor Stinnerf91929b2013-11-19 13:07:38 +01002071 writer.overallocate = 0;
2072 if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
2073 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 Py_ReprLeave((PyObject *)mp);
Victor Stinnerf91929b2013-11-19 13:07:38 +01002076
2077 return _PyUnicodeWriter_Finish(&writer);
2078
2079error:
2080 Py_ReprLeave((PyObject *)mp);
2081 _PyUnicodeWriter_Dealloc(&writer);
2082 Py_XDECREF(key);
2083 Py_XDECREF(value);
2084 return NULL;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002085}
2086
Martin v. Löwis18e16552006-02-15 17:27:45 +00002087static Py_ssize_t
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002088dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 return mp->ma_used;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002091}
2092
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002093static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002094dict_subscript(PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002095{
Victor Stinner742da042016-09-07 17:40:12 -07002096 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002097 Py_hash_t hash;
INADA Naokiba609772016-12-07 20:41:42 +09002098 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002101 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 hash = PyObject_Hash(key);
2103 if (hash == -1)
2104 return NULL;
2105 }
INADA Naoki778928b2017-08-03 23:45:15 +09002106 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002107 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002109 if (ix == DKIX_EMPTY || value == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 if (!PyDict_CheckExact(mp)) {
2111 /* Look up __missing__ method if we're a subclass. */
2112 PyObject *missing, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05002113 _Py_IDENTIFIER(__missing__);
2114 missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 if (missing != NULL) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +02002116 res = _PyObject_CallOneArg(missing, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 Py_DECREF(missing);
2118 return res;
2119 }
2120 else if (PyErr_Occurred())
2121 return NULL;
2122 }
Raymond Hettinger69492da2013-09-02 15:59:26 -07002123 _PyErr_SetKeyError(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 return NULL;
2125 }
INADA Naokiba609772016-12-07 20:41:42 +09002126 Py_INCREF(value);
2127 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002128}
2129
2130static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002131dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 if (w == NULL)
2134 return PyDict_DelItem((PyObject *)mp, v);
2135 else
2136 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002137}
2138
Guido van Rossuma9e7a811997-05-13 21:02:11 +00002139static PyMappingMethods dict_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 (lenfunc)dict_length, /*mp_length*/
2141 (binaryfunc)dict_subscript, /*mp_subscript*/
2142 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002143};
2144
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002145static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002146dict_keys(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002147{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002148 PyObject *v;
2149 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002150 PyDictKeyEntry *ep;
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002151 Py_ssize_t n, offset;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002152 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002153
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002154 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 n = mp->ma_used;
2156 v = PyList_New(n);
2157 if (v == NULL)
2158 return NULL;
2159 if (n != mp->ma_used) {
2160 /* Durnit. The allocations caused the dict to resize.
2161 * Just start over, this shouldn't normally happen.
2162 */
2163 Py_DECREF(v);
2164 goto again;
2165 }
Victor Stinner742da042016-09-07 17:40:12 -07002166 ep = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002167 if (mp->ma_values) {
2168 value_ptr = mp->ma_values;
2169 offset = sizeof(PyObject *);
2170 }
2171 else {
2172 value_ptr = &ep[0].me_value;
2173 offset = sizeof(PyDictKeyEntry);
2174 }
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002175 for (i = 0, j = 0; j < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002176 if (*value_ptr != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 PyObject *key = ep[i].me_key;
2178 Py_INCREF(key);
2179 PyList_SET_ITEM(v, j, key);
2180 j++;
2181 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002182 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 }
2184 assert(j == n);
2185 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002186}
2187
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002188static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002189dict_values(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002190{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002191 PyObject *v;
2192 Py_ssize_t i, j;
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002193 PyDictKeyEntry *ep;
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002194 Py_ssize_t n, offset;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002195 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002196
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002197 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 n = mp->ma_used;
2199 v = PyList_New(n);
2200 if (v == NULL)
2201 return NULL;
2202 if (n != mp->ma_used) {
2203 /* Durnit. The allocations caused the dict to resize.
2204 * Just start over, this shouldn't normally happen.
2205 */
2206 Py_DECREF(v);
2207 goto again;
2208 }
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002209 ep = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002210 if (mp->ma_values) {
2211 value_ptr = mp->ma_values;
2212 offset = sizeof(PyObject *);
2213 }
2214 else {
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002215 value_ptr = &ep[0].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002216 offset = sizeof(PyDictKeyEntry);
2217 }
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002218 for (i = 0, j = 0; j < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002219 PyObject *value = *value_ptr;
2220 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2221 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 Py_INCREF(value);
2223 PyList_SET_ITEM(v, j, value);
2224 j++;
2225 }
2226 }
2227 assert(j == n);
2228 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002229}
2230
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002231static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002232dict_items(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002233{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002234 PyObject *v;
2235 Py_ssize_t i, j, n;
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002236 Py_ssize_t offset;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002237 PyObject *item, *key;
2238 PyDictKeyEntry *ep;
2239 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 /* Preallocate the list of tuples, to avoid allocations during
2242 * the loop over the items, which could trigger GC, which
2243 * could resize the dict. :-(
2244 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002245 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 n = mp->ma_used;
2247 v = PyList_New(n);
2248 if (v == NULL)
2249 return NULL;
2250 for (i = 0; i < n; i++) {
2251 item = PyTuple_New(2);
2252 if (item == NULL) {
2253 Py_DECREF(v);
2254 return NULL;
2255 }
2256 PyList_SET_ITEM(v, i, item);
2257 }
2258 if (n != mp->ma_used) {
2259 /* Durnit. The allocations caused the dict to resize.
2260 * Just start over, this shouldn't normally happen.
2261 */
2262 Py_DECREF(v);
2263 goto again;
2264 }
2265 /* Nothing we do below makes any function calls. */
Victor Stinner742da042016-09-07 17:40:12 -07002266 ep = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002267 if (mp->ma_values) {
2268 value_ptr = mp->ma_values;
2269 offset = sizeof(PyObject *);
2270 }
2271 else {
2272 value_ptr = &ep[0].me_value;
2273 offset = sizeof(PyDictKeyEntry);
2274 }
Cheryl Sabellaf66e3362019-04-05 06:08:43 -04002275 for (i = 0, j = 0; j < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002276 PyObject *value = *value_ptr;
2277 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2278 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 key = ep[i].me_key;
2280 item = PyList_GET_ITEM(v, j);
2281 Py_INCREF(key);
2282 PyTuple_SET_ITEM(item, 0, key);
2283 Py_INCREF(value);
2284 PyTuple_SET_ITEM(item, 1, value);
2285 j++;
2286 }
2287 }
2288 assert(j == n);
2289 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002290}
2291
Larry Hastings5c661892014-01-24 06:17:25 -08002292/*[clinic input]
2293@classmethod
2294dict.fromkeys
Larry Hastings5c661892014-01-24 06:17:25 -08002295 iterable: object
2296 value: object=None
2297 /
2298
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002299Create a new dictionary with keys from iterable and values set to value.
Larry Hastings5c661892014-01-24 06:17:25 -08002300[clinic start generated code]*/
2301
Larry Hastings5c661892014-01-24 06:17:25 -08002302static PyObject *
2303dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002304/*[clinic end generated code: output=8fb98e4b10384999 input=382ba4855d0f74c3]*/
Larry Hastings5c661892014-01-24 06:17:25 -08002305{
Eric Snow96c6af92015-05-29 22:21:39 -06002306 return _PyDict_FromKeys((PyObject *)type, iterable, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002307}
2308
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002309static int
Victor Stinner742da042016-09-07 17:40:12 -07002310dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
2311 const char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 PyObject *arg = NULL;
2314 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002315
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002316 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 result = -1;
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002318 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 else if (arg != NULL) {
Serhiy Storchakaf163aea2019-09-25 09:47:00 +03002320 if (PyDict_CheckExact(arg)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 result = PyDict_Merge(self, arg, 1);
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002322 }
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002323 else {
Serhiy Storchakaf163aea2019-09-25 09:47:00 +03002324 _Py_IDENTIFIER(keys);
2325 PyObject *func;
2326 if (_PyObject_LookupAttrId(arg, &PyId_keys, &func) < 0) {
2327 result = -1;
2328 }
2329 else if (func != NULL) {
2330 Py_DECREF(func);
2331 result = PyDict_Merge(self, arg, 1);
2332 }
2333 else {
2334 result = PyDict_MergeFromSeq2(self, arg, 1);
2335 }
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002336 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 }
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 if (result == 0 && kwds != NULL) {
2340 if (PyArg_ValidateKeywordArguments(kwds))
2341 result = PyDict_Merge(self, kwds, 1);
2342 else
2343 result = -1;
2344 }
2345 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002346}
2347
Victor Stinner91f0d4a2017-01-19 12:45:06 +01002348/* Note: dict.update() uses the METH_VARARGS|METH_KEYWORDS calling convention.
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002349 Using METH_FASTCALL|METH_KEYWORDS would make dict.update(**dict2) calls
2350 slower, see the issue #29312. */
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002351static PyObject *
2352dict_update(PyObject *self, PyObject *args, PyObject *kwds)
2353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 if (dict_update_common(self, args, kwds, "update") != -1)
2355 Py_RETURN_NONE;
2356 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002357}
2358
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002359/* Update unconditionally replaces existing items.
2360 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00002361 otherwise it leaves existing items unchanged.
2362
2363 PyDict_{Update,Merge} update/merge from a mapping object.
2364
Tim Petersf582b822001-12-11 18:51:08 +00002365 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00002366 producing iterable objects of length 2.
2367*/
2368
Tim Petersf582b822001-12-11 18:51:08 +00002369int
Tim Peters1fc240e2001-10-26 05:06:50 +00002370PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
2371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 PyObject *it; /* iter(seq2) */
2373 Py_ssize_t i; /* index into seq2 of current element */
2374 PyObject *item; /* seq2[i] */
2375 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 assert(d != NULL);
2378 assert(PyDict_Check(d));
2379 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 it = PyObject_GetIter(seq2);
2382 if (it == NULL)
2383 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 for (i = 0; ; ++i) {
2386 PyObject *key, *value;
2387 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00002388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 fast = NULL;
2390 item = PyIter_Next(it);
2391 if (item == NULL) {
2392 if (PyErr_Occurred())
2393 goto Fail;
2394 break;
2395 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 /* Convert item to sequence, and verify length 2. */
2398 fast = PySequence_Fast(item, "");
2399 if (fast == NULL) {
2400 if (PyErr_ExceptionMatches(PyExc_TypeError))
2401 PyErr_Format(PyExc_TypeError,
2402 "cannot convert dictionary update "
2403 "sequence element #%zd to a sequence",
2404 i);
2405 goto Fail;
2406 }
2407 n = PySequence_Fast_GET_SIZE(fast);
2408 if (n != 2) {
2409 PyErr_Format(PyExc_ValueError,
2410 "dictionary update sequence element #%zd "
2411 "has length %zd; 2 is required",
2412 i, n);
2413 goto Fail;
2414 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 /* Update/merge with this (key, value) pair. */
2417 key = PySequence_Fast_GET_ITEM(fast, 0);
2418 value = PySequence_Fast_GET_ITEM(fast, 1);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002419 Py_INCREF(key);
2420 Py_INCREF(value);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002421 if (override) {
2422 if (PyDict_SetItem(d, key, value) < 0) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002423 Py_DECREF(key);
2424 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 goto Fail;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002426 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002428 else if (PyDict_GetItemWithError(d, key) == NULL) {
2429 if (PyErr_Occurred() || PyDict_SetItem(d, key, value) < 0) {
2430 Py_DECREF(key);
2431 Py_DECREF(value);
2432 goto Fail;
2433 }
2434 }
2435
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002436 Py_DECREF(key);
2437 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 Py_DECREF(fast);
2439 Py_DECREF(item);
2440 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 i = 0;
Victor Stinner0fc91ee2019-04-12 21:51:34 +02002443 ASSERT_CONSISTENT(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00002445Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 Py_XDECREF(item);
2447 Py_XDECREF(fast);
2448 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002449Return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 Py_DECREF(it);
2451 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00002452}
2453
doko@ubuntu.comc96df682016-10-11 08:04:02 +02002454static int
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002455dict_merge(PyObject *a, PyObject *b, int override)
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002456{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002457 PyDictObject *mp, *other;
2458 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -07002459 PyDictKeyEntry *entry, *ep0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002460
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002461 assert(0 <= override && override <= 2);
2462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 /* We accept for the argument either a concrete dictionary object,
2464 * or an abstract "mapping" object. For the former, we can do
2465 * things quite efficiently. For the latter, we only require that
2466 * PyMapping_Keys() and PyObject_GetItem() be supported.
2467 */
2468 if (a == NULL || !PyDict_Check(a) || b == NULL) {
2469 PyErr_BadInternalCall();
2470 return -1;
2471 }
2472 mp = (PyDictObject*)a;
INADA Naoki2aaf98c2018-09-26 12:59:00 +09002473 if (PyDict_Check(b) && (Py_TYPE(b)->tp_iter == (getiterfunc)dict_iter)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 other = (PyDictObject*)b;
2475 if (other == mp || other->ma_used == 0)
2476 /* a.update(a) or a.update({}); nothing to do */
2477 return 0;
2478 if (mp->ma_used == 0)
2479 /* Since the target dict is empty, PyDict_GetItem()
2480 * always returns NULL. Setting override to 1
2481 * skips the unnecessary test.
2482 */
2483 override = 1;
2484 /* Do one big resize at the start, rather than
2485 * incrementally resizing as we insert new items. Expect
2486 * that there will be no (or few) overlapping keys.
2487 */
INADA Naokib1152be2016-10-27 19:26:50 +09002488 if (USABLE_FRACTION(mp->ma_keys->dk_size) < other->ma_used) {
2489 if (dictresize(mp, ESTIMATE_SIZE(mp->ma_used + other->ma_used))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 return -1;
INADA Naokib1152be2016-10-27 19:26:50 +09002491 }
2492 }
Victor Stinner742da042016-09-07 17:40:12 -07002493 ep0 = DK_ENTRIES(other->ma_keys);
2494 for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002495 PyObject *key, *value;
2496 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002497 entry = &ep0[i];
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002498 key = entry->me_key;
2499 hash = entry->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002500 if (other->ma_values)
2501 value = other->ma_values[i];
2502 else
2503 value = entry->me_value;
2504
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002505 if (value != NULL) {
2506 int err = 0;
2507 Py_INCREF(key);
2508 Py_INCREF(value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002509 if (override == 1)
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002510 err = insertdict(mp, key, hash, value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002511 else if (_PyDict_GetItem_KnownHash(a, key, hash) == NULL) {
2512 if (PyErr_Occurred()) {
2513 Py_DECREF(value);
2514 Py_DECREF(key);
2515 return -1;
2516 }
2517 err = insertdict(mp, key, hash, value);
2518 }
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002519 else if (override != 0) {
2520 _PyErr_SetKeyError(key);
2521 Py_DECREF(value);
2522 Py_DECREF(key);
2523 return -1;
2524 }
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002525 Py_DECREF(value);
2526 Py_DECREF(key);
2527 if (err != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 return -1;
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002529
Victor Stinner742da042016-09-07 17:40:12 -07002530 if (n != other->ma_keys->dk_nentries) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002531 PyErr_SetString(PyExc_RuntimeError,
2532 "dict mutated during update");
2533 return -1;
2534 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 }
2536 }
2537 }
2538 else {
2539 /* Do it the generic, slower way */
2540 PyObject *keys = PyMapping_Keys(b);
2541 PyObject *iter;
2542 PyObject *key, *value;
2543 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 if (keys == NULL)
2546 /* Docstring says this is equivalent to E.keys() so
2547 * if E doesn't have a .keys() method we want
2548 * AttributeError to percolate up. Might as well
2549 * do the same for any other error.
2550 */
2551 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 iter = PyObject_GetIter(keys);
2554 Py_DECREF(keys);
2555 if (iter == NULL)
2556 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002559 if (override != 1) {
2560 if (PyDict_GetItemWithError(a, key) != NULL) {
2561 if (override != 0) {
2562 _PyErr_SetKeyError(key);
2563 Py_DECREF(key);
2564 Py_DECREF(iter);
2565 return -1;
2566 }
2567 Py_DECREF(key);
2568 continue;
2569 }
2570 else if (PyErr_Occurred()) {
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002571 Py_DECREF(key);
2572 Py_DECREF(iter);
2573 return -1;
2574 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 }
2576 value = PyObject_GetItem(b, key);
2577 if (value == NULL) {
2578 Py_DECREF(iter);
2579 Py_DECREF(key);
2580 return -1;
2581 }
2582 status = PyDict_SetItem(a, key, value);
2583 Py_DECREF(key);
2584 Py_DECREF(value);
2585 if (status < 0) {
2586 Py_DECREF(iter);
2587 return -1;
2588 }
2589 }
2590 Py_DECREF(iter);
2591 if (PyErr_Occurred())
2592 /* Iterator completed, via error */
2593 return -1;
2594 }
Victor Stinner0fc91ee2019-04-12 21:51:34 +02002595 ASSERT_CONSISTENT(a);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002597}
2598
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002599int
2600PyDict_Update(PyObject *a, PyObject *b)
2601{
2602 return dict_merge(a, b, 1);
2603}
2604
2605int
2606PyDict_Merge(PyObject *a, PyObject *b, int override)
2607{
2608 /* XXX Deprecate override not in (0, 1). */
2609 return dict_merge(a, b, override != 0);
2610}
2611
2612int
2613_PyDict_MergeEx(PyObject *a, PyObject *b, int override)
2614{
2615 return dict_merge(a, b, override);
2616}
2617
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002618static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302619dict_copy(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002622}
2623
2624PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002625PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 PyObject *copy;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002628 PyDictObject *mp;
2629 Py_ssize_t i, n;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 if (o == NULL || !PyDict_Check(o)) {
2632 PyErr_BadInternalCall();
2633 return NULL;
2634 }
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002635
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002636 mp = (PyDictObject *)o;
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002637 if (mp->ma_used == 0) {
2638 /* The dict is empty; just return a new dict. */
2639 return PyDict_New();
2640 }
2641
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002642 if (_PyDict_HasSplitTable(mp)) {
2643 PyDictObject *split_copy;
Victor Stinner742da042016-09-07 17:40:12 -07002644 Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
2645 PyObject **newvalues;
2646 newvalues = new_values(size);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002647 if (newvalues == NULL)
2648 return PyErr_NoMemory();
2649 split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
2650 if (split_copy == NULL) {
2651 free_values(newvalues);
2652 return NULL;
2653 }
2654 split_copy->ma_values = newvalues;
2655 split_copy->ma_keys = mp->ma_keys;
2656 split_copy->ma_used = mp->ma_used;
INADA Naokid1c82c52018-04-03 11:43:53 +09002657 split_copy->ma_version_tag = DICT_NEXT_VERSION();
INADA Naokia7576492018-11-14 18:39:27 +09002658 dictkeys_incref(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002659 for (i = 0, n = size; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002660 PyObject *value = mp->ma_values[i];
2661 Py_XINCREF(value);
2662 split_copy->ma_values[i] = value;
2663 }
Benjamin Peterson7ce67e42012-04-24 10:32:57 -04002664 if (_PyObject_GC_IS_TRACKED(mp))
2665 _PyObject_GC_TRACK(split_copy);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002666 return (PyObject *)split_copy;
2667 }
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002668
2669 if (PyDict_CheckExact(mp) && mp->ma_values == NULL &&
2670 (mp->ma_used >= (mp->ma_keys->dk_nentries * 2) / 3))
2671 {
2672 /* Use fast-copy if:
2673
2674 (1) 'mp' is an instance of a subclassed dict; and
2675
2676 (2) 'mp' is not a split-dict; and
2677
2678 (3) if 'mp' is non-compact ('del' operation does not resize dicts),
2679 do fast-copy only if it has at most 1/3 non-used keys.
2680
Ville Skyttä61f82e02018-04-20 23:08:45 +03002681 The last condition (3) is important to guard against a pathological
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002682 case when a large dict is almost emptied with multiple del/pop
2683 operations and copied after that. In cases like this, we defer to
2684 PyDict_Merge, which produces a compacted copy.
2685 */
2686 return clone_combined_dict(mp);
2687 }
2688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 copy = PyDict_New();
2690 if (copy == NULL)
2691 return NULL;
2692 if (PyDict_Merge(copy, o, 1) == 0)
2693 return copy;
2694 Py_DECREF(copy);
2695 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002696}
2697
Martin v. Löwis18e16552006-02-15 17:27:45 +00002698Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00002699PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00002700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 if (mp == NULL || !PyDict_Check(mp)) {
2702 PyErr_BadInternalCall();
2703 return -1;
2704 }
2705 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00002706}
2707
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002708PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002709PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 if (mp == NULL || !PyDict_Check(mp)) {
2712 PyErr_BadInternalCall();
2713 return NULL;
2714 }
2715 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002716}
2717
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002718PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002719PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 if (mp == NULL || !PyDict_Check(mp)) {
2722 PyErr_BadInternalCall();
2723 return NULL;
2724 }
2725 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002726}
2727
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002728PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002729PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 if (mp == NULL || !PyDict_Check(mp)) {
2732 PyErr_BadInternalCall();
2733 return NULL;
2734 }
2735 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002736}
2737
Tim Peterse63415e2001-05-08 04:38:29 +00002738/* Return 1 if dicts equal, 0 if not, -1 if error.
2739 * Gets out as soon as any difference is detected.
2740 * Uses only Py_EQ comparison.
2741 */
2742static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002743dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00002744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00002746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 if (a->ma_used != b->ma_used)
2748 /* can't be equal if # of entries differ */
2749 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Victor Stinner742da042016-09-07 17:40:12 -07002751 for (i = 0; i < a->ma_keys->dk_nentries; i++) {
2752 PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002753 PyObject *aval;
2754 if (a->ma_values)
2755 aval = a->ma_values[i];
2756 else
2757 aval = ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 if (aval != NULL) {
2759 int cmp;
2760 PyObject *bval;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002761 PyObject *key = ep->me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 /* temporarily bump aval's refcount to ensure it stays
2763 alive until we're done with it */
2764 Py_INCREF(aval);
2765 /* ditto for key */
2766 Py_INCREF(key);
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002767 /* reuse the known hash value */
INADA Naoki778928b2017-08-03 23:45:15 +09002768 b->ma_keys->dk_lookup(b, key, ep->me_hash, &bval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 if (bval == NULL) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002770 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 Py_DECREF(aval);
2772 if (PyErr_Occurred())
2773 return -1;
2774 return 0;
2775 }
2776 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002777 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 Py_DECREF(aval);
2779 if (cmp <= 0) /* error or not equal */
2780 return cmp;
2781 }
2782 }
2783 return 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002784}
Tim Peterse63415e2001-05-08 04:38:29 +00002785
2786static PyObject *
2787dict_richcompare(PyObject *v, PyObject *w, int op)
2788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 int cmp;
2790 PyObject *res;
Tim Peterse63415e2001-05-08 04:38:29 +00002791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 if (!PyDict_Check(v) || !PyDict_Check(w)) {
2793 res = Py_NotImplemented;
2794 }
2795 else if (op == Py_EQ || op == Py_NE) {
2796 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
2797 if (cmp < 0)
2798 return NULL;
2799 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
2800 }
2801 else
2802 res = Py_NotImplemented;
2803 Py_INCREF(res);
2804 return res;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002805}
Tim Peterse63415e2001-05-08 04:38:29 +00002806
Larry Hastings61272b72014-01-07 12:41:53 -08002807/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002808
2809@coexist
2810dict.__contains__
2811
2812 key: object
2813 /
2814
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002815True if the dictionary has the specified key, else False.
Larry Hastings61272b72014-01-07 12:41:53 -08002816[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002817
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002818static PyObject *
Larry Hastingsc2047262014-01-25 20:43:29 -08002819dict___contains__(PyDictObject *self, PyObject *key)
Serhiy Storchaka19d25972017-02-04 08:05:07 +02002820/*[clinic end generated code: output=a3d03db709ed6e6b input=fe1cb42ad831e820]*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002821{
Larry Hastingsc2047262014-01-25 20:43:29 -08002822 register PyDictObject *mp = self;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002823 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002824 Py_ssize_t ix;
INADA Naokiba609772016-12-07 20:41:42 +09002825 PyObject *value;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002828 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 hash = PyObject_Hash(key);
2830 if (hash == -1)
2831 return NULL;
2832 }
INADA Naoki778928b2017-08-03 23:45:15 +09002833 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002834 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002836 if (ix == DKIX_EMPTY || value == NULL)
Victor Stinner742da042016-09-07 17:40:12 -07002837 Py_RETURN_FALSE;
2838 Py_RETURN_TRUE;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002839}
2840
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002841/*[clinic input]
2842dict.get
2843
2844 key: object
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002845 default: object = None
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002846 /
2847
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002848Return the value for key if key is in the dictionary, else default.
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002849[clinic start generated code]*/
2850
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002851static PyObject *
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002852dict_get_impl(PyDictObject *self, PyObject *key, PyObject *default_value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002853/*[clinic end generated code: output=bba707729dee05bf input=279ddb5790b6b107]*/
Barry Warsawc38c5da1997-10-06 17:49:20 +00002854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002856 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002857 Py_ssize_t ix;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002860 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 hash = PyObject_Hash(key);
2862 if (hash == -1)
2863 return NULL;
2864 }
INADA Naoki778928b2017-08-03 23:45:15 +09002865 ix = (self->ma_keys->dk_lookup) (self, key, hash, &val);
Victor Stinner742da042016-09-07 17:40:12 -07002866 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002868 if (ix == DKIX_EMPTY || val == NULL) {
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002869 val = default_value;
INADA Naokiba609772016-12-07 20:41:42 +09002870 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 Py_INCREF(val);
2872 return val;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002873}
2874
Benjamin Peterson00e98862013-03-07 22:16:29 -05002875PyObject *
2876PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
Guido van Rossum164452c2000-08-08 16:12:54 +00002877{
Benjamin Peterson00e98862013-03-07 22:16:29 -05002878 PyDictObject *mp = (PyDictObject *)d;
INADA Naoki93f26f72016-11-02 18:45:16 +09002879 PyObject *value;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002880 Py_hash_t hash;
Guido van Rossum164452c2000-08-08 16:12:54 +00002881
Benjamin Peterson00e98862013-03-07 22:16:29 -05002882 if (!PyDict_Check(d)) {
2883 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 return NULL;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002885 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002888 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 hash = PyObject_Hash(key);
2890 if (hash == -1)
2891 return NULL;
2892 }
Inada Naoki2ddc7f62019-03-18 20:38:33 +09002893 if (mp->ma_keys == Py_EMPTY_KEYS) {
2894 if (insert_to_emptydict(mp, key, hash, defaultobj) < 0) {
2895 return NULL;
2896 }
2897 return defaultobj;
2898 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002899
2900 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
2901 if (insertion_resize(mp) < 0)
2902 return NULL;
2903 }
2904
INADA Naoki778928b2017-08-03 23:45:15 +09002905 Py_ssize_t ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002906 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 return NULL;
INADA Naoki93f26f72016-11-02 18:45:16 +09002908
2909 if (_PyDict_HasSplitTable(mp) &&
INADA Naokiba609772016-12-07 20:41:42 +09002910 ((ix >= 0 && value == NULL && mp->ma_used != ix) ||
INADA Naoki93f26f72016-11-02 18:45:16 +09002911 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
2912 if (insertion_resize(mp) < 0) {
2913 return NULL;
2914 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002915 ix = DKIX_EMPTY;
2916 }
2917
2918 if (ix == DKIX_EMPTY) {
2919 PyDictKeyEntry *ep, *ep0;
2920 value = defaultobj;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002921 if (mp->ma_keys->dk_usable <= 0) {
Victor Stinner3c336c52016-09-12 14:17:40 +02002922 if (insertion_resize(mp) < 0) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002923 return NULL;
Victor Stinner3c336c52016-09-12 14:17:40 +02002924 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002925 }
INADA Naoki778928b2017-08-03 23:45:15 +09002926 Py_ssize_t hashpos = find_empty_slot(mp->ma_keys, hash);
INADA Naoki93f26f72016-11-02 18:45:16 +09002927 ep0 = DK_ENTRIES(mp->ma_keys);
2928 ep = &ep0[mp->ma_keys->dk_nentries];
INADA Naokia7576492018-11-14 18:39:27 +09002929 dictkeys_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
Benjamin Petersonb1efa532013-03-04 09:47:50 -05002930 Py_INCREF(key);
INADA Naoki93f26f72016-11-02 18:45:16 +09002931 Py_INCREF(value);
2932 MAINTAIN_TRACKING(mp, key, value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002933 ep->me_key = key;
2934 ep->me_hash = hash;
INADA Naokiba609772016-12-07 20:41:42 +09002935 if (_PyDict_HasSplitTable(mp)) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002936 assert(mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
2937 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Victor Stinner742da042016-09-07 17:40:12 -07002938 }
2939 else {
INADA Naoki93f26f72016-11-02 18:45:16 +09002940 ep->me_value = value;
Victor Stinner742da042016-09-07 17:40:12 -07002941 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002942 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07002943 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naoki93f26f72016-11-02 18:45:16 +09002944 mp->ma_keys->dk_usable--;
2945 mp->ma_keys->dk_nentries++;
2946 assert(mp->ma_keys->dk_usable >= 0);
2947 }
INADA Naokiba609772016-12-07 20:41:42 +09002948 else if (value == NULL) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002949 value = defaultobj;
2950 assert(_PyDict_HasSplitTable(mp));
2951 assert(ix == mp->ma_used);
2952 Py_INCREF(value);
2953 MAINTAIN_TRACKING(mp, key, value);
INADA Naokiba609772016-12-07 20:41:42 +09002954 mp->ma_values[ix] = value;
INADA Naoki93f26f72016-11-02 18:45:16 +09002955 mp->ma_used++;
2956 mp->ma_version_tag = DICT_NEXT_VERSION();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002958
Victor Stinner0fc91ee2019-04-12 21:51:34 +02002959 ASSERT_CONSISTENT(mp);
INADA Naoki93f26f72016-11-02 18:45:16 +09002960 return value;
Guido van Rossum164452c2000-08-08 16:12:54 +00002961}
2962
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002963/*[clinic input]
2964dict.setdefault
2965
2966 key: object
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002967 default: object = None
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002968 /
2969
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002970Insert key with a value of default if key is not in the dictionary.
2971
2972Return the value for key if key is in the dictionary, else default.
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002973[clinic start generated code]*/
2974
Benjamin Peterson00e98862013-03-07 22:16:29 -05002975static PyObject *
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002976dict_setdefault_impl(PyDictObject *self, PyObject *key,
2977 PyObject *default_value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002978/*[clinic end generated code: output=f8c1101ebf69e220 input=0f063756e815fd9d]*/
Benjamin Peterson00e98862013-03-07 22:16:29 -05002979{
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002980 PyObject *val;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002981
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002982 val = PyDict_SetDefault((PyObject *)self, key, default_value);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002983 Py_XINCREF(val);
2984 return val;
2985}
Guido van Rossum164452c2000-08-08 16:12:54 +00002986
2987static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302988dict_clear(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 PyDict_Clear((PyObject *)mp);
2991 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002992}
2993
Inada Naoki9e4f2f32019-04-12 16:11:28 +09002994/*[clinic input]
2995dict.pop
2996
2997 key: object
2998 default: object = NULL
2999 /
3000
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003001D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003002
3003If key is not found, default is returned if given, otherwise KeyError is raised
3004[clinic start generated code]*/
3005
Guido van Rossumba6ab842000-12-12 22:02:18 +00003006static PyObject *
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003007dict_pop_impl(PyDictObject *self, PyObject *key, PyObject *default_value)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003008/*[clinic end generated code: output=3abb47b89f24c21c input=eeebec7812190348]*/
Guido van Rossume027d982002-04-12 15:11:59 +00003009{
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003010 return _PyDict_Pop((PyObject*)self, key, default_value);
Guido van Rossume027d982002-04-12 15:11:59 +00003011}
3012
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003013/*[clinic input]
3014dict.popitem
3015
3016Remove and return a (key, value) pair as a 2-tuple.
3017
3018Pairs are returned in LIFO (last-in, first-out) order.
3019Raises KeyError if the dict is empty.
3020[clinic start generated code]*/
3021
Guido van Rossume027d982002-04-12 15:11:59 +00003022static PyObject *
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003023dict_popitem_impl(PyDictObject *self)
3024/*[clinic end generated code: output=e65fcb04420d230d input=1c38a49f21f64941]*/
Guido van Rossumba6ab842000-12-12 22:02:18 +00003025{
Victor Stinner742da042016-09-07 17:40:12 -07003026 Py_ssize_t i, j;
3027 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 PyObject *res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00003029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 /* Allocate the result tuple before checking the size. Believe it
3031 * or not, this allocation could trigger a garbage collection which
3032 * could empty the dict, so if we checked the size first and that
3033 * happened, the result would be an infinite loop (searching for an
3034 * entry that no longer exists). Note that the usual popitem()
3035 * idiom is "while d: k, v = d.popitem()". so needing to throw the
3036 * tuple away if the dict *is* empty isn't a significant
3037 * inefficiency -- possible, but unlikely in practice.
3038 */
3039 res = PyTuple_New(2);
3040 if (res == NULL)
3041 return NULL;
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003042 if (self->ma_used == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 Py_DECREF(res);
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003044 PyErr_SetString(PyExc_KeyError, "popitem(): dictionary is empty");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 return NULL;
3046 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003047 /* Convert split table to combined table */
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003048 if (self->ma_keys->dk_lookup == lookdict_split) {
3049 if (dictresize(self, DK_SIZE(self->ma_keys))) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003050 Py_DECREF(res);
3051 return NULL;
3052 }
3053 }
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003054 ENSURE_ALLOWS_DELETIONS(self);
Victor Stinner742da042016-09-07 17:40:12 -07003055
3056 /* Pop last item */
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003057 ep0 = DK_ENTRIES(self->ma_keys);
3058 i = self->ma_keys->dk_nentries - 1;
Victor Stinner742da042016-09-07 17:40:12 -07003059 while (i >= 0 && ep0[i].me_value == NULL) {
3060 i--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 }
Victor Stinner742da042016-09-07 17:40:12 -07003062 assert(i >= 0);
3063
3064 ep = &ep0[i];
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003065 j = lookdict_index(self->ma_keys, ep->me_hash, i);
Victor Stinner742da042016-09-07 17:40:12 -07003066 assert(j >= 0);
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003067 assert(dictkeys_get_index(self->ma_keys, j) == i);
3068 dictkeys_set_index(self->ma_keys, j, DKIX_DUMMY);
Victor Stinner742da042016-09-07 17:40:12 -07003069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 PyTuple_SET_ITEM(res, 0, ep->me_key);
3071 PyTuple_SET_ITEM(res, 1, ep->me_value);
Victor Stinner742da042016-09-07 17:40:12 -07003072 ep->me_key = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 ep->me_value = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07003074 /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003075 self->ma_keys->dk_nentries = i;
3076 self->ma_used--;
3077 self->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner0fc91ee2019-04-12 21:51:34 +02003078 ASSERT_CONSISTENT(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 return res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00003080}
3081
Jeremy Hylton8caad492000-06-23 14:18:11 +00003082static int
3083dict_traverse(PyObject *op, visitproc visit, void *arg)
3084{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003085 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson55f44522016-09-05 12:12:59 -07003086 PyDictKeysObject *keys = mp->ma_keys;
Serhiy Storchaka46825d22016-09-26 21:29:34 +03003087 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Victor Stinner742da042016-09-07 17:40:12 -07003088 Py_ssize_t i, n = keys->dk_nentries;
3089
Benjamin Peterson55f44522016-09-05 12:12:59 -07003090 if (keys->dk_lookup == lookdict) {
3091 for (i = 0; i < n; i++) {
3092 if (entries[i].me_value != NULL) {
3093 Py_VISIT(entries[i].me_value);
3094 Py_VISIT(entries[i].me_key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003095 }
3096 }
Victor Stinner742da042016-09-07 17:40:12 -07003097 }
3098 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003099 if (mp->ma_values != NULL) {
Benjamin Peterson55f44522016-09-05 12:12:59 -07003100 for (i = 0; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003101 Py_VISIT(mp->ma_values[i]);
3102 }
3103 }
3104 else {
Benjamin Peterson55f44522016-09-05 12:12:59 -07003105 for (i = 0; i < n; i++) {
3106 Py_VISIT(entries[i].me_value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003107 }
3108 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 }
3110 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00003111}
3112
3113static int
3114dict_tp_clear(PyObject *op)
3115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 PyDict_Clear(op);
3117 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00003118}
3119
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003120static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003121
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003122Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003123_PyDict_SizeOf(PyDictObject *mp)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003124{
Victor Stinner742da042016-09-07 17:40:12 -07003125 Py_ssize_t size, usable, res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003126
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003127 size = DK_SIZE(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07003128 usable = USABLE_FRACTION(size);
3129
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02003130 res = _PyObject_SIZE(Py_TYPE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003131 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07003132 res += usable * sizeof(PyObject*);
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003133 /* If the dictionary is split, the keys portion is accounted-for
3134 in the type object. */
3135 if (mp->ma_keys->dk_refcnt == 1)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003136 res += (sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003137 + DK_IXSIZE(mp->ma_keys) * size
3138 + sizeof(PyDictKeyEntry) * usable);
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003139 return res;
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003140}
3141
3142Py_ssize_t
3143_PyDict_KeysSize(PyDictKeysObject *keys)
3144{
Victor Stinner98ee9d52016-09-08 09:33:56 -07003145 return (sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003146 + DK_IXSIZE(keys) * DK_SIZE(keys)
3147 + USABLE_FRACTION(DK_SIZE(keys)) * sizeof(PyDictKeyEntry));
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003148}
3149
doko@ubuntu.com17210f52016-01-14 14:04:59 +01003150static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303151dict_sizeof(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003152{
3153 return PyLong_FromSsize_t(_PyDict_SizeOf(mp));
3154}
3155
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003156PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
3157
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003158PyDoc_STRVAR(sizeof__doc__,
3159"D.__sizeof__() -> size of D in memory, in bytes");
3160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003161PyDoc_STRVAR(update__doc__,
Brett Cannonf2754162013-05-11 14:46:48 -04003162"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n\
3163If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]\n\
3164If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n\
3165In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00003166
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003167PyDoc_STRVAR(clear__doc__,
3168"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00003169
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003170PyDoc_STRVAR(copy__doc__,
3171"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00003172
Guido van Rossumb90c8482007-02-10 01:11:45 +00003173/* Forward */
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303174static PyObject *dictkeys_new(PyObject *, PyObject *);
3175static PyObject *dictitems_new(PyObject *, PyObject *);
3176static PyObject *dictvalues_new(PyObject *, PyObject *);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003177
Guido van Rossum45c85d12007-07-27 16:31:40 +00003178PyDoc_STRVAR(keys__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 "D.keys() -> a set-like object providing a view on D's keys");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003180PyDoc_STRVAR(items__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 "D.items() -> a set-like object providing a view on D's items");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003182PyDoc_STRVAR(values__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 "D.values() -> an object providing a view on D's values");
Guido van Rossumb90c8482007-02-10 01:11:45 +00003184
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003185static PyMethodDef mapp_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -07003186 DICT___CONTAINS___METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003187 {"__getitem__", (PyCFunction)(void(*)(void))dict_subscript, METH_O | METH_COEXIST,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 getitem__doc__},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003189 {"__sizeof__", (PyCFunction)(void(*)(void))dict_sizeof, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 sizeof__doc__},
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01003191 DICT_GET_METHODDEF
3192 DICT_SETDEFAULT_METHODDEF
Inada Naoki9e4f2f32019-04-12 16:11:28 +09003193 DICT_POP_METHODDEF
3194 DICT_POPITEM_METHODDEF
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303195 {"keys", dictkeys_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 keys__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303197 {"items", dictitems_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 items__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303199 {"values", dictvalues_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 values__doc__},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003201 {"update", (PyCFunction)(void(*)(void))dict_update, METH_VARARGS | METH_KEYWORDS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 update__doc__},
Larry Hastings5c661892014-01-24 06:17:25 -08003203 DICT_FROMKEYS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
3205 clear__doc__},
3206 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
3207 copy__doc__},
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003208 DICT___REVERSED___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003210};
3211
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00003212/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00003213int
3214PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003215{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003216 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07003217 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09003219 PyObject *value;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003222 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 hash = PyObject_Hash(key);
3224 if (hash == -1)
3225 return -1;
3226 }
INADA Naoki778928b2017-08-03 23:45:15 +09003227 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07003228 if (ix == DKIX_ERROR)
3229 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09003230 return (ix != DKIX_EMPTY && value != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003231}
3232
Thomas Wouterscf297e42007-02-23 15:07:44 +00003233/* Internal version of PyDict_Contains used when the hash value is already known */
3234int
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003235_PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00003236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09003238 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -07003239 Py_ssize_t ix;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003240
INADA Naoki778928b2017-08-03 23:45:15 +09003241 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07003242 if (ix == DKIX_ERROR)
3243 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09003244 return (ix != DKIX_EMPTY && value != NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00003245}
3246
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003247/* Hack to implement "key in dict" */
3248static PySequenceMethods dict_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003249 0, /* sq_length */
3250 0, /* sq_concat */
3251 0, /* sq_repeat */
3252 0, /* sq_item */
3253 0, /* sq_slice */
3254 0, /* sq_ass_item */
3255 0, /* sq_ass_slice */
3256 PyDict_Contains, /* sq_contains */
3257 0, /* sq_inplace_concat */
3258 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003259};
3260
Guido van Rossum09e563a2001-05-01 12:10:21 +00003261static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003262dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 PyObject *self;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003265 PyDictObject *d;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 assert(type != NULL && type->tp_alloc != NULL);
3268 self = type->tp_alloc(type, 0);
Victor Stinnera9f61a52013-07-16 22:17:26 +02003269 if (self == NULL)
3270 return NULL;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003271 d = (PyDictObject *)self;
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003272
Victor Stinnera9f61a52013-07-16 22:17:26 +02003273 /* The object has been implicitly tracked by tp_alloc */
3274 if (type == &PyDict_Type)
3275 _PyObject_GC_UNTRACK(d);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003276
3277 d->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07003278 d->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07003279 d->ma_keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003280 if (d->ma_keys == NULL) {
3281 Py_DECREF(self);
3282 return NULL;
3283 }
Victor Stinner0fc91ee2019-04-12 21:51:34 +02003284 ASSERT_CONSISTENT(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 return self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003286}
3287
Tim Peters25786c02001-09-02 08:22:48 +00003288static int
3289dict_init(PyObject *self, PyObject *args, PyObject *kwds)
3290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00003292}
3293
Tim Peters6d6c1a32001-08-02 04:15:00 +00003294static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003295dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00003296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003298}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003299
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003300PyDoc_STRVAR(dictionary_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00003301"dict() -> new empty dictionary\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00003302"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003303" (key, value) pairs\n"
3304"dict(iterable) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00003305" d = {}\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003306" for k, v in iterable:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00003307" d[k] = v\n"
3308"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
3309" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00003310
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003311PyTypeObject PyDict_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3313 "dict",
3314 sizeof(PyDictObject),
3315 0,
3316 (destructor)dict_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003317 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 0, /* tp_getattr */
3319 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003320 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 (reprfunc)dict_repr, /* tp_repr */
3322 0, /* tp_as_number */
3323 &dict_as_sequence, /* tp_as_sequence */
3324 &dict_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003325 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 0, /* tp_call */
3327 0, /* tp_str */
3328 PyObject_GenericGetAttr, /* tp_getattro */
3329 0, /* tp_setattro */
3330 0, /* tp_as_buffer */
3331 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3332 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
3333 dictionary_doc, /* tp_doc */
3334 dict_traverse, /* tp_traverse */
3335 dict_tp_clear, /* tp_clear */
3336 dict_richcompare, /* tp_richcompare */
3337 0, /* tp_weaklistoffset */
3338 (getiterfunc)dict_iter, /* tp_iter */
3339 0, /* tp_iternext */
3340 mapp_methods, /* tp_methods */
3341 0, /* tp_members */
3342 0, /* tp_getset */
3343 0, /* tp_base */
3344 0, /* tp_dict */
3345 0, /* tp_descr_get */
3346 0, /* tp_descr_set */
3347 0, /* tp_dictoffset */
3348 dict_init, /* tp_init */
3349 PyType_GenericAlloc, /* tp_alloc */
3350 dict_new, /* tp_new */
3351 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003352};
3353
Victor Stinner3c1e4812012-03-26 22:10:51 +02003354PyObject *
3355_PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
3356{
3357 PyObject *kv;
3358 kv = _PyUnicode_FromId(key); /* borrowed */
Victor Stinner5b3b1002013-07-22 23:50:57 +02003359 if (kv == NULL) {
3360 PyErr_Clear();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003361 return NULL;
Victor Stinner5b3b1002013-07-22 23:50:57 +02003362 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003363 return PyDict_GetItem(dp, kv);
3364}
3365
Guido van Rossum3cca2451997-05-16 14:23:33 +00003366/* For backward compatibility with old dictionary interface */
3367
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003368PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003369PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 PyObject *kv, *rv;
3372 kv = PyUnicode_FromString(key);
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003373 if (kv == NULL) {
3374 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 return NULL;
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003376 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003377 rv = PyDict_GetItem(v, kv);
3378 Py_DECREF(kv);
3379 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003380}
3381
3382int
Victor Stinner3c1e4812012-03-26 22:10:51 +02003383_PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
3384{
3385 PyObject *kv;
3386 kv = _PyUnicode_FromId(key); /* borrowed */
3387 if (kv == NULL)
3388 return -1;
3389 return PyDict_SetItem(v, kv, item);
3390}
3391
3392int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003393PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 PyObject *kv;
3396 int err;
3397 kv = PyUnicode_FromString(key);
3398 if (kv == NULL)
3399 return -1;
3400 PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
3401 err = PyDict_SetItem(v, kv, item);
3402 Py_DECREF(kv);
3403 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003404}
3405
3406int
Victor Stinner5fd2e5a2013-11-06 18:58:22 +01003407_PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
3408{
3409 PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
3410 if (kv == NULL)
3411 return -1;
3412 return PyDict_DelItem(v, kv);
3413}
3414
3415int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003416PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 PyObject *kv;
3419 int err;
3420 kv = PyUnicode_FromString(key);
3421 if (kv == NULL)
3422 return -1;
3423 err = PyDict_DelItem(v, kv);
3424 Py_DECREF(kv);
3425 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003426}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003427
Raymond Hettinger019a1482004-03-18 02:41:19 +00003428/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003429
3430typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 PyObject_HEAD
3432 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
3433 Py_ssize_t di_used;
3434 Py_ssize_t di_pos;
3435 PyObject* di_result; /* reusable result tuple for iteritems */
3436 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003437} dictiterobject;
3438
3439static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003440dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 dictiterobject *di;
3443 di = PyObject_GC_New(dictiterobject, itertype);
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003444 if (di == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003445 return NULL;
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003446 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003447 Py_INCREF(dict);
3448 di->di_dict = dict;
3449 di->di_used = dict->ma_used;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 di->len = dict->ma_used;
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003451 if ((itertype == &PyDictRevIterKey_Type ||
3452 itertype == &PyDictRevIterItem_Type ||
3453 itertype == &PyDictRevIterValue_Type) && dict->ma_used) {
3454 di->di_pos = dict->ma_keys->dk_nentries - 1;
3455 }
3456 else {
3457 di->di_pos = 0;
3458 }
3459 if (itertype == &PyDictIterItem_Type ||
3460 itertype == &PyDictRevIterItem_Type) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
3462 if (di->di_result == NULL) {
3463 Py_DECREF(di);
3464 return NULL;
3465 }
3466 }
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003467 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 di->di_result = NULL;
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003469 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003470 _PyObject_GC_TRACK(di);
3471 return (PyObject *)di;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003472}
3473
3474static void
3475dictiter_dealloc(dictiterobject *di)
3476{
INADA Naokia6296d32017-08-24 14:55:17 +09003477 /* bpo-31095: UnTrack is needed before calling any callbacks */
3478 _PyObject_GC_UNTRACK(di);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 Py_XDECREF(di->di_dict);
3480 Py_XDECREF(di->di_result);
3481 PyObject_GC_Del(di);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003482}
3483
3484static int
3485dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
3486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 Py_VISIT(di->di_dict);
3488 Py_VISIT(di->di_result);
3489 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003490}
3491
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003492static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303493dictiter_len(dictiterobject *di, PyObject *Py_UNUSED(ignored))
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 Py_ssize_t len = 0;
3496 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
3497 len = di->len;
3498 return PyLong_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003499}
3500
Guido van Rossumb90c8482007-02-10 01:11:45 +00003501PyDoc_STRVAR(length_hint_doc,
3502 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003503
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003504static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303505dictiter_reduce(dictiterobject *di, PyObject *Py_UNUSED(ignored));
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003506
3507PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3508
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003509static PyMethodDef dictiter_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003510 {"__length_hint__", (PyCFunction)(void(*)(void))dictiter_len, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003511 length_hint_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003512 {"__reduce__", (PyCFunction)(void(*)(void))dictiter_reduce, METH_NOARGS,
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003513 reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003515};
3516
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003517static PyObject*
3518dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00003519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 PyObject *key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003521 Py_ssize_t i;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003522 PyDictKeysObject *k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 PyDictObject *d = di->di_dict;
Guido van Rossum213c7a62001-04-23 14:08:49 +00003524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 if (d == NULL)
3526 return NULL;
3527 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00003528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 if (di->di_used != d->ma_used) {
3530 PyErr_SetString(PyExc_RuntimeError,
3531 "dictionary changed size during iteration");
3532 di->di_used = -1; /* Make this state sticky */
3533 return NULL;
3534 }
Guido van Rossum2147df72002-07-16 20:30:22 +00003535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 i = di->di_pos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003537 k = d->ma_keys;
INADA Naokica2d8be2016-11-04 16:59:10 +09003538 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003539 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003540 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003541 goto fail;
3542 key = DK_ENTRIES(k)[i].me_key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003543 assert(d->ma_values[i] != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003544 }
3545 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003546 Py_ssize_t n = k->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003547 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
3548 while (i < n && entry_ptr->me_value == NULL) {
3549 entry_ptr++;
3550 i++;
3551 }
3552 if (i >= n)
3553 goto fail;
3554 key = entry_ptr->me_key;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003555 }
Thomas Perl796cc6e2019-03-28 07:03:25 +01003556 // We found an element (key), but did not expect it
3557 if (di->len == 0) {
3558 PyErr_SetString(PyExc_RuntimeError,
3559 "dictionary keys changed during iteration");
3560 goto fail;
3561 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 di->di_pos = i+1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 di->len--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 Py_INCREF(key);
3565 return key;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003566
3567fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003569 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003571}
3572
Raymond Hettinger019a1482004-03-18 02:41:19 +00003573PyTypeObject PyDictIterKey_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3575 "dict_keyiterator", /* tp_name */
3576 sizeof(dictiterobject), /* tp_basicsize */
3577 0, /* tp_itemsize */
3578 /* methods */
3579 (destructor)dictiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003580 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 0, /* tp_getattr */
3582 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003583 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 0, /* tp_repr */
3585 0, /* tp_as_number */
3586 0, /* tp_as_sequence */
3587 0, /* tp_as_mapping */
3588 0, /* tp_hash */
3589 0, /* tp_call */
3590 0, /* tp_str */
3591 PyObject_GenericGetAttr, /* tp_getattro */
3592 0, /* tp_setattro */
3593 0, /* tp_as_buffer */
3594 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3595 0, /* tp_doc */
3596 (traverseproc)dictiter_traverse, /* tp_traverse */
3597 0, /* tp_clear */
3598 0, /* tp_richcompare */
3599 0, /* tp_weaklistoffset */
3600 PyObject_SelfIter, /* tp_iter */
3601 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
3602 dictiter_methods, /* tp_methods */
3603 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003604};
3605
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003606static PyObject *
3607dictiter_iternextvalue(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 PyObject *value;
INADA Naokica2d8be2016-11-04 16:59:10 +09003610 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 if (d == NULL)
3614 return NULL;
3615 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 if (di->di_used != d->ma_used) {
3618 PyErr_SetString(PyExc_RuntimeError,
3619 "dictionary changed size during iteration");
3620 di->di_used = -1; /* Make this state sticky */
3621 return NULL;
3622 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 i = di->di_pos;
INADA Naokica2d8be2016-11-04 16:59:10 +09003625 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003626 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003627 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003628 goto fail;
INADA Naokica2d8be2016-11-04 16:59:10 +09003629 value = d->ma_values[i];
3630 assert(value != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003631 }
3632 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003633 Py_ssize_t n = d->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003634 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3635 while (i < n && entry_ptr->me_value == NULL) {
3636 entry_ptr++;
3637 i++;
3638 }
3639 if (i >= n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 goto fail;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003641 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642 }
Thomas Perlb8311cf2019-04-02 11:30:10 +02003643 // We found an element, but did not expect it
3644 if (di->len == 0) {
3645 PyErr_SetString(PyExc_RuntimeError,
3646 "dictionary keys changed during iteration");
3647 goto fail;
3648 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 di->di_pos = i+1;
3650 di->len--;
3651 Py_INCREF(value);
3652 return value;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003653
3654fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003656 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003658}
3659
3660PyTypeObject PyDictIterValue_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003661 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3662 "dict_valueiterator", /* tp_name */
3663 sizeof(dictiterobject), /* tp_basicsize */
3664 0, /* tp_itemsize */
3665 /* methods */
3666 (destructor)dictiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003667 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003668 0, /* tp_getattr */
3669 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003670 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 0, /* tp_repr */
3672 0, /* tp_as_number */
3673 0, /* tp_as_sequence */
3674 0, /* tp_as_mapping */
3675 0, /* tp_hash */
3676 0, /* tp_call */
3677 0, /* tp_str */
3678 PyObject_GenericGetAttr, /* tp_getattro */
3679 0, /* tp_setattro */
3680 0, /* tp_as_buffer */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003681 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 0, /* tp_doc */
3683 (traverseproc)dictiter_traverse, /* tp_traverse */
3684 0, /* tp_clear */
3685 0, /* tp_richcompare */
3686 0, /* tp_weaklistoffset */
3687 PyObject_SelfIter, /* tp_iter */
3688 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
3689 dictiter_methods, /* tp_methods */
3690 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003691};
3692
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003693static PyObject *
3694dictiter_iternextitem(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003695{
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003696 PyObject *key, *value, *result;
INADA Naokica2d8be2016-11-04 16:59:10 +09003697 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003698 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 if (d == NULL)
3701 return NULL;
3702 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003704 if (di->di_used != d->ma_used) {
3705 PyErr_SetString(PyExc_RuntimeError,
3706 "dictionary changed size during iteration");
3707 di->di_used = -1; /* Make this state sticky */
3708 return NULL;
3709 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003711 i = di->di_pos;
INADA Naokica2d8be2016-11-04 16:59:10 +09003712 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003713 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003714 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003715 goto fail;
3716 key = DK_ENTRIES(d->ma_keys)[i].me_key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003717 value = d->ma_values[i];
3718 assert(value != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003719 }
3720 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003721 Py_ssize_t n = d->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003722 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3723 while (i < n && entry_ptr->me_value == NULL) {
3724 entry_ptr++;
3725 i++;
3726 }
3727 if (i >= n)
3728 goto fail;
3729 key = entry_ptr->me_key;
3730 value = entry_ptr->me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003731 }
Thomas Perlb8311cf2019-04-02 11:30:10 +02003732 // We found an element, but did not expect it
3733 if (di->len == 0) {
3734 PyErr_SetString(PyExc_RuntimeError,
3735 "dictionary keys changed during iteration");
3736 goto fail;
3737 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 di->di_pos = i+1;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003739 di->len--;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003740 Py_INCREF(key);
3741 Py_INCREF(value);
3742 result = di->di_result;
3743 if (Py_REFCNT(result) == 1) {
3744 PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
3745 PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
3746 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3747 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 Py_INCREF(result);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003749 Py_DECREF(oldkey);
3750 Py_DECREF(oldvalue);
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003751 }
3752 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003753 result = PyTuple_New(2);
3754 if (result == NULL)
3755 return NULL;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003756 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 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003759 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003760
3761fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003763 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003765}
3766
3767PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3769 "dict_itemiterator", /* tp_name */
3770 sizeof(dictiterobject), /* tp_basicsize */
3771 0, /* tp_itemsize */
3772 /* methods */
3773 (destructor)dictiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003774 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 0, /* tp_getattr */
3776 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003777 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 0, /* tp_repr */
3779 0, /* tp_as_number */
3780 0, /* tp_as_sequence */
3781 0, /* tp_as_mapping */
3782 0, /* tp_hash */
3783 0, /* tp_call */
3784 0, /* tp_str */
3785 PyObject_GenericGetAttr, /* tp_getattro */
3786 0, /* tp_setattro */
3787 0, /* tp_as_buffer */
3788 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3789 0, /* tp_doc */
3790 (traverseproc)dictiter_traverse, /* tp_traverse */
3791 0, /* tp_clear */
3792 0, /* tp_richcompare */
3793 0, /* tp_weaklistoffset */
3794 PyObject_SelfIter, /* tp_iter */
3795 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
3796 dictiter_methods, /* tp_methods */
3797 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003798};
Guido van Rossumb90c8482007-02-10 01:11:45 +00003799
3800
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003801/* dictreviter */
3802
3803static PyObject *
3804dictreviter_iternext(dictiterobject *di)
3805{
3806 PyDictObject *d = di->di_dict;
3807
3808 if (d == NULL) {
3809 return NULL;
3810 }
3811 assert (PyDict_Check(d));
3812
3813 if (di->di_used != d->ma_used) {
3814 PyErr_SetString(PyExc_RuntimeError,
3815 "dictionary changed size during iteration");
3816 di->di_used = -1; /* Make this state sticky */
3817 return NULL;
3818 }
3819
3820 Py_ssize_t i = di->di_pos;
3821 PyDictKeysObject *k = d->ma_keys;
3822 PyObject *key, *value, *result;
3823
3824 if (d->ma_values) {
3825 if (i < 0) {
3826 goto fail;
3827 }
3828 key = DK_ENTRIES(k)[i].me_key;
3829 value = d->ma_values[i];
3830 assert (value != NULL);
3831 }
3832 else {
3833 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
3834 while (i >= 0 && entry_ptr->me_value == NULL) {
3835 entry_ptr--;
3836 i--;
3837 }
3838 if (i < 0) {
3839 goto fail;
3840 }
3841 key = entry_ptr->me_key;
3842 value = entry_ptr->me_value;
3843 }
3844 di->di_pos = i-1;
3845 di->len--;
3846
3847 if (Py_TYPE(di) == &PyDictRevIterKey_Type) {
3848 Py_INCREF(key);
3849 return key;
3850 }
3851 else if (Py_TYPE(di) == &PyDictRevIterValue_Type) {
3852 Py_INCREF(value);
3853 return value;
3854 }
3855 else if (Py_TYPE(di) == &PyDictRevIterItem_Type) {
3856 Py_INCREF(key);
3857 Py_INCREF(value);
3858 result = di->di_result;
3859 if (Py_REFCNT(result) == 1) {
3860 PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
3861 PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
3862 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3863 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
3864 Py_INCREF(result);
3865 Py_DECREF(oldkey);
3866 Py_DECREF(oldvalue);
3867 }
3868 else {
3869 result = PyTuple_New(2);
3870 if (result == NULL) {
3871 return NULL;
3872 }
3873 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3874 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
3875 }
3876 return result;
3877 }
3878 else {
3879 Py_UNREACHABLE();
3880 }
3881
3882fail:
3883 di->di_dict = NULL;
3884 Py_DECREF(d);
3885 return NULL;
3886}
3887
3888PyTypeObject PyDictRevIterKey_Type = {
3889 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3890 "dict_reversekeyiterator",
3891 sizeof(dictiterobject),
3892 .tp_dealloc = (destructor)dictiter_dealloc,
3893 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3894 .tp_traverse = (traverseproc)dictiter_traverse,
3895 .tp_iter = PyObject_SelfIter,
3896 .tp_iternext = (iternextfunc)dictreviter_iternext,
3897 .tp_methods = dictiter_methods
3898};
3899
3900
3901/*[clinic input]
3902dict.__reversed__
3903
3904Return a reverse iterator over the dict keys.
3905[clinic start generated code]*/
3906
3907static PyObject *
3908dict___reversed___impl(PyDictObject *self)
3909/*[clinic end generated code: output=e674483336d1ed51 input=23210ef3477d8c4d]*/
3910{
3911 assert (PyDict_Check(self));
3912 return dictiter_new(self, &PyDictRevIterKey_Type);
3913}
3914
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003915static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303916dictiter_reduce(dictiterobject *di, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003917{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003918 _Py_IDENTIFIER(iter);
Sergey Fedoseev63958442018-10-20 05:43:33 +05003919 /* copy the iterator state */
3920 dictiterobject tmp = *di;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003921 Py_XINCREF(tmp.di_dict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003922
Sergey Fedoseev63958442018-10-20 05:43:33 +05003923 PyObject *list = PySequence_List((PyObject*)&tmp);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003924 Py_XDECREF(tmp.di_dict);
Sergey Fedoseev63958442018-10-20 05:43:33 +05003925 if (list == NULL) {
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003926 return NULL;
3927 }
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003928 return Py_BuildValue("N(N)", _PyEval_GetBuiltinId(&PyId_iter), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003929}
3930
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003931PyTypeObject PyDictRevIterItem_Type = {
3932 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3933 "dict_reverseitemiterator",
3934 sizeof(dictiterobject),
3935 .tp_dealloc = (destructor)dictiter_dealloc,
3936 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3937 .tp_traverse = (traverseproc)dictiter_traverse,
3938 .tp_iter = PyObject_SelfIter,
3939 .tp_iternext = (iternextfunc)dictreviter_iternext,
3940 .tp_methods = dictiter_methods
3941};
3942
3943PyTypeObject PyDictRevIterValue_Type = {
3944 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3945 "dict_reversevalueiterator",
3946 sizeof(dictiterobject),
3947 .tp_dealloc = (destructor)dictiter_dealloc,
3948 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3949 .tp_traverse = (traverseproc)dictiter_traverse,
3950 .tp_iter = PyObject_SelfIter,
3951 .tp_iternext = (iternextfunc)dictreviter_iternext,
3952 .tp_methods = dictiter_methods
3953};
3954
Guido van Rossum3ac67412007-02-10 18:55:06 +00003955/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003956/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00003957/***********************************************/
3958
Guido van Rossumb90c8482007-02-10 01:11:45 +00003959/* The instance lay-out is the same for all three; but the type differs. */
3960
Guido van Rossumb90c8482007-02-10 01:11:45 +00003961static void
Eric Snow96c6af92015-05-29 22:21:39 -06003962dictview_dealloc(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003963{
INADA Naokia6296d32017-08-24 14:55:17 +09003964 /* bpo-31095: UnTrack is needed before calling any callbacks */
3965 _PyObject_GC_UNTRACK(dv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003966 Py_XDECREF(dv->dv_dict);
3967 PyObject_GC_Del(dv);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003968}
3969
3970static int
Eric Snow96c6af92015-05-29 22:21:39 -06003971dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 Py_VISIT(dv->dv_dict);
3974 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003975}
3976
Guido van Rossum83825ac2007-02-10 04:54:19 +00003977static Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003978dictview_len(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003980 Py_ssize_t len = 0;
3981 if (dv->dv_dict != NULL)
3982 len = dv->dv_dict->ma_used;
3983 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003984}
3985
Eric Snow96c6af92015-05-29 22:21:39 -06003986PyObject *
3987_PyDictView_New(PyObject *dict, PyTypeObject *type)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003988{
Eric Snow96c6af92015-05-29 22:21:39 -06003989 _PyDictViewObject *dv;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003990 if (dict == NULL) {
3991 PyErr_BadInternalCall();
3992 return NULL;
3993 }
3994 if (!PyDict_Check(dict)) {
3995 /* XXX Get rid of this restriction later */
3996 PyErr_Format(PyExc_TypeError,
3997 "%s() requires a dict argument, not '%s'",
3998 type->tp_name, dict->ob_type->tp_name);
3999 return NULL;
4000 }
Eric Snow96c6af92015-05-29 22:21:39 -06004001 dv = PyObject_GC_New(_PyDictViewObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004002 if (dv == NULL)
4003 return NULL;
4004 Py_INCREF(dict);
4005 dv->dv_dict = (PyDictObject *)dict;
4006 _PyObject_GC_TRACK(dv);
4007 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00004008}
4009
Neal Norwitze36f2ba2007-02-26 23:12:28 +00004010/* TODO(guido): The views objects are not complete:
4011
4012 * support more set operations
4013 * support arbitrary mappings?
4014 - either these should be static or exported in dictobject.h
4015 - if public then they should probably be in builtins
4016*/
4017
Guido van Rossumaac530c2007-08-24 22:33:45 +00004018/* Return 1 if self is a subset of other, iterating over self;
4019 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00004020static int
4021all_contained_in(PyObject *self, PyObject *other)
4022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 PyObject *iter = PyObject_GetIter(self);
4024 int ok = 1;
Guido van Rossumd9214d12007-02-12 02:23:40 +00004025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004026 if (iter == NULL)
4027 return -1;
4028 for (;;) {
4029 PyObject *next = PyIter_Next(iter);
4030 if (next == NULL) {
4031 if (PyErr_Occurred())
4032 ok = -1;
4033 break;
4034 }
4035 ok = PySequence_Contains(other, next);
4036 Py_DECREF(next);
4037 if (ok <= 0)
4038 break;
4039 }
4040 Py_DECREF(iter);
4041 return ok;
Guido van Rossumd9214d12007-02-12 02:23:40 +00004042}
4043
4044static PyObject *
4045dictview_richcompare(PyObject *self, PyObject *other, int op)
4046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004047 Py_ssize_t len_self, len_other;
4048 int ok;
4049 PyObject *result;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 assert(self != NULL);
4052 assert(PyDictViewSet_Check(self));
4053 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00004054
Brian Curtindfc80e32011-08-10 20:28:54 -05004055 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
4056 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004058 len_self = PyObject_Size(self);
4059 if (len_self < 0)
4060 return NULL;
4061 len_other = PyObject_Size(other);
4062 if (len_other < 0)
4063 return NULL;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 ok = 0;
4066 switch(op) {
Guido van Rossumaac530c2007-08-24 22:33:45 +00004067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 case Py_NE:
4069 case Py_EQ:
4070 if (len_self == len_other)
4071 ok = all_contained_in(self, other);
4072 if (op == Py_NE && ok >= 0)
4073 ok = !ok;
4074 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004076 case Py_LT:
4077 if (len_self < len_other)
4078 ok = all_contained_in(self, other);
4079 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004081 case Py_LE:
4082 if (len_self <= len_other)
4083 ok = all_contained_in(self, other);
4084 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 case Py_GT:
4087 if (len_self > len_other)
4088 ok = all_contained_in(other, self);
4089 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004091 case Py_GE:
4092 if (len_self >= len_other)
4093 ok = all_contained_in(other, self);
4094 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00004095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 }
4097 if (ok < 0)
4098 return NULL;
4099 result = ok ? Py_True : Py_False;
4100 Py_INCREF(result);
4101 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00004102}
4103
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00004104static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004105dictview_repr(_PyDictViewObject *dv)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00004106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 PyObject *seq;
bennorthd7773d92018-01-26 15:46:01 +00004108 PyObject *result = NULL;
4109 Py_ssize_t rc;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00004110
bennorthd7773d92018-01-26 15:46:01 +00004111 rc = Py_ReprEnter((PyObject *)dv);
4112 if (rc != 0) {
4113 return rc > 0 ? PyUnicode_FromString("...") : NULL;
4114 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004115 seq = PySequence_List((PyObject *)dv);
bennorthd7773d92018-01-26 15:46:01 +00004116 if (seq == NULL) {
4117 goto Done;
4118 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
4120 Py_DECREF(seq);
bennorthd7773d92018-01-26 15:46:01 +00004121
4122Done:
4123 Py_ReprLeave((PyObject *)dv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 return result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00004125}
4126
Guido van Rossum3ac67412007-02-10 18:55:06 +00004127/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004128
4129static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004130dictkeys_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 if (dv->dv_dict == NULL) {
4133 Py_RETURN_NONE;
4134 }
4135 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00004136}
4137
4138static int
Eric Snow96c6af92015-05-29 22:21:39 -06004139dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00004140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 if (dv->dv_dict == NULL)
4142 return 0;
4143 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004144}
4145
Guido van Rossum83825ac2007-02-10 04:54:19 +00004146static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004147 (lenfunc)dictview_len, /* sq_length */
4148 0, /* sq_concat */
4149 0, /* sq_repeat */
4150 0, /* sq_item */
4151 0, /* sq_slice */
4152 0, /* sq_ass_item */
4153 0, /* sq_ass_slice */
4154 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004155};
4156
Guido van Rossum523259b2007-08-24 23:41:22 +00004157static PyObject*
4158dictviews_sub(PyObject* self, PyObject *other)
4159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004160 PyObject *result = PySet_New(self);
4161 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004162 _Py_IDENTIFIER(difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 if (result == NULL)
4165 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004166
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02004167 tmp = _PyObject_CallMethodIdOneArg(result, &PyId_difference_update, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004168 if (tmp == NULL) {
4169 Py_DECREF(result);
4170 return NULL;
4171 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004173 Py_DECREF(tmp);
4174 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004175}
4176
Forest Gregg998cf1f2019-08-26 02:17:43 -05004177static int
4178dictitems_contains(_PyDictViewObject *dv, PyObject *obj);
4179
4180PyObject *
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004181_PyDictView_Intersect(PyObject* self, PyObject *other)
Guido van Rossum523259b2007-08-24 23:41:22 +00004182{
Forest Gregg998cf1f2019-08-26 02:17:43 -05004183 PyObject *result;
4184 PyObject *it;
4185 PyObject *key;
4186 Py_ssize_t len_self;
4187 int rv;
4188 int (*dict_contains)(_PyDictViewObject *, PyObject *);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004189
Forest Gregg998cf1f2019-08-26 02:17:43 -05004190 /* Python interpreter swaps parameters when dict view
4191 is on right side of & */
4192 if (!PyDictViewSet_Check(self)) {
4193 PyObject *tmp = other;
4194 other = self;
4195 self = tmp;
4196 }
4197
4198 len_self = dictview_len((_PyDictViewObject *)self);
4199
4200 /* if other is a set and self is smaller than other,
4201 reuse set intersection logic */
4202 if (Py_TYPE(other) == &PySet_Type && len_self <= PyObject_Size(other)) {
4203 _Py_IDENTIFIER(intersection);
4204 return _PyObject_CallMethodIdObjArgs(other, &PyId_intersection, self, NULL);
4205 }
4206
4207 /* if other is another dict view, and it is bigger than self,
4208 swap them */
4209 if (PyDictViewSet_Check(other)) {
4210 Py_ssize_t len_other = dictview_len((_PyDictViewObject *)other);
4211 if (len_other > len_self) {
4212 PyObject *tmp = other;
4213 other = self;
4214 self = tmp;
4215 }
4216 }
4217
4218 /* at this point, two things should be true
4219 1. self is a dictview
4220 2. if other is a dictview then it is smaller than self */
4221 result = PySet_New(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 if (result == NULL)
4223 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004224
Forest Gregg998cf1f2019-08-26 02:17:43 -05004225 it = PyObject_GetIter(other);
4226
Forest Gregg998cf1f2019-08-26 02:17:43 -05004227 if (PyDictKeys_Check(self)) {
4228 dict_contains = dictkeys_contains;
4229 }
4230 /* else PyDictItems_Check(self) */
4231 else {
4232 dict_contains = dictitems_contains;
4233 }
4234
4235 while ((key = PyIter_Next(it)) != NULL) {
4236 rv = dict_contains((_PyDictViewObject *)self, key);
4237 if (rv < 0) {
4238 goto error;
4239 }
4240 if (rv) {
4241 if (PySet_Add(result, key)) {
4242 goto error;
4243 }
4244 }
4245 Py_DECREF(key);
4246 }
4247 Py_DECREF(it);
4248 if (PyErr_Occurred()) {
4249 Py_DECREF(result);
4250 return NULL;
4251 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004252 return result;
Forest Gregg998cf1f2019-08-26 02:17:43 -05004253
4254error:
4255 Py_DECREF(it);
4256 Py_DECREF(result);
4257 Py_DECREF(key);
4258 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004259}
4260
4261static PyObject*
4262dictviews_or(PyObject* self, PyObject *other)
4263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004264 PyObject *result = PySet_New(self);
4265 PyObject *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02004266 _Py_IDENTIFIER(update);
Victor Stinnerd1a9cc22011-10-13 22:51:17 +02004267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268 if (result == NULL)
4269 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004270
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02004271 tmp = _PyObject_CallMethodIdOneArg(result, &PyId_update, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004272 if (tmp == NULL) {
4273 Py_DECREF(result);
4274 return NULL;
4275 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 Py_DECREF(tmp);
4278 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004279}
4280
4281static PyObject*
4282dictviews_xor(PyObject* self, PyObject *other)
4283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004284 PyObject *result = PySet_New(self);
4285 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004286 _Py_IDENTIFIER(symmetric_difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288 if (result == NULL)
4289 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004290
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02004291 tmp = _PyObject_CallMethodIdOneArg(result, &PyId_symmetric_difference_update, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004292 if (tmp == NULL) {
4293 Py_DECREF(result);
4294 return NULL;
4295 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 Py_DECREF(tmp);
4298 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004299}
4300
4301static PyNumberMethods dictviews_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004302 0, /*nb_add*/
4303 (binaryfunc)dictviews_sub, /*nb_subtract*/
4304 0, /*nb_multiply*/
4305 0, /*nb_remainder*/
4306 0, /*nb_divmod*/
4307 0, /*nb_power*/
4308 0, /*nb_negative*/
4309 0, /*nb_positive*/
4310 0, /*nb_absolute*/
4311 0, /*nb_bool*/
4312 0, /*nb_invert*/
4313 0, /*nb_lshift*/
4314 0, /*nb_rshift*/
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004315 (binaryfunc)_PyDictView_Intersect, /*nb_and*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004316 (binaryfunc)dictviews_xor, /*nb_xor*/
4317 (binaryfunc)dictviews_or, /*nb_or*/
Guido van Rossum523259b2007-08-24 23:41:22 +00004318};
4319
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004320static PyObject*
4321dictviews_isdisjoint(PyObject *self, PyObject *other)
4322{
4323 PyObject *it;
4324 PyObject *item = NULL;
4325
4326 if (self == other) {
Eric Snow96c6af92015-05-29 22:21:39 -06004327 if (dictview_len((_PyDictViewObject *)self) == 0)
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004328 Py_RETURN_TRUE;
4329 else
4330 Py_RETURN_FALSE;
4331 }
4332
4333 /* Iterate over the shorter object (only if other is a set,
4334 * because PySequence_Contains may be expensive otherwise): */
4335 if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
Eric Snow96c6af92015-05-29 22:21:39 -06004336 Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004337 Py_ssize_t len_other = PyObject_Size(other);
4338 if (len_other == -1)
4339 return NULL;
4340
4341 if ((len_other > len_self)) {
4342 PyObject *tmp = other;
4343 other = self;
4344 self = tmp;
4345 }
4346 }
4347
4348 it = PyObject_GetIter(other);
4349 if (it == NULL)
4350 return NULL;
4351
4352 while ((item = PyIter_Next(it)) != NULL) {
4353 int contains = PySequence_Contains(self, item);
4354 Py_DECREF(item);
4355 if (contains == -1) {
4356 Py_DECREF(it);
4357 return NULL;
4358 }
4359
4360 if (contains) {
4361 Py_DECREF(it);
4362 Py_RETURN_FALSE;
4363 }
4364 }
4365 Py_DECREF(it);
4366 if (PyErr_Occurred())
4367 return NULL; /* PyIter_Next raised an exception. */
4368 Py_RETURN_TRUE;
4369}
4370
4371PyDoc_STRVAR(isdisjoint_doc,
4372"Return True if the view and the given iterable have a null intersection.");
4373
Serhiy Storchaka81524022018-11-27 13:05:02 +02004374static PyObject* dictkeys_reversed(_PyDictViewObject *dv, PyObject *Py_UNUSED(ignored));
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004375
4376PyDoc_STRVAR(reversed_keys_doc,
4377"Return a reverse iterator over the dict keys.");
4378
Guido van Rossumb90c8482007-02-10 01:11:45 +00004379static PyMethodDef dictkeys_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004380 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4381 isdisjoint_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02004382 {"__reversed__", (PyCFunction)(void(*)(void))dictkeys_reversed, METH_NOARGS,
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004383 reversed_keys_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004385};
4386
4387PyTypeObject PyDictKeys_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004388 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4389 "dict_keys", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004390 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 0, /* tp_itemsize */
4392 /* methods */
4393 (destructor)dictview_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004394 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004395 0, /* tp_getattr */
4396 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004397 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004398 (reprfunc)dictview_repr, /* tp_repr */
4399 &dictviews_as_number, /* tp_as_number */
4400 &dictkeys_as_sequence, /* tp_as_sequence */
4401 0, /* tp_as_mapping */
4402 0, /* tp_hash */
4403 0, /* tp_call */
4404 0, /* tp_str */
4405 PyObject_GenericGetAttr, /* tp_getattro */
4406 0, /* tp_setattro */
4407 0, /* tp_as_buffer */
4408 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4409 0, /* tp_doc */
4410 (traverseproc)dictview_traverse, /* tp_traverse */
4411 0, /* tp_clear */
4412 dictview_richcompare, /* tp_richcompare */
4413 0, /* tp_weaklistoffset */
4414 (getiterfunc)dictkeys_iter, /* tp_iter */
4415 0, /* tp_iternext */
4416 dictkeys_methods, /* tp_methods */
4417 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004418};
4419
4420static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304421dictkeys_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004422{
Eric Snow96c6af92015-05-29 22:21:39 -06004423 return _PyDictView_New(dict, &PyDictKeys_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004424}
4425
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004426static PyObject *
Serhiy Storchaka81524022018-11-27 13:05:02 +02004427dictkeys_reversed(_PyDictViewObject *dv, PyObject *Py_UNUSED(ignored))
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004428{
4429 if (dv->dv_dict == NULL) {
4430 Py_RETURN_NONE;
4431 }
4432 return dictiter_new(dv->dv_dict, &PyDictRevIterKey_Type);
4433}
4434
Guido van Rossum3ac67412007-02-10 18:55:06 +00004435/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004436
4437static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004438dictitems_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 if (dv->dv_dict == NULL) {
4441 Py_RETURN_NONE;
4442 }
4443 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00004444}
4445
4446static int
Eric Snow96c6af92015-05-29 22:21:39 -06004447dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00004448{
Serhiy Storchaka753bca32017-05-20 12:30:02 +03004449 int result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 PyObject *key, *value, *found;
4451 if (dv->dv_dict == NULL)
4452 return 0;
4453 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
4454 return 0;
4455 key = PyTuple_GET_ITEM(obj, 0);
4456 value = PyTuple_GET_ITEM(obj, 1);
Raymond Hettinger6692f012016-09-18 21:46:08 -07004457 found = PyDict_GetItemWithError((PyObject *)dv->dv_dict, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004458 if (found == NULL) {
4459 if (PyErr_Occurred())
4460 return -1;
4461 return 0;
4462 }
Serhiy Storchaka753bca32017-05-20 12:30:02 +03004463 Py_INCREF(found);
Serhiy Storchaka18b711c2019-08-04 14:12:48 +03004464 result = PyObject_RichCompareBool(found, value, Py_EQ);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03004465 Py_DECREF(found);
4466 return result;
Guido van Rossumb90c8482007-02-10 01:11:45 +00004467}
4468
Guido van Rossum83825ac2007-02-10 04:54:19 +00004469static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004470 (lenfunc)dictview_len, /* sq_length */
4471 0, /* sq_concat */
4472 0, /* sq_repeat */
4473 0, /* sq_item */
4474 0, /* sq_slice */
4475 0, /* sq_ass_item */
4476 0, /* sq_ass_slice */
4477 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004478};
4479
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004480static PyObject* dictitems_reversed(_PyDictViewObject *dv);
4481
4482PyDoc_STRVAR(reversed_items_doc,
4483"Return a reverse iterator over the dict items.");
4484
Guido van Rossumb90c8482007-02-10 01:11:45 +00004485static PyMethodDef dictitems_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004486 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4487 isdisjoint_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02004488 {"__reversed__", (PyCFunction)(void(*)(void))dictitems_reversed, METH_NOARGS,
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004489 reversed_items_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004491};
4492
4493PyTypeObject PyDictItems_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004494 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4495 "dict_items", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004496 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004497 0, /* tp_itemsize */
4498 /* methods */
4499 (destructor)dictview_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004500 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004501 0, /* tp_getattr */
4502 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004503 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 (reprfunc)dictview_repr, /* tp_repr */
4505 &dictviews_as_number, /* tp_as_number */
4506 &dictitems_as_sequence, /* tp_as_sequence */
4507 0, /* tp_as_mapping */
4508 0, /* tp_hash */
4509 0, /* tp_call */
4510 0, /* tp_str */
4511 PyObject_GenericGetAttr, /* tp_getattro */
4512 0, /* tp_setattro */
4513 0, /* tp_as_buffer */
4514 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4515 0, /* tp_doc */
4516 (traverseproc)dictview_traverse, /* tp_traverse */
4517 0, /* tp_clear */
4518 dictview_richcompare, /* tp_richcompare */
4519 0, /* tp_weaklistoffset */
4520 (getiterfunc)dictitems_iter, /* tp_iter */
4521 0, /* tp_iternext */
4522 dictitems_methods, /* tp_methods */
4523 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004524};
4525
4526static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304527dictitems_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004528{
Eric Snow96c6af92015-05-29 22:21:39 -06004529 return _PyDictView_New(dict, &PyDictItems_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004530}
4531
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004532static PyObject *
4533dictitems_reversed(_PyDictViewObject *dv)
4534{
4535 if (dv->dv_dict == NULL) {
4536 Py_RETURN_NONE;
4537 }
4538 return dictiter_new(dv->dv_dict, &PyDictRevIterItem_Type);
4539}
4540
Guido van Rossum3ac67412007-02-10 18:55:06 +00004541/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004542
4543static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004544dictvalues_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004546 if (dv->dv_dict == NULL) {
4547 Py_RETURN_NONE;
4548 }
4549 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004550}
4551
Guido van Rossum83825ac2007-02-10 04:54:19 +00004552static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004553 (lenfunc)dictview_len, /* sq_length */
4554 0, /* sq_concat */
4555 0, /* sq_repeat */
4556 0, /* sq_item */
4557 0, /* sq_slice */
4558 0, /* sq_ass_item */
4559 0, /* sq_ass_slice */
4560 (objobjproc)0, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004561};
4562
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004563static PyObject* dictvalues_reversed(_PyDictViewObject *dv);
4564
4565PyDoc_STRVAR(reversed_values_doc,
4566"Return a reverse iterator over the dict values.");
4567
Guido van Rossumb90c8482007-02-10 01:11:45 +00004568static PyMethodDef dictvalues_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02004569 {"__reversed__", (PyCFunction)(void(*)(void))dictvalues_reversed, METH_NOARGS,
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004570 reversed_values_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004571 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004572};
4573
4574PyTypeObject PyDictValues_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004575 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4576 "dict_values", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004577 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 0, /* tp_itemsize */
4579 /* methods */
4580 (destructor)dictview_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004581 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004582 0, /* tp_getattr */
4583 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004584 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 (reprfunc)dictview_repr, /* tp_repr */
4586 0, /* tp_as_number */
4587 &dictvalues_as_sequence, /* tp_as_sequence */
4588 0, /* tp_as_mapping */
4589 0, /* tp_hash */
4590 0, /* tp_call */
4591 0, /* tp_str */
4592 PyObject_GenericGetAttr, /* tp_getattro */
4593 0, /* tp_setattro */
4594 0, /* tp_as_buffer */
4595 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4596 0, /* tp_doc */
4597 (traverseproc)dictview_traverse, /* tp_traverse */
4598 0, /* tp_clear */
4599 0, /* tp_richcompare */
4600 0, /* tp_weaklistoffset */
4601 (getiterfunc)dictvalues_iter, /* tp_iter */
4602 0, /* tp_iternext */
4603 dictvalues_methods, /* tp_methods */
4604 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004605};
4606
4607static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304608dictvalues_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004609{
Eric Snow96c6af92015-05-29 22:21:39 -06004610 return _PyDictView_New(dict, &PyDictValues_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004611}
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004612
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004613static PyObject *
4614dictvalues_reversed(_PyDictViewObject *dv)
4615{
4616 if (dv->dv_dict == NULL) {
4617 Py_RETURN_NONE;
4618 }
4619 return dictiter_new(dv->dv_dict, &PyDictRevIterValue_Type);
4620}
4621
4622
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004623/* Returns NULL if cannot allocate a new PyDictKeysObject,
4624 but does not set an error */
4625PyDictKeysObject *
4626_PyDict_NewKeysForClass(void)
4627{
Victor Stinner742da042016-09-07 17:40:12 -07004628 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004629 if (keys == NULL)
4630 PyErr_Clear();
4631 else
4632 keys->dk_lookup = lookdict_split;
4633 return keys;
4634}
4635
4636#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
4637
4638PyObject *
4639PyObject_GenericGetDict(PyObject *obj, void *context)
4640{
4641 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
4642 if (dictptr == NULL) {
4643 PyErr_SetString(PyExc_AttributeError,
4644 "This object has no __dict__");
4645 return NULL;
4646 }
4647 dict = *dictptr;
4648 if (dict == NULL) {
4649 PyTypeObject *tp = Py_TYPE(obj);
4650 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
INADA Naokia7576492018-11-14 18:39:27 +09004651 dictkeys_incref(CACHED_KEYS(tp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004652 *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
4653 }
4654 else {
4655 *dictptr = dict = PyDict_New();
4656 }
4657 }
4658 Py_XINCREF(dict);
4659 return dict;
4660}
4661
4662int
4663_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
Victor Stinner742da042016-09-07 17:40:12 -07004664 PyObject *key, PyObject *value)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004665{
4666 PyObject *dict;
4667 int res;
4668 PyDictKeysObject *cached;
4669
4670 assert(dictptr != NULL);
4671 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
4672 assert(dictptr != NULL);
4673 dict = *dictptr;
4674 if (dict == NULL) {
INADA Naokia7576492018-11-14 18:39:27 +09004675 dictkeys_incref(cached);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004676 dict = new_dict_with_shared_keys(cached);
4677 if (dict == NULL)
4678 return -1;
4679 *dictptr = dict;
4680 }
4681 if (value == NULL) {
4682 res = PyDict_DelItem(dict, key);
INADA Naoki2294f3a2017-02-12 13:51:30 +09004683 // Since key sharing dict doesn't allow deletion, PyDict_DelItem()
4684 // always converts dict to combined form.
4685 if ((cached = CACHED_KEYS(tp)) != NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004686 CACHED_KEYS(tp) = NULL;
INADA Naokia7576492018-11-14 18:39:27 +09004687 dictkeys_decref(cached);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004688 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01004689 }
4690 else {
INADA Naoki2294f3a2017-02-12 13:51:30 +09004691 int was_shared = (cached == ((PyDictObject *)dict)->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004692 res = PyDict_SetItem(dict, key, value);
INADA Naoki2294f3a2017-02-12 13:51:30 +09004693 if (was_shared &&
4694 (cached = CACHED_KEYS(tp)) != NULL &&
4695 cached != ((PyDictObject *)dict)->ma_keys) {
Victor Stinner3d3f2642016-12-15 17:21:23 +01004696 /* PyDict_SetItem() may call dictresize and convert split table
4697 * into combined table. In such case, convert it to split
4698 * table again and update type's shared key only when this is
4699 * the only dict sharing key with the type.
4700 *
4701 * This is to allow using shared key in class like this:
4702 *
4703 * class C:
4704 * def __init__(self):
4705 * # one dict resize happens
4706 * self.a, self.b, self.c = 1, 2, 3
4707 * self.d, self.e, self.f = 4, 5, 6
4708 * a = C()
4709 */
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004710 if (cached->dk_refcnt == 1) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004711 CACHED_KEYS(tp) = make_keys_shared(dict);
Victor Stinner742da042016-09-07 17:40:12 -07004712 }
4713 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004714 CACHED_KEYS(tp) = NULL;
4715 }
INADA Naokia7576492018-11-14 18:39:27 +09004716 dictkeys_decref(cached);
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004717 if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
4718 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004719 }
4720 }
4721 } else {
4722 dict = *dictptr;
4723 if (dict == NULL) {
4724 dict = PyDict_New();
4725 if (dict == NULL)
4726 return -1;
4727 *dictptr = dict;
4728 }
4729 if (value == NULL) {
4730 res = PyDict_DelItem(dict, key);
4731 } else {
4732 res = PyDict_SetItem(dict, key, value);
4733 }
4734 }
4735 return res;
4736}
4737
4738void
4739_PyDictKeys_DecRef(PyDictKeysObject *keys)
4740{
INADA Naokia7576492018-11-14 18:39:27 +09004741 dictkeys_decref(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004742}