blob: 413557d6674127ab80c98877ad2854a4f9a47e41 [file] [log] [blame]
Guido van Rossum2bc13791999-03-24 19:06:42 +00001/* Dictionary object implementation using a hash table */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002
Raymond Hettinger930427b2003-05-03 06:51:59 +00003/* The distribution includes a separate file, Objects/dictnotes.txt,
Tim Peters60b29962006-01-01 01:19:23 +00004 describing explorations into dictionary design and optimization.
Raymond Hettinger930427b2003-05-03 06:51:59 +00005 It covers typical dictionary use patterns, the parameters for
6 tuning dictionaries, and several ideas for possible optimizations.
7*/
8
Victor Stinner742da042016-09-07 17:40:12 -07009/* PyDictKeysObject
10
11This implements the dictionary's hashtable.
12
Raymond Hettingerb12785d2016-10-22 09:58:14 -070013As of Python 3.6, this is compact and ordered. Basic idea is described here:
14* https://mail.python.org/pipermail/python-dev/2012-December/123028.html
15* https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html
Victor Stinner742da042016-09-07 17:40:12 -070016
17layout:
18
19+---------------+
20| dk_refcnt |
21| dk_size |
22| dk_lookup |
23| dk_usable |
24| dk_nentries |
25+---------------+
26| dk_indices |
27| |
28+---------------+
29| dk_entries |
30| |
31+---------------+
32
33dk_indices is actual hashtable. It holds index in entries, or DKIX_EMPTY(-1)
34or DKIX_DUMMY(-2).
35Size of indices is dk_size. Type of each index in indices is vary on dk_size:
36
37* int8 for dk_size <= 128
38* int16 for 256 <= dk_size <= 2**15
39* int32 for 2**16 <= dk_size <= 2**31
40* int64 for 2**32 <= dk_size
41
42dk_entries is array of PyDictKeyEntry. It's size is USABLE_FRACTION(dk_size).
43DK_ENTRIES(dk) can be used to get pointer to entries.
44
45NOTE: Since negative value is used for DKIX_EMPTY and DKIX_DUMMY, type of
46dk_indices entry is signed integer and int16 is used for table which
47dk_size == 256.
48*/
49
Benjamin Peterson7d95e402012-04-23 11:24:50 -040050
51/*
Benjamin Peterson7d95e402012-04-23 11:24:50 -040052The DictObject can be in one of two forms.
Victor Stinner742da042016-09-07 17:40:12 -070053
Benjamin Peterson7d95e402012-04-23 11:24:50 -040054Either:
55 A combined table:
56 ma_values == NULL, dk_refcnt == 1.
57 Values are stored in the me_value field of the PyDictKeysObject.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040058Or:
59 A split table:
60 ma_values != NULL, dk_refcnt >= 1
61 Values are stored in the ma_values array.
Victor Stinner742da042016-09-07 17:40:12 -070062 Only string (unicode) keys are allowed.
63 All dicts sharing same key must have same insertion order.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040064
Victor Stinner742da042016-09-07 17:40:12 -070065There are four kinds of slots in the table (slot is index, and
66DK_ENTRIES(keys)[index] if index >= 0):
67
681. Unused. index == DKIX_EMPTY
69 Does not hold an active (key, value) pair now and never did. Unused can
70 transition to Active upon key insertion. This is each slot's initial state.
71
722. Active. index >= 0, me_key != NULL and me_value != NULL
73 Holds an active (key, value) pair. Active can transition to Dummy or
74 Pending upon key deletion (for combined and split tables respectively).
75 This is the only case in which me_value != NULL.
76
773. Dummy. index == DKIX_DUMMY (combined only)
78 Previously held an active (key, value) pair, but that was deleted and an
79 active pair has not yet overwritten the slot. Dummy can transition to
80 Active upon key insertion. Dummy slots cannot be made Unused again
81 else the probe sequence in case of collision would have no way to know
82 they were once active.
83
844. Pending. index >= 0, key != NULL, and value == NULL (split only)
85 Not yet inserted in split-table.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040086*/
87
Victor Stinner742da042016-09-07 17:40:12 -070088/*
89Preserving insertion order
Benjamin Peterson7d95e402012-04-23 11:24:50 -040090
Victor Stinner742da042016-09-07 17:40:12 -070091It's simple for combined table. Since dk_entries is mostly append only, we can
92get insertion order by just iterating dk_entries.
93
94One exception is .popitem(). It removes last item in dk_entries and decrement
95dk_nentries to achieve amortized O(1). Since there are DKIX_DUMMY remains in
96dk_indices, we can't increment dk_usable even though dk_nentries is
97decremented.
98
99In split table, inserting into pending entry is allowed only for dk_entries[ix]
100where ix == mp->ma_used. Inserting into other index and deleting item cause
101converting the dict to the combined table.
102*/
103
104/* PyDict_MINSIZE is the starting size for any new dict.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400105 * 8 allows dicts with no more than 5 active entries; experiments suggested
106 * this suffices for the majority of dicts (consisting mostly of usually-small
107 * dicts created to pass keyword arguments).
108 * Making this 8, rather than 4 reduces the number of resizes for most
109 * dictionaries, without any significant extra memory use.
110 */
Victor Stinner742da042016-09-07 17:40:12 -0700111#define PyDict_MINSIZE 8
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400112
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113#include "Python.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600114#include "internal/pystate.h"
Eric Snow96c6af92015-05-29 22:21:39 -0600115#include "dict-common.h"
Victor Stinner990397e2016-09-09 20:22:59 -0700116#include "stringlib/eq.h" /* to get unicode_eq() */
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000117
Larry Hastings61272b72014-01-07 12:41:53 -0800118/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -0800119class dict "PyDictObject *" "&PyDict_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800120[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -0800121/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f157a5a0ce9589d6]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800122
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400123
124/*
125To ensure the lookup algorithm terminates, there must be at least one Unused
126slot (NULL key) in the table.
127To avoid slowing down lookups on a near-full table, we resize the table when
128it's USABLE_FRACTION (currently two-thirds) full.
129*/
Guido van Rossum16e93a81997-01-28 00:00:11 +0000130
Tim Peterseb28ef22001-06-02 05:27:19 +0000131#define PERTURB_SHIFT 5
132
Guido van Rossum16e93a81997-01-28 00:00:11 +0000133/*
Tim Peterseb28ef22001-06-02 05:27:19 +0000134Major subtleties ahead: Most hash schemes depend on having a "good" hash
135function, in the sense of simulating randomness. Python doesn't: its most
R David Murray537ad7a2016-07-10 12:33:18 -0400136important hash functions (for ints) are very regular in common
Tim Peterseb28ef22001-06-02 05:27:19 +0000137cases:
Tim Peters15d49292001-05-27 07:39:22 +0000138
R David Murray537ad7a2016-07-10 12:33:18 -0400139 >>>[hash(i) for i in range(4)]
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000140 [0, 1, 2, 3]
Tim Peters15d49292001-05-27 07:39:22 +0000141
Tim Peterseb28ef22001-06-02 05:27:19 +0000142This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
143the low-order i bits as the initial table index is extremely fast, and there
R David Murray537ad7a2016-07-10 12:33:18 -0400144are no collisions at all for dicts indexed by a contiguous range of ints. So
145this gives better-than-random behavior in common cases, and that's very
146desirable.
Tim Peters15d49292001-05-27 07:39:22 +0000147
Tim Peterseb28ef22001-06-02 05:27:19 +0000148OTOH, when collisions occur, the tendency to fill contiguous slices of the
149hash table makes a good collision resolution strategy crucial. Taking only
150the last i bits of the hash code is also vulnerable: for example, consider
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151the list [i << 16 for i in range(20000)] as a set of keys. Since ints are
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000152their own hash codes, and this fits in a dict of size 2**15, the last 15 bits
153 of every hash code are all 0: they *all* map to the same table index.
Tim Peters15d49292001-05-27 07:39:22 +0000154
Tim Peterseb28ef22001-06-02 05:27:19 +0000155But catering to unusual cases should not slow the usual ones, so we just take
156the last i bits anyway. It's up to collision resolution to do the rest. If
157we *usually* find the key we're looking for on the first try (and, it turns
158out, we usually do -- the table load factor is kept under 2/3, so the odds
159are solidly in our favor), then it makes best sense to keep the initial index
160computation dirt cheap.
Tim Peters15d49292001-05-27 07:39:22 +0000161
Tim Peterseb28ef22001-06-02 05:27:19 +0000162The first half of collision resolution is to visit table indices via this
163recurrence:
Tim Peters15d49292001-05-27 07:39:22 +0000164
Tim Peterseb28ef22001-06-02 05:27:19 +0000165 j = ((5*j) + 1) mod 2**i
Tim Peters15d49292001-05-27 07:39:22 +0000166
Tim Peterseb28ef22001-06-02 05:27:19 +0000167For any initial j in range(2**i), repeating that 2**i times generates each
168int in range(2**i) exactly once (see any text on random-number generation for
169proof). By itself, this doesn't help much: like linear probing (setting
170j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
171order. This would be bad, except that's not the only thing we do, and it's
172actually *good* in the common cases where hash keys are consecutive. In an
173example that's really too small to make this entirely clear, for a table of
174size 2**3 the order of indices is:
Tim Peters15d49292001-05-27 07:39:22 +0000175
Tim Peterseb28ef22001-06-02 05:27:19 +0000176 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
177
178If two things come in at index 5, the first place we look after is index 2,
179not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
180Linear probing is deadly in this case because there the fixed probe order
181is the *same* as the order consecutive keys are likely to arrive. But it's
182extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
183and certain that consecutive hash codes do not.
184
185The other half of the strategy is to get the other bits of the hash code
186into play. This is done by initializing a (unsigned) vrbl "perturb" to the
187full hash code, and changing the recurrence to:
188
Tim Peterseb28ef22001-06-02 05:27:19 +0000189 perturb >>= PERTURB_SHIFT;
INADA Naoki267941c2016-10-06 15:19:07 +0900190 j = (5*j) + 1 + perturb;
Tim Peterseb28ef22001-06-02 05:27:19 +0000191 use j % 2**i as the next table index;
192
193Now the probe sequence depends (eventually) on every bit in the hash code,
194and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
195because it quickly magnifies small differences in the bits that didn't affect
196the initial index. Note that because perturb is unsigned, if the recurrence
197is executed often enough perturb eventually becomes and remains 0. At that
198point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
199that's certain to find an empty slot eventually (since it generates every int
200in range(2**i), and we make sure there's always at least one empty slot).
201
202Selecting a good value for PERTURB_SHIFT is a balancing act. You want it
203small so that the high bits of the hash code continue to affect the probe
204sequence across iterations; but you want it large so that in really bad cases
205the high-order hash bits have an effect on early iterations. 5 was "the
206best" in minimizing total collisions across experiments Tim Peters ran (on
207both normal and pathological cases), but 4 and 6 weren't significantly worse.
208
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000209Historical: Reimer Behrends contributed the idea of using a polynomial-based
Tim Peterseb28ef22001-06-02 05:27:19 +0000210approach, using repeated multiplication by x in GF(2**n) where an irreducible
211polynomial for each table size was chosen such that x was a primitive root.
212Christian Tismer later extended that to use division by x instead, as an
213efficient way to get the high bits of the hash code into play. This scheme
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000214also gave excellent collision statistics, but was more expensive: two
215if-tests were required inside the loop; computing "the next" index took about
216the same number of operations but without as much potential parallelism
217(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
218above, and then shifting perturb can be done while the table index is being
219masked); and the PyDictObject struct required a member to hold the table's
220polynomial. In Tim's experiments the current scheme ran faster, produced
221equally good collision statistics, needed less code & used less memory.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000222
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000223*/
Tim Petersdea48ec2001-05-22 20:40:22 +0000224
Fred Drake1bff34a2000-08-31 19:31:38 +0000225/* forward declarations */
Victor Stinner742da042016-09-07 17:40:12 -0700226static Py_ssize_t lookdict(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900227 Py_hash_t hash, PyObject **value_addr);
Victor Stinner742da042016-09-07 17:40:12 -0700228static Py_ssize_t lookdict_unicode(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900229 Py_hash_t hash, PyObject **value_addr);
Victor Stinner742da042016-09-07 17:40:12 -0700230static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400231lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900232 Py_hash_t hash, PyObject **value_addr);
Victor Stinner742da042016-09-07 17:40:12 -0700233static Py_ssize_t lookdict_split(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900234 Py_hash_t hash, PyObject **value_addr);
Fred Drake1bff34a2000-08-31 19:31:38 +0000235
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400236static int dictresize(PyDictObject *mp, Py_ssize_t minused);
Tim Petersdea48ec2001-05-22 20:40:22 +0000237
Benjamin Peterson3c569292016-09-08 13:16:41 -0700238/*Global counter used to set ma_version_tag field of dictionary.
Victor Stinner3b6a6b42016-09-08 12:51:24 -0700239 * It is incremented each time that a dictionary is created and each
240 * time that a dictionary is modified. */
241static uint64_t pydict_global_version = 0;
242
243#define DICT_NEXT_VERSION() (++pydict_global_version)
244
Victor Stinner742da042016-09-07 17:40:12 -0700245/* Dictionary reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +0000246#ifndef PyDict_MAXFREELIST
247#define PyDict_MAXFREELIST 80
248#endif
249static PyDictObject *free_list[PyDict_MAXFREELIST];
250static int numfree = 0;
Victor Stinner742da042016-09-07 17:40:12 -0700251static PyDictKeysObject *keys_free_list[PyDict_MAXFREELIST];
252static int numfreekeys = 0;
Raymond Hettinger43442782004-03-17 21:55:03 +0000253
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300254#include "clinic/dictobject.c.h"
255
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100256int
257PyDict_ClearFreeList(void)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 PyDictObject *op;
Victor Stinner742da042016-09-07 17:40:12 -0700260 int ret = numfree + numfreekeys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 while (numfree) {
262 op = free_list[--numfree];
263 assert(PyDict_CheckExact(op));
264 PyObject_GC_Del(op);
265 }
Victor Stinner742da042016-09-07 17:40:12 -0700266 while (numfreekeys) {
267 PyObject_FREE(keys_free_list[--numfreekeys]);
268 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100269 return ret;
270}
271
David Malcolm49526f42012-06-22 14:55:41 -0400272/* Print summary info about the state of the optimized allocator */
273void
274_PyDict_DebugMallocStats(FILE *out)
275{
276 _PyDebugAllocatorStats(out,
277 "free PyDictObject", numfree, sizeof(PyDictObject));
278}
279
280
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100281void
282PyDict_Fini(void)
283{
284 PyDict_ClearFreeList();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000285}
286
Victor Stinner742da042016-09-07 17:40:12 -0700287#define DK_SIZE(dk) ((dk)->dk_size)
288#if SIZEOF_VOID_P > 4
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700289#define DK_IXSIZE(dk) \
290 (DK_SIZE(dk) <= 0xff ? \
291 1 : DK_SIZE(dk) <= 0xffff ? \
292 2 : DK_SIZE(dk) <= 0xffffffff ? \
Benjamin Peterson3c569292016-09-08 13:16:41 -0700293 4 : sizeof(int64_t))
Victor Stinner742da042016-09-07 17:40:12 -0700294#else
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700295#define DK_IXSIZE(dk) \
296 (DK_SIZE(dk) <= 0xff ? \
297 1 : DK_SIZE(dk) <= 0xffff ? \
Benjamin Peterson3c569292016-09-08 13:16:41 -0700298 2 : sizeof(int32_t))
Victor Stinner742da042016-09-07 17:40:12 -0700299#endif
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700300#define DK_ENTRIES(dk) \
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700301 ((PyDictKeyEntry*)(&((int8_t*)((dk)->dk_indices))[DK_SIZE(dk) * DK_IXSIZE(dk)]))
Victor Stinner742da042016-09-07 17:40:12 -0700302
Antoine Pitrou2d169b22012-05-12 23:43:44 +0200303#define DK_DEBUG_INCREF _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA
304#define DK_DEBUG_DECREF _Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA
305
306#define DK_INCREF(dk) (DK_DEBUG_INCREF ++(dk)->dk_refcnt)
307#define DK_DECREF(dk) if (DK_DEBUG_DECREF (--(dk)->dk_refcnt) == 0) free_keys_object(dk)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400308#define DK_MASK(dk) (((dk)->dk_size)-1)
309#define IS_POWER_OF_2(x) (((x) & (x-1)) == 0)
310
Victor Stinner742da042016-09-07 17:40:12 -0700311/* lookup indices. returns DKIX_EMPTY, DKIX_DUMMY, or ix >=0 */
Benjamin Peterson73222252016-09-08 09:58:47 -0700312static inline Py_ssize_t
Victor Stinner742da042016-09-07 17:40:12 -0700313dk_get_index(PyDictKeysObject *keys, Py_ssize_t i)
314{
315 Py_ssize_t s = DK_SIZE(keys);
Victor Stinner71211e32016-09-08 10:52:46 -0700316 Py_ssize_t ix;
317
Victor Stinner742da042016-09-07 17:40:12 -0700318 if (s <= 0xff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700319 int8_t *indices = (int8_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700320 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700321 }
322 else if (s <= 0xffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700323 int16_t *indices = (int16_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700324 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700325 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700326#if SIZEOF_VOID_P > 4
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300327 else if (s > 0xffffffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700328 int64_t *indices = (int64_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700329 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700330 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700331#endif
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300332 else {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700333 int32_t *indices = (int32_t*)(keys->dk_indices);
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300334 ix = indices[i];
335 }
Victor Stinner71211e32016-09-08 10:52:46 -0700336 assert(ix >= DKIX_DUMMY);
337 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700338}
339
340/* write to indices. */
Benjamin Peterson73222252016-09-08 09:58:47 -0700341static inline void
Victor Stinner742da042016-09-07 17:40:12 -0700342dk_set_index(PyDictKeysObject *keys, Py_ssize_t i, Py_ssize_t ix)
343{
344 Py_ssize_t s = DK_SIZE(keys);
Victor Stinner71211e32016-09-08 10:52:46 -0700345
346 assert(ix >= DKIX_DUMMY);
347
Victor Stinner742da042016-09-07 17:40:12 -0700348 if (s <= 0xff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700349 int8_t *indices = (int8_t*)(keys->dk_indices);
Victor Stinner71211e32016-09-08 10:52:46 -0700350 assert(ix <= 0x7f);
Victor Stinner208857e2016-09-08 11:35:46 -0700351 indices[i] = (char)ix;
Victor Stinner742da042016-09-07 17:40:12 -0700352 }
353 else if (s <= 0xffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700354 int16_t *indices = (int16_t*)(keys->dk_indices);
Victor Stinner71211e32016-09-08 10:52:46 -0700355 assert(ix <= 0x7fff);
Victor Stinner208857e2016-09-08 11:35:46 -0700356 indices[i] = (int16_t)ix;
Victor Stinner742da042016-09-07 17:40:12 -0700357 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700358#if SIZEOF_VOID_P > 4
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300359 else if (s > 0xffffffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700360 int64_t *indices = (int64_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700361 indices[i] = ix;
Victor Stinner742da042016-09-07 17:40:12 -0700362 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700363#endif
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300364 else {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700365 int32_t *indices = (int32_t*)(keys->dk_indices);
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300366 assert(ix <= 0x7fffffff);
367 indices[i] = (int32_t)ix;
368 }
Victor Stinner742da042016-09-07 17:40:12 -0700369}
370
371
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200372/* USABLE_FRACTION is the maximum dictionary load.
Victor Stinner742da042016-09-07 17:40:12 -0700373 * Increasing this ratio makes dictionaries more dense resulting in more
374 * collisions. Decreasing it improves sparseness at the expense of spreading
375 * indices over more cache lines and at the cost of total memory consumed.
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200376 *
377 * USABLE_FRACTION must obey the following:
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400378 * (0 < USABLE_FRACTION(n) < n) for all n >= 2
379 *
Victor Stinner742da042016-09-07 17:40:12 -0700380 * USABLE_FRACTION should be quick to calculate.
381 * Fractions around 1/2 to 2/3 seem to work well in practice.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400382 */
Victor Stinner742da042016-09-07 17:40:12 -0700383#define USABLE_FRACTION(n) (((n) << 1)/3)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400384
Victor Stinner742da042016-09-07 17:40:12 -0700385/* ESTIMATE_SIZE is reverse function of USABLE_FRACTION.
386 * This can be used to reserve enough size to insert n entries without
387 * resizing.
388 */
INADA Naoki92c50ee2016-11-22 00:57:02 +0900389#define ESTIMATE_SIZE(n) (((n)*3+1) >> 1)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400390
Victor Stinner742da042016-09-07 17:40:12 -0700391/* Alternative fraction that is otherwise close enough to 2n/3 to make
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400392 * little difference. 8 * 2/3 == 8 * 5/8 == 5. 16 * 2/3 == 16 * 5/8 == 10.
393 * 32 * 2/3 = 21, 32 * 5/8 = 20.
394 * Its advantage is that it is faster to compute on machines with slow division.
395 * #define USABLE_FRACTION(n) (((n) >> 1) + ((n) >> 2) - ((n) >> 3))
Victor Stinner742da042016-09-07 17:40:12 -0700396 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400397
Victor Stinnera9f61a52013-07-16 22:17:26 +0200398/* GROWTH_RATE. Growth rate upon hitting maximum load.
INADA Naoki5fbc5112018-04-17 15:53:34 +0900399 * Currently set to used*3.
Victor Stinnera9f61a52013-07-16 22:17:26 +0200400 * This means that dicts double in size when growing without deletions,
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700401 * but have more head room when the number of deletions is on a par with the
INADA Naoki5fbc5112018-04-17 15:53:34 +0900402 * number of insertions. See also bpo-17563 and bpo-33205.
403 *
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700404 * GROWTH_RATE was set to used*4 up to version 3.2.
405 * GROWTH_RATE was set to used*2 in version 3.3.0
INADA Naoki5fbc5112018-04-17 15:53:34 +0900406 * GROWTH_RATE was set to used*2 + capacity/2 in 3.4.0-3.6.0.
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200407 */
INADA Naoki5fbc5112018-04-17 15:53:34 +0900408#define GROWTH_RATE(d) ((d)->ma_used*3)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400409
410#define ENSURE_ALLOWS_DELETIONS(d) \
411 if ((d)->ma_keys->dk_lookup == lookdict_unicode_nodummy) { \
412 (d)->ma_keys->dk_lookup = lookdict_unicode; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400414
415/* This immutable, empty PyDictKeysObject is used for PyDict_Clear()
416 * (which cannot fail and thus can do no allocation).
417 */
418static PyDictKeysObject empty_keys_struct = {
Serhiy Storchaka97932e42016-09-26 23:01:23 +0300419 1, /* dk_refcnt */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400420 1, /* dk_size */
421 lookdict_split, /* dk_lookup */
422 0, /* dk_usable (immutable) */
Victor Stinner742da042016-09-07 17:40:12 -0700423 0, /* dk_nentries */
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700424 {DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY,
425 DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY}, /* dk_indices */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400426};
427
428static PyObject *empty_values[1] = { NULL };
429
430#define Py_EMPTY_KEYS &empty_keys_struct
431
Victor Stinner611b0fa2016-09-14 15:02:01 +0200432/* Uncomment to check the dict content in _PyDict_CheckConsistency() */
433/* #define DEBUG_PYDICT */
434
435
T. Woutersa00c3fd2017-03-31 09:14:41 -0700436#ifndef NDEBUG
Victor Stinner611b0fa2016-09-14 15:02:01 +0200437static int
438_PyDict_CheckConsistency(PyDictObject *mp)
439{
440 PyDictKeysObject *keys = mp->ma_keys;
441 int splitted = _PyDict_HasSplitTable(mp);
442 Py_ssize_t usable = USABLE_FRACTION(keys->dk_size);
443#ifdef DEBUG_PYDICT
444 PyDictKeyEntry *entries = DK_ENTRIES(keys);
445 Py_ssize_t i;
446#endif
447
448 assert(0 <= mp->ma_used && mp->ma_used <= usable);
449 assert(IS_POWER_OF_2(keys->dk_size));
450 assert(0 <= keys->dk_usable
451 && keys->dk_usable <= usable);
452 assert(0 <= keys->dk_nentries
453 && keys->dk_nentries <= usable);
454 assert(keys->dk_usable + keys->dk_nentries <= usable);
455
456 if (!splitted) {
457 /* combined table */
458 assert(keys->dk_refcnt == 1);
459 }
460
461#ifdef DEBUG_PYDICT
462 for (i=0; i < keys->dk_size; i++) {
463 Py_ssize_t ix = dk_get_index(keys, i);
464 assert(DKIX_DUMMY <= ix && ix <= usable);
465 }
466
467 for (i=0; i < usable; i++) {
468 PyDictKeyEntry *entry = &entries[i];
469 PyObject *key = entry->me_key;
470
471 if (key != NULL) {
472 if (PyUnicode_CheckExact(key)) {
473 Py_hash_t hash = ((PyASCIIObject *)key)->hash;
474 assert(hash != -1);
475 assert(entry->me_hash == hash);
476 }
477 else {
478 /* test_dict fails if PyObject_Hash() is called again */
479 assert(entry->me_hash != -1);
480 }
481 if (!splitted) {
482 assert(entry->me_value != NULL);
483 }
484 }
485
486 if (splitted) {
487 assert(entry->me_value == NULL);
488 }
489 }
490
491 if (splitted) {
492 /* splitted table */
493 for (i=0; i < mp->ma_used; i++) {
494 assert(mp->ma_values[i] != NULL);
495 }
496 }
497#endif
498
499 return 1;
500}
501#endif
502
503
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400504static PyDictKeysObject *new_keys_object(Py_ssize_t size)
505{
506 PyDictKeysObject *dk;
Victor Stinner742da042016-09-07 17:40:12 -0700507 Py_ssize_t es, usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400508
Victor Stinner742da042016-09-07 17:40:12 -0700509 assert(size >= PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400510 assert(IS_POWER_OF_2(size));
Victor Stinner742da042016-09-07 17:40:12 -0700511
512 usable = USABLE_FRACTION(size);
513 if (size <= 0xff) {
514 es = 1;
515 }
516 else if (size <= 0xffff) {
517 es = 2;
518 }
519#if SIZEOF_VOID_P > 4
520 else if (size <= 0xffffffff) {
521 es = 4;
522 }
523#endif
524 else {
525 es = sizeof(Py_ssize_t);
526 }
527
528 if (size == PyDict_MINSIZE && numfreekeys > 0) {
529 dk = keys_free_list[--numfreekeys];
530 }
531 else {
Victor Stinner98ee9d52016-09-08 09:33:56 -0700532 dk = PyObject_MALLOC(sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -0700533 + es * size
534 + sizeof(PyDictKeyEntry) * usable);
Victor Stinner742da042016-09-07 17:40:12 -0700535 if (dk == NULL) {
536 PyErr_NoMemory();
537 return NULL;
538 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400539 }
Antoine Pitrou2d169b22012-05-12 23:43:44 +0200540 DK_DEBUG_INCREF dk->dk_refcnt = 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400541 dk->dk_size = size;
Victor Stinner742da042016-09-07 17:40:12 -0700542 dk->dk_usable = usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400543 dk->dk_lookup = lookdict_unicode_nodummy;
Victor Stinner742da042016-09-07 17:40:12 -0700544 dk->dk_nentries = 0;
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700545 memset(&dk->dk_indices[0], 0xff, es * size);
Victor Stinner742da042016-09-07 17:40:12 -0700546 memset(DK_ENTRIES(dk), 0, sizeof(PyDictKeyEntry) * usable);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400547 return dk;
548}
549
550static void
551free_keys_object(PyDictKeysObject *keys)
552{
Victor Stinner742da042016-09-07 17:40:12 -0700553 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400554 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -0700555 for (i = 0, n = keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400556 Py_XDECREF(entries[i].me_key);
557 Py_XDECREF(entries[i].me_value);
558 }
Victor Stinner742da042016-09-07 17:40:12 -0700559 if (keys->dk_size == PyDict_MINSIZE && numfreekeys < PyDict_MAXFREELIST) {
560 keys_free_list[numfreekeys++] = keys;
561 return;
562 }
Raymond Hettingerce5179f2016-01-31 08:56:21 -0800563 PyObject_FREE(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400564}
565
566#define new_values(size) PyMem_NEW(PyObject *, size)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400567#define free_values(values) PyMem_FREE(values)
568
569/* Consumes a reference to the keys object */
570static PyObject *
571new_dict(PyDictKeysObject *keys, PyObject **values)
572{
573 PyDictObject *mp;
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200574 assert(keys != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 if (numfree) {
576 mp = free_list[--numfree];
577 assert (mp != NULL);
578 assert (Py_TYPE(mp) == &PyDict_Type);
579 _Py_NewReference((PyObject *)mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400581 else {
582 mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
583 if (mp == NULL) {
584 DK_DECREF(keys);
585 free_values(values);
586 return NULL;
587 }
588 }
589 mp->ma_keys = keys;
590 mp->ma_values = values;
591 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -0700592 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner611b0fa2016-09-14 15:02:01 +0200593 assert(_PyDict_CheckConsistency(mp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000595}
596
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400597/* Consumes a reference to the keys object */
598static PyObject *
599new_dict_with_shared_keys(PyDictKeysObject *keys)
600{
601 PyObject **values;
602 Py_ssize_t i, size;
603
Victor Stinner742da042016-09-07 17:40:12 -0700604 size = USABLE_FRACTION(DK_SIZE(keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400605 values = new_values(size);
606 if (values == NULL) {
607 DK_DECREF(keys);
608 return PyErr_NoMemory();
609 }
610 for (i = 0; i < size; i++) {
611 values[i] = NULL;
612 }
613 return new_dict(keys, values);
614}
615
Yury Selivanovb0a7a032018-01-22 11:54:41 -0500616
617static PyObject *
618clone_combined_dict(PyDictObject *orig)
619{
620 assert(PyDict_CheckExact(orig));
621 assert(orig->ma_values == NULL);
622 assert(orig->ma_keys->dk_refcnt == 1);
623
624 Py_ssize_t keys_size = _PyDict_KeysSize(orig->ma_keys);
625 PyDictKeysObject *keys = PyObject_Malloc(keys_size);
626 if (keys == NULL) {
627 PyErr_NoMemory();
628 return NULL;
629 }
630
631 memcpy(keys, orig->ma_keys, keys_size);
632
633 /* After copying key/value pairs, we need to incref all
634 keys and values and they are about to be co-owned by a
635 new dict object. */
636 PyDictKeyEntry *ep0 = DK_ENTRIES(keys);
637 Py_ssize_t n = keys->dk_nentries;
638 for (Py_ssize_t i = 0; i < n; i++) {
639 PyDictKeyEntry *entry = &ep0[i];
640 PyObject *value = entry->me_value;
641 if (value != NULL) {
642 Py_INCREF(value);
643 Py_INCREF(entry->me_key);
644 }
645 }
646
647 PyDictObject *new = (PyDictObject *)new_dict(keys, NULL);
648 if (new == NULL) {
649 /* In case of an error, `new_dict()` takes care of
650 cleaning up `keys`. */
651 return NULL;
652 }
653 new->ma_used = orig->ma_used;
654 assert(_PyDict_CheckConsistency(new));
655 if (_PyObject_GC_IS_TRACKED(orig)) {
656 /* Maintain tracking. */
657 _PyObject_GC_TRACK(new);
658 }
Yury Selivanov0b752282018-07-06 12:20:07 -0400659
660 /* Since we copied the keys table we now have an extra reference
661 in the system. Manually call _Py_INC_REFTOTAL to signal that
662 we have it now; calling DK_INCREF would be an error as
663 keys->dk_refcnt is already set to 1 (after memcpy). */
664 _Py_INC_REFTOTAL;
665
Yury Selivanovb0a7a032018-01-22 11:54:41 -0500666 return (PyObject *)new;
667}
668
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400669PyObject *
670PyDict_New(void)
671{
Victor Stinner742da042016-09-07 17:40:12 -0700672 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200673 if (keys == NULL)
674 return NULL;
675 return new_dict(keys, NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400676}
677
Victor Stinner742da042016-09-07 17:40:12 -0700678/* Search index of hash table from offset of entry table */
679static Py_ssize_t
680lookdict_index(PyDictKeysObject *k, Py_hash_t hash, Py_ssize_t index)
681{
Victor Stinner742da042016-09-07 17:40:12 -0700682 size_t mask = DK_MASK(k);
INADA Naoki073ae482017-06-23 15:22:50 +0900683 size_t perturb = (size_t)hash;
684 size_t i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700685
INADA Naoki073ae482017-06-23 15:22:50 +0900686 for (;;) {
687 Py_ssize_t ix = dk_get_index(k, i);
Victor Stinner742da042016-09-07 17:40:12 -0700688 if (ix == index) {
689 return i;
690 }
691 if (ix == DKIX_EMPTY) {
692 return DKIX_EMPTY;
693 }
INADA Naoki073ae482017-06-23 15:22:50 +0900694 perturb >>= PERTURB_SHIFT;
695 i = mask & (i*5 + perturb + 1);
Victor Stinner742da042016-09-07 17:40:12 -0700696 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700697 Py_UNREACHABLE();
Victor Stinner742da042016-09-07 17:40:12 -0700698}
699
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000700/*
701The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000702This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000703Open addressing is preferred over chaining since the link overhead for
704chaining would be substantial (100% with typical malloc overhead).
705
Tim Peterseb28ef22001-06-02 05:27:19 +0000706The initial probe index is computed as hash mod the table size. Subsequent
707probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000708
709All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000710
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000711The details in this version are due to Tim Peters, building on many past
Tim Peterseb28ef22001-06-02 05:27:19 +0000712contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000713Christian Tismer.
Fred Drake1bff34a2000-08-31 19:31:38 +0000714
Victor Stinner742da042016-09-07 17:40:12 -0700715lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a
Victor Stinnera4348cc2016-09-08 12:01:25 -0700716comparison raises an exception.
Guido van Rossum89d8c602007-09-18 17:26:56 +0000717lookdict_unicode() below is specialized to string keys, comparison of which can
INADA Naoki1b8df102017-02-20 22:48:10 +0900718never raise an exception; that function can never return DKIX_ERROR when key
719is string. Otherwise, it falls back to lookdict().
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400720lookdict_unicode_nodummy is further specialized for string keys that cannot be
721the <dummy> value.
INADA Naoki778928b2017-08-03 23:45:15 +0900722For both, when the key isn't found a DKIX_EMPTY is returned.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000723*/
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100724static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400725lookdict(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900726 Py_hash_t hash, PyObject **value_addr)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000727{
INADA Naoki778928b2017-08-03 23:45:15 +0900728 size_t i, mask, perturb;
Victor Stinner742da042016-09-07 17:40:12 -0700729 PyDictKeysObject *dk;
INADA Naoki778928b2017-08-03 23:45:15 +0900730 PyDictKeyEntry *ep0;
Tim Peterseb28ef22001-06-02 05:27:19 +0000731
Antoine Pitrou9a234902012-05-13 20:48:01 +0200732top:
Victor Stinner742da042016-09-07 17:40:12 -0700733 dk = mp->ma_keys;
Victor Stinner742da042016-09-07 17:40:12 -0700734 ep0 = DK_ENTRIES(dk);
INADA Naoki778928b2017-08-03 23:45:15 +0900735 mask = DK_MASK(dk);
736 perturb = hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700738
INADA Naoki778928b2017-08-03 23:45:15 +0900739 for (;;) {
740 Py_ssize_t ix = dk_get_index(dk, i);
Victor Stinner742da042016-09-07 17:40:12 -0700741 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700742 *value_addr = NULL;
743 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400744 }
INADA Naoki778928b2017-08-03 23:45:15 +0900745 if (ix >= 0) {
746 PyDictKeyEntry *ep = &ep0[ix];
747 assert(ep->me_key != NULL);
748 if (ep->me_key == key) {
749 *value_addr = ep->me_value;
750 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700751 }
INADA Naoki778928b2017-08-03 23:45:15 +0900752 if (ep->me_hash == hash) {
753 PyObject *startkey = ep->me_key;
754 Py_INCREF(startkey);
755 int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
756 Py_DECREF(startkey);
757 if (cmp < 0) {
758 *value_addr = NULL;
759 return DKIX_ERROR;
760 }
761 if (dk == mp->ma_keys && ep->me_key == startkey) {
762 if (cmp > 0) {
763 *value_addr = ep->me_value;
764 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700765 }
INADA Naoki778928b2017-08-03 23:45:15 +0900766 }
767 else {
768 /* The dict was mutated, restart */
769 goto top;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400770 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 }
INADA Naoki778928b2017-08-03 23:45:15 +0900773 perturb >>= PERTURB_SHIFT;
774 i = (i*5 + perturb + 1) & mask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700776 Py_UNREACHABLE();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000777}
778
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400779/* Specialized version for string-only keys */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100780static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400781lookdict_unicode(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900782 Py_hash_t hash, PyObject **value_addr)
Fred Drake1bff34a2000-08-31 19:31:38 +0000783{
Victor Stinner742da042016-09-07 17:40:12 -0700784 assert(mp->ma_values == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 /* Make sure this function doesn't have to handle non-unicode keys,
786 including subclasses of str; e.g., one reason to subclass
787 unicodes is to override __eq__, and for speed we don't cater to
788 that here. */
789 if (!PyUnicode_CheckExact(key)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400790 mp->ma_keys->dk_lookup = lookdict;
INADA Naoki778928b2017-08-03 23:45:15 +0900791 return lookdict(mp, key, hash, value_addr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 }
Tim Peters15d49292001-05-27 07:39:22 +0000793
INADA Naoki778928b2017-08-03 23:45:15 +0900794 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
795 size_t mask = DK_MASK(mp->ma_keys);
796 size_t perturb = (size_t)hash;
797 size_t i = (size_t)hash & mask;
798
799 for (;;) {
800 Py_ssize_t ix = dk_get_index(mp->ma_keys, i);
Victor Stinner742da042016-09-07 17:40:12 -0700801 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700802 *value_addr = NULL;
803 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400804 }
INADA Naoki778928b2017-08-03 23:45:15 +0900805 if (ix >= 0) {
806 PyDictKeyEntry *ep = &ep0[ix];
807 assert(ep->me_key != NULL);
808 assert(PyUnicode_CheckExact(ep->me_key));
809 if (ep->me_key == key ||
810 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
811 *value_addr = ep->me_value;
812 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700813 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400814 }
INADA Naoki778928b2017-08-03 23:45:15 +0900815 perturb >>= PERTURB_SHIFT;
816 i = mask & (i*5 + perturb + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700818 Py_UNREACHABLE();
Fred Drake1bff34a2000-08-31 19:31:38 +0000819}
820
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400821/* Faster version of lookdict_unicode when it is known that no <dummy> keys
822 * will be present. */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100823static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400824lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900825 Py_hash_t hash, PyObject **value_addr)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400826{
Victor Stinner742da042016-09-07 17:40:12 -0700827 assert(mp->ma_values == NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400828 /* Make sure this function doesn't have to handle non-unicode keys,
829 including subclasses of str; e.g., one reason to subclass
830 unicodes is to override __eq__, and for speed we don't cater to
831 that here. */
832 if (!PyUnicode_CheckExact(key)) {
833 mp->ma_keys->dk_lookup = lookdict;
INADA Naoki778928b2017-08-03 23:45:15 +0900834 return lookdict(mp, key, hash, value_addr);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400835 }
INADA Naoki778928b2017-08-03 23:45:15 +0900836
837 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
838 size_t mask = DK_MASK(mp->ma_keys);
839 size_t perturb = (size_t)hash;
840 size_t i = (size_t)hash & mask;
841
842 for (;;) {
843 Py_ssize_t ix = dk_get_index(mp->ma_keys, i);
Victor Stinner742da042016-09-07 17:40:12 -0700844 assert (ix != DKIX_DUMMY);
845 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700846 *value_addr = NULL;
847 return DKIX_EMPTY;
848 }
INADA Naoki778928b2017-08-03 23:45:15 +0900849 PyDictKeyEntry *ep = &ep0[ix];
850 assert(ep->me_key != NULL);
851 assert(PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700852 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400853 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
INADA Naokiba609772016-12-07 20:41:42 +0900854 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700855 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400856 }
INADA Naoki778928b2017-08-03 23:45:15 +0900857 perturb >>= PERTURB_SHIFT;
858 i = mask & (i*5 + perturb + 1);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400859 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700860 Py_UNREACHABLE();
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400861}
862
863/* Version of lookdict for split tables.
864 * All split tables and only split tables use this lookup function.
865 * Split tables only contain unicode keys and no dummy keys,
866 * so algorithm is the same as lookdict_unicode_nodummy.
867 */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100868static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400869lookdict_split(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900870 Py_hash_t hash, PyObject **value_addr)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400871{
Victor Stinner742da042016-09-07 17:40:12 -0700872 /* mp must split table */
873 assert(mp->ma_values != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400874 if (!PyUnicode_CheckExact(key)) {
INADA Naoki778928b2017-08-03 23:45:15 +0900875 Py_ssize_t ix = lookdict(mp, key, hash, value_addr);
Victor Stinner742da042016-09-07 17:40:12 -0700876 if (ix >= 0) {
INADA Naokiba609772016-12-07 20:41:42 +0900877 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700878 }
879 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400880 }
Victor Stinner742da042016-09-07 17:40:12 -0700881
INADA Naoki778928b2017-08-03 23:45:15 +0900882 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
883 size_t mask = DK_MASK(mp->ma_keys);
884 size_t perturb = (size_t)hash;
885 size_t i = (size_t)hash & mask;
886
887 for (;;) {
888 Py_ssize_t ix = dk_get_index(mp->ma_keys, i);
889 assert (ix != DKIX_DUMMY);
Victor Stinner742da042016-09-07 17:40:12 -0700890 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700891 *value_addr = NULL;
892 return DKIX_EMPTY;
893 }
INADA Naoki778928b2017-08-03 23:45:15 +0900894 PyDictKeyEntry *ep = &ep0[ix];
895 assert(ep->me_key != NULL);
896 assert(PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700897 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400898 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
INADA Naokiba609772016-12-07 20:41:42 +0900899 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700900 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400901 }
INADA Naoki778928b2017-08-03 23:45:15 +0900902 perturb >>= PERTURB_SHIFT;
903 i = mask & (i*5 + perturb + 1);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400904 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700905 Py_UNREACHABLE();
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400906}
907
Benjamin Petersonfb886362010-04-24 18:21:17 +0000908int
909_PyDict_HasOnlyStringKeys(PyObject *dict)
910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 Py_ssize_t pos = 0;
912 PyObject *key, *value;
Benjamin Petersonf6096542010-11-17 22:33:12 +0000913 assert(PyDict_Check(dict));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 /* Shortcut */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400915 if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 return 1;
917 while (PyDict_Next(dict, &pos, &key, &value))
918 if (!PyUnicode_Check(key))
919 return 0;
920 return 1;
Benjamin Petersonfb886362010-04-24 18:21:17 +0000921}
922
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000923#define MAINTAIN_TRACKING(mp, key, value) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 do { \
925 if (!_PyObject_GC_IS_TRACKED(mp)) { \
926 if (_PyObject_GC_MAY_BE_TRACKED(key) || \
927 _PyObject_GC_MAY_BE_TRACKED(value)) { \
928 _PyObject_GC_TRACK(mp); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 } \
930 } \
931 } while(0)
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000932
933void
934_PyDict_MaybeUntrack(PyObject *op)
935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 PyDictObject *mp;
937 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -0700938 Py_ssize_t i, numentries;
939 PyDictKeyEntry *ep0;
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
942 return;
943
944 mp = (PyDictObject *) op;
Victor Stinner742da042016-09-07 17:40:12 -0700945 ep0 = DK_ENTRIES(mp->ma_keys);
946 numentries = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400947 if (_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -0700948 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400949 if ((value = mp->ma_values[i]) == NULL)
950 continue;
951 if (_PyObject_GC_MAY_BE_TRACKED(value)) {
Victor Stinner742da042016-09-07 17:40:12 -0700952 assert(!_PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400953 return;
954 }
955 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400957 else {
Victor Stinner742da042016-09-07 17:40:12 -0700958 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400959 if ((value = ep0[i].me_value) == NULL)
960 continue;
961 if (_PyObject_GC_MAY_BE_TRACKED(value) ||
962 _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
963 return;
964 }
965 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 _PyObject_GC_UNTRACK(op);
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000967}
968
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400969/* Internal function to find slot for an item from its hash
Victor Stinner3c336c52016-09-12 14:17:40 +0200970 when it is known that the key is not present in the dict.
971
972 The dict must be combined. */
INADA Naokiba609772016-12-07 20:41:42 +0900973static Py_ssize_t
INADA Naoki778928b2017-08-03 23:45:15 +0900974find_empty_slot(PyDictKeysObject *keys, Py_hash_t hash)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000975{
INADA Naoki778928b2017-08-03 23:45:15 +0900976 assert(keys != NULL);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000977
INADA Naoki778928b2017-08-03 23:45:15 +0900978 const size_t mask = DK_MASK(keys);
979 size_t i = hash & mask;
980 Py_ssize_t ix = dk_get_index(keys, i);
981 for (size_t perturb = hash; ix >= 0;) {
INADA Naoki267941c2016-10-06 15:19:07 +0900982 perturb >>= PERTURB_SHIFT;
INADA Naoki778928b2017-08-03 23:45:15 +0900983 i = (i*5 + perturb + 1) & mask;
984 ix = dk_get_index(keys, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 }
INADA Naoki778928b2017-08-03 23:45:15 +0900986 return i;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000987}
988
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400989static int
990insertion_resize(PyDictObject *mp)
991{
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700992 return dictresize(mp, GROWTH_RATE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400993}
Antoine Pitroue965d972012-02-27 00:45:12 +0100994
995/*
996Internal routine to insert a new item into the table.
997Used both by the internal resize routine and by the public insert routine.
Antoine Pitroue965d972012-02-27 00:45:12 +0100998Returns -1 if an error occurred, or 0 on success.
999*/
1000static int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001001insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001002{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001003 PyObject *old_value;
INADA Naokiba609772016-12-07 20:41:42 +09001004 PyDictKeyEntry *ep;
Antoine Pitroue965d972012-02-27 00:45:12 +01001005
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001006 Py_INCREF(key);
1007 Py_INCREF(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001008 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
1009 if (insertion_resize(mp) < 0)
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001010 goto Fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001011 }
1012
INADA Naoki778928b2017-08-03 23:45:15 +09001013 Py_ssize_t ix = mp->ma_keys->dk_lookup(mp, key, hash, &old_value);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001014 if (ix == DKIX_ERROR)
1015 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001016
Antoine Pitroud6967322014-10-18 00:35:00 +02001017 assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001018 MAINTAIN_TRACKING(mp, key, value);
Victor Stinner742da042016-09-07 17:40:12 -07001019
1020 /* When insertion order is different from shared key, we can't share
1021 * the key anymore. Convert this instance to combine table.
1022 */
1023 if (_PyDict_HasSplitTable(mp) &&
INADA Naokiba609772016-12-07 20:41:42 +09001024 ((ix >= 0 && old_value == NULL && mp->ma_used != ix) ||
Victor Stinner742da042016-09-07 17:40:12 -07001025 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001026 if (insertion_resize(mp) < 0)
1027 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001028 ix = DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001029 }
Victor Stinner742da042016-09-07 17:40:12 -07001030
1031 if (ix == DKIX_EMPTY) {
1032 /* Insert into new slot. */
INADA Naokiba609772016-12-07 20:41:42 +09001033 assert(old_value == NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001034 if (mp->ma_keys->dk_usable <= 0) {
1035 /* Need to resize. */
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001036 if (insertion_resize(mp) < 0)
1037 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001038 }
INADA Naoki778928b2017-08-03 23:45:15 +09001039 Py_ssize_t hashpos = find_empty_slot(mp->ma_keys, hash);
INADA Naokiba609772016-12-07 20:41:42 +09001040 ep = &DK_ENTRIES(mp->ma_keys)[mp->ma_keys->dk_nentries];
Victor Stinner742da042016-09-07 17:40:12 -07001041 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
Victor Stinner742da042016-09-07 17:40:12 -07001042 ep->me_key = key;
1043 ep->me_hash = hash;
1044 if (mp->ma_values) {
1045 assert (mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
1046 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001047 }
1048 else {
Victor Stinner742da042016-09-07 17:40:12 -07001049 ep->me_value = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001050 }
1051 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001052 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07001053 mp->ma_keys->dk_usable--;
1054 mp->ma_keys->dk_nentries++;
1055 assert(mp->ma_keys->dk_usable >= 0);
Victor Stinner611b0fa2016-09-14 15:02:01 +02001056 assert(_PyDict_CheckConsistency(mp));
Victor Stinner742da042016-09-07 17:40:12 -07001057 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001058 }
Victor Stinner742da042016-09-07 17:40:12 -07001059
INADA Naokiba609772016-12-07 20:41:42 +09001060 if (_PyDict_HasSplitTable(mp)) {
1061 mp->ma_values[ix] = value;
1062 if (old_value == NULL) {
1063 /* pending state */
1064 assert(ix == mp->ma_used);
1065 mp->ma_used++;
1066 }
1067 }
1068 else {
1069 assert(old_value != NULL);
1070 DK_ENTRIES(mp->ma_keys)[ix].me_value = value;
Victor Stinner742da042016-09-07 17:40:12 -07001071 }
1072
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001073 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naokiba609772016-12-07 20:41:42 +09001074 Py_XDECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
Victor Stinner611b0fa2016-09-14 15:02:01 +02001075 assert(_PyDict_CheckConsistency(mp));
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001076 Py_DECREF(key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001077 return 0;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001078
1079Fail:
1080 Py_DECREF(value);
1081 Py_DECREF(key);
1082 return -1;
Antoine Pitroue965d972012-02-27 00:45:12 +01001083}
1084
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001085/*
luzpaza5293b42017-11-05 07:37:50 -06001086Internal routine used by dictresize() to build a hashtable of entries.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001087*/
1088static void
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001089build_indices(PyDictKeysObject *keys, PyDictKeyEntry *ep, Py_ssize_t n)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001090{
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001091 size_t mask = (size_t)DK_SIZE(keys) - 1;
1092 for (Py_ssize_t ix = 0; ix != n; ix++, ep++) {
1093 Py_hash_t hash = ep->me_hash;
1094 size_t i = hash & mask;
1095 for (size_t perturb = hash; dk_get_index(keys, i) != DKIX_EMPTY;) {
1096 perturb >>= PERTURB_SHIFT;
INADA Naoki870c2862017-06-24 09:03:19 +09001097 i = mask & (i*5 + perturb + 1);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001098 }
1099 dk_set_index(keys, i, ix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001101}
1102
1103/*
1104Restructure the table by allocating a new table and reinserting all
1105items again. When entries have been deleted, the new table may
1106actually be smaller than the old one.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001107If a table is split (its keys and hashes are shared, its values are not),
1108then the values are temporarily copied into the table, it is resized as
1109a combined table, then the me_value slots in the old table are NULLed out.
1110After resizing a table is always combined,
1111but can be resplit by make_keys_shared().
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001112*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001113static int
Victor Stinner3d3f2642016-12-15 17:21:23 +01001114dictresize(PyDictObject *mp, Py_ssize_t minsize)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001115{
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001116 Py_ssize_t newsize, numentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001117 PyDictKeysObject *oldkeys;
1118 PyObject **oldvalues;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001119 PyDictKeyEntry *oldentries, *newentries;
Tim Peters91a364d2001-05-19 07:04:38 +00001120
Victor Stinner742da042016-09-07 17:40:12 -07001121 /* Find the smallest table size > minused. */
1122 for (newsize = PyDict_MINSIZE;
Victor Stinner3d3f2642016-12-15 17:21:23 +01001123 newsize < minsize && newsize > 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 newsize <<= 1)
1125 ;
1126 if (newsize <= 0) {
1127 PyErr_NoMemory();
1128 return -1;
1129 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001130
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001131 oldkeys = mp->ma_keys;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001132
1133 /* NOTE: Current odict checks mp->ma_keys to detect resize happen.
1134 * So we can't reuse oldkeys even if oldkeys->dk_size == newsize.
1135 * TODO: Try reusing oldkeys when reimplement odict.
1136 */
1137
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001138 /* Allocate a new table. */
1139 mp->ma_keys = new_keys_object(newsize);
1140 if (mp->ma_keys == NULL) {
1141 mp->ma_keys = oldkeys;
1142 return -1;
1143 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01001144 // New table must be large enough.
1145 assert(mp->ma_keys->dk_usable >= mp->ma_used);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001146 if (oldkeys->dk_lookup == lookdict)
1147 mp->ma_keys->dk_lookup = lookdict;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001148
1149 numentries = mp->ma_used;
1150 oldentries = DK_ENTRIES(oldkeys);
1151 newentries = DK_ENTRIES(mp->ma_keys);
1152 oldvalues = mp->ma_values;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001153 if (oldvalues != NULL) {
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001154 /* Convert split table into new combined table.
1155 * We must incref keys; we can transfer values.
1156 * Note that values of split table is always dense.
1157 */
1158 for (Py_ssize_t i = 0; i < numentries; i++) {
1159 assert(oldvalues[i] != NULL);
1160 PyDictKeyEntry *ep = &oldentries[i];
1161 PyObject *key = ep->me_key;
1162 Py_INCREF(key);
1163 newentries[i].me_key = key;
1164 newentries[i].me_hash = ep->me_hash;
1165 newentries[i].me_value = oldvalues[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001167
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001168 DK_DECREF(oldkeys);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001169 mp->ma_values = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001170 if (oldvalues != empty_values) {
1171 free_values(oldvalues);
1172 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001173 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001174 else { // combined table.
1175 if (oldkeys->dk_nentries == numentries) {
1176 memcpy(newentries, oldentries, numentries * sizeof(PyDictKeyEntry));
1177 }
1178 else {
1179 PyDictKeyEntry *ep = oldentries;
1180 for (Py_ssize_t i = 0; i < numentries; i++) {
1181 while (ep->me_value == NULL)
1182 ep++;
1183 newentries[i] = *ep++;
1184 }
1185 }
1186
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001187 assert(oldkeys->dk_lookup != lookdict_split);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001188 assert(oldkeys->dk_refcnt == 1);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001189 if (oldkeys->dk_size == PyDict_MINSIZE &&
1190 numfreekeys < PyDict_MAXFREELIST) {
1191 DK_DEBUG_DECREF keys_free_list[numfreekeys++] = oldkeys;
1192 }
1193 else {
1194 DK_DEBUG_DECREF PyObject_FREE(oldkeys);
1195 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001196 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001197
1198 build_indices(mp->ma_keys, newentries, numentries);
1199 mp->ma_keys->dk_usable -= numentries;
1200 mp->ma_keys->dk_nentries = numentries;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001202}
1203
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001204/* Returns NULL if unable to split table.
1205 * A NULL return does not necessarily indicate an error */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001206static PyDictKeysObject *
1207make_keys_shared(PyObject *op)
1208{
1209 Py_ssize_t i;
1210 Py_ssize_t size;
1211 PyDictObject *mp = (PyDictObject *)op;
1212
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001213 if (!PyDict_CheckExact(op))
1214 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001215 if (!_PyDict_HasSplitTable(mp)) {
1216 PyDictKeyEntry *ep0;
1217 PyObject **values;
1218 assert(mp->ma_keys->dk_refcnt == 1);
1219 if (mp->ma_keys->dk_lookup == lookdict) {
1220 return NULL;
1221 }
1222 else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
1223 /* Remove dummy keys */
1224 if (dictresize(mp, DK_SIZE(mp->ma_keys)))
1225 return NULL;
1226 }
1227 assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
1228 /* Copy values into a new array */
Victor Stinner742da042016-09-07 17:40:12 -07001229 ep0 = DK_ENTRIES(mp->ma_keys);
1230 size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001231 values = new_values(size);
1232 if (values == NULL) {
1233 PyErr_SetString(PyExc_MemoryError,
1234 "Not enough memory to allocate new values array");
1235 return NULL;
1236 }
1237 for (i = 0; i < size; i++) {
1238 values[i] = ep0[i].me_value;
1239 ep0[i].me_value = NULL;
1240 }
1241 mp->ma_keys->dk_lookup = lookdict_split;
1242 mp->ma_values = values;
1243 }
1244 DK_INCREF(mp->ma_keys);
1245 return mp->ma_keys;
1246}
Christian Heimes99170a52007-12-19 02:07:34 +00001247
1248PyObject *
1249_PyDict_NewPresized(Py_ssize_t minused)
1250{
INADA Naoki92c50ee2016-11-22 00:57:02 +09001251 const Py_ssize_t max_presize = 128 * 1024;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001252 Py_ssize_t newsize;
1253 PyDictKeysObject *new_keys;
INADA Naoki92c50ee2016-11-22 00:57:02 +09001254
1255 /* There are no strict guarantee that returned dict can contain minused
1256 * items without resize. So we create medium size dict instead of very
1257 * large dict or MemoryError.
1258 */
1259 if (minused > USABLE_FRACTION(max_presize)) {
1260 newsize = max_presize;
1261 }
1262 else {
1263 Py_ssize_t minsize = ESTIMATE_SIZE(minused);
1264 newsize = PyDict_MINSIZE;
1265 while (newsize < minsize) {
1266 newsize <<= 1;
1267 }
1268 }
1269 assert(IS_POWER_OF_2(newsize));
1270
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001271 new_keys = new_keys_object(newsize);
1272 if (new_keys == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001274 return new_dict(new_keys, NULL);
Christian Heimes99170a52007-12-19 02:07:34 +00001275}
1276
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001277/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
1278 * that may occur (originally dicts supported only string keys, and exceptions
1279 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001280 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001281 * (suppressed) occurred while computing the key's hash, or that some error
1282 * (suppressed) occurred when comparing keys in the dict's internal probe
1283 * sequence. A nasty example of the latter is when a Python-coded comparison
1284 * function hits a stack-depth error, which can cause this to return NULL
1285 * even if the key is present.
1286 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001287PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001288PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001289{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001290 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001291 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 PyDictObject *mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 PyThreadState *tstate;
INADA Naokiba609772016-12-07 20:41:42 +09001294 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 if (!PyDict_Check(op))
1297 return NULL;
1298 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001299 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 {
1301 hash = PyObject_Hash(key);
1302 if (hash == -1) {
1303 PyErr_Clear();
1304 return NULL;
1305 }
1306 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 /* We can arrive here with a NULL tstate during initialization: try
1309 running "python -Wi" for an example related to string interning.
1310 Let's just hope that no exception occurs then... This must be
1311 _PyThreadState_Current and not PyThreadState_GET() because in debug
1312 mode, the latter complains if tstate is NULL. */
Victor Stinner0cae6092016-11-11 01:43:56 +01001313 tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 if (tstate != NULL && tstate->curexc_type != NULL) {
1315 /* preserve the existing exception */
1316 PyObject *err_type, *err_value, *err_tb;
1317 PyErr_Fetch(&err_type, &err_value, &err_tb);
INADA Naoki778928b2017-08-03 23:45:15 +09001318 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 /* ignore errors */
1320 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001321 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 return NULL;
1323 }
1324 else {
INADA Naoki778928b2017-08-03 23:45:15 +09001325 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001326 if (ix < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 PyErr_Clear();
1328 return NULL;
1329 }
1330 }
INADA Naokiba609772016-12-07 20:41:42 +09001331 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001332}
1333
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001334/* Same as PyDict_GetItemWithError() but with hash supplied by caller.
1335 This returns NULL *with* an exception set if an exception occurred.
1336 It returns NULL *without* an exception set if the key wasn't present.
1337*/
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001338PyObject *
1339_PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1340{
Victor Stinner742da042016-09-07 17:40:12 -07001341 Py_ssize_t ix;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001342 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001343 PyObject *value;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001344
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001345 if (!PyDict_Check(op)) {
1346 PyErr_BadInternalCall();
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001347 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001348 }
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001349
INADA Naoki778928b2017-08-03 23:45:15 +09001350 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001351 if (ix < 0) {
1352 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001353 }
INADA Naokiba609772016-12-07 20:41:42 +09001354 return value;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001355}
1356
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001357/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
1358 This returns NULL *with* an exception set if an exception occurred.
1359 It returns NULL *without* an exception set if the key wasn't present.
1360*/
1361PyObject *
1362PyDict_GetItemWithError(PyObject *op, PyObject *key)
1363{
Victor Stinner742da042016-09-07 17:40:12 -07001364 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001365 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 PyDictObject*mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001367 PyObject *value;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 if (!PyDict_Check(op)) {
1370 PyErr_BadInternalCall();
1371 return NULL;
1372 }
1373 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001374 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 {
1376 hash = PyObject_Hash(key);
1377 if (hash == -1) {
1378 return NULL;
1379 }
1380 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001381
INADA Naoki778928b2017-08-03 23:45:15 +09001382 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001383 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001385 return value;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001386}
1387
Brett Cannonfd074152012-04-14 14:10:13 -04001388PyObject *
1389_PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
1390{
1391 PyObject *kv;
1392 kv = _PyUnicode_FromId(key); /* borrowed */
1393 if (kv == NULL)
1394 return NULL;
1395 return PyDict_GetItemWithError(dp, kv);
1396}
1397
Victor Stinnerb4efc962015-11-20 09:24:02 +01001398/* Fast version of global value lookup (LOAD_GLOBAL).
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001399 * Lookup in globals, then builtins.
Victor Stinnerb4efc962015-11-20 09:24:02 +01001400 *
1401 * Raise an exception and return NULL if an error occurred (ex: computing the
1402 * key hash failed, key comparison failed, ...). Return NULL if the key doesn't
1403 * exist. Return the value if the key exists.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001404 */
1405PyObject *
1406_PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001407{
Victor Stinner742da042016-09-07 17:40:12 -07001408 Py_ssize_t ix;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001409 Py_hash_t hash;
INADA Naokiba609772016-12-07 20:41:42 +09001410 PyObject *value;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001411
1412 if (!PyUnicode_CheckExact(key) ||
1413 (hash = ((PyASCIIObject *) key)->hash) == -1)
1414 {
1415 hash = PyObject_Hash(key);
1416 if (hash == -1)
1417 return NULL;
Antoine Pitroue965d972012-02-27 00:45:12 +01001418 }
Victor Stinnerb4efc962015-11-20 09:24:02 +01001419
1420 /* namespace 1: globals */
INADA Naoki778928b2017-08-03 23:45:15 +09001421 ix = globals->ma_keys->dk_lookup(globals, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001422 if (ix == DKIX_ERROR)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001423 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001424 if (ix != DKIX_EMPTY && value != NULL)
1425 return value;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001426
1427 /* namespace 2: builtins */
INADA Naoki778928b2017-08-03 23:45:15 +09001428 ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001429 if (ix < 0)
Victor Stinnerb4efc962015-11-20 09:24:02 +01001430 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001431 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001432}
1433
Antoine Pitroue965d972012-02-27 00:45:12 +01001434/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
1435 * dictionary if it's merely replacing the value for an existing key.
1436 * This means that it's safe to loop over a dictionary with PyDict_Next()
1437 * and occasionally replace a value -- but you can't insert new keys or
1438 * remove them.
1439 */
1440int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001441PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001442{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001443 PyDictObject *mp;
1444 Py_hash_t hash;
Antoine Pitroue965d972012-02-27 00:45:12 +01001445 if (!PyDict_Check(op)) {
1446 PyErr_BadInternalCall();
1447 return -1;
1448 }
1449 assert(key);
1450 assert(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001451 mp = (PyDictObject *)op;
1452 if (!PyUnicode_CheckExact(key) ||
1453 (hash = ((PyASCIIObject *) key)->hash) == -1)
1454 {
Antoine Pitroue965d972012-02-27 00:45:12 +01001455 hash = PyObject_Hash(key);
1456 if (hash == -1)
1457 return -1;
1458 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001459
1460 /* insertdict() handles any resizing that might be necessary */
1461 return insertdict(mp, key, hash, value);
Antoine Pitroue965d972012-02-27 00:45:12 +01001462}
1463
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001464int
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001465_PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
1466 Py_hash_t hash)
1467{
1468 PyDictObject *mp;
1469
1470 if (!PyDict_Check(op)) {
1471 PyErr_BadInternalCall();
1472 return -1;
1473 }
1474 assert(key);
1475 assert(value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001476 assert(hash != -1);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001477 mp = (PyDictObject *)op;
1478
1479 /* insertdict() handles any resizing that might be necessary */
1480 return insertdict(mp, key, hash, value);
1481}
1482
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001483static int
INADA Naoki778928b2017-08-03 23:45:15 +09001484delitem_common(PyDictObject *mp, Py_hash_t hash, Py_ssize_t ix,
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001485 PyObject *old_value)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001486{
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001487 PyObject *old_key;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001488 PyDictKeyEntry *ep;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001489
INADA Naoki778928b2017-08-03 23:45:15 +09001490 Py_ssize_t hashpos = lookdict_index(mp->ma_keys, hash, ix);
1491 assert(hashpos >= 0);
1492
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001493 mp->ma_used--;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001494 mp->ma_version_tag = DICT_NEXT_VERSION();
1495 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1496 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1497 ENSURE_ALLOWS_DELETIONS(mp);
1498 old_key = ep->me_key;
1499 ep->me_key = NULL;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001500 ep->me_value = NULL;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001501 Py_DECREF(old_key);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001502 Py_DECREF(old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001503
1504 assert(_PyDict_CheckConsistency(mp));
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001505 return 0;
1506}
1507
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001508int
Tim Peters1f5871e2000-07-04 17:44:48 +00001509PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001510{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001511 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 assert(key);
1513 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001514 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 hash = PyObject_Hash(key);
1516 if (hash == -1)
1517 return -1;
1518 }
Victor Stinner742da042016-09-07 17:40:12 -07001519
1520 return _PyDict_DelItem_KnownHash(op, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001521}
1522
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001523int
1524_PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1525{
INADA Naoki778928b2017-08-03 23:45:15 +09001526 Py_ssize_t ix;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001527 PyDictObject *mp;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001528 PyObject *old_value;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001529
1530 if (!PyDict_Check(op)) {
1531 PyErr_BadInternalCall();
1532 return -1;
1533 }
1534 assert(key);
1535 assert(hash != -1);
1536 mp = (PyDictObject *)op;
INADA Naoki778928b2017-08-03 23:45:15 +09001537 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner742da042016-09-07 17:40:12 -07001538 if (ix == DKIX_ERROR)
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001539 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09001540 if (ix == DKIX_EMPTY || old_value == NULL) {
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001541 _PyErr_SetKeyError(key);
1542 return -1;
1543 }
Victor Stinner78601a32016-09-09 19:28:36 -07001544
1545 // Split table doesn't allow deletion. Combine it.
1546 if (_PyDict_HasSplitTable(mp)) {
1547 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1548 return -1;
1549 }
INADA Naoki778928b2017-08-03 23:45:15 +09001550 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner78601a32016-09-09 19:28:36 -07001551 assert(ix >= 0);
1552 }
1553
INADA Naoki778928b2017-08-03 23:45:15 +09001554 return delitem_common(mp, hash, ix, old_value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001555}
1556
Antoine Pitroud741ed42016-12-27 14:23:43 +01001557/* This function promises that the predicate -> deletion sequence is atomic
1558 * (i.e. protected by the GIL), assuming the predicate itself doesn't
1559 * release the GIL.
1560 */
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001561int
1562_PyDict_DelItemIf(PyObject *op, PyObject *key,
1563 int (*predicate)(PyObject *value))
1564{
Antoine Pitroud741ed42016-12-27 14:23:43 +01001565 Py_ssize_t hashpos, ix;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001566 PyDictObject *mp;
1567 Py_hash_t hash;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001568 PyObject *old_value;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001569 int res;
1570
1571 if (!PyDict_Check(op)) {
1572 PyErr_BadInternalCall();
1573 return -1;
1574 }
1575 assert(key);
1576 hash = PyObject_Hash(key);
1577 if (hash == -1)
1578 return -1;
1579 mp = (PyDictObject *)op;
INADA Naoki778928b2017-08-03 23:45:15 +09001580 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001581 if (ix == DKIX_ERROR)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001582 return -1;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001583 if (ix == DKIX_EMPTY || old_value == NULL) {
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001584 _PyErr_SetKeyError(key);
1585 return -1;
1586 }
Antoine Pitroud741ed42016-12-27 14:23:43 +01001587
1588 // Split table doesn't allow deletion. Combine it.
1589 if (_PyDict_HasSplitTable(mp)) {
1590 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1591 return -1;
1592 }
INADA Naoki778928b2017-08-03 23:45:15 +09001593 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001594 assert(ix >= 0);
1595 }
1596
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001597 res = predicate(old_value);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001598 if (res == -1)
1599 return -1;
INADA Naoki778928b2017-08-03 23:45:15 +09001600
1601 hashpos = lookdict_index(mp->ma_keys, hash, ix);
1602 assert(hashpos >= 0);
1603
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001604 if (res > 0)
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001605 return delitem_common(mp, hashpos, ix, old_value);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001606 else
1607 return 0;
1608}
1609
1610
Guido van Rossum25831651993-05-19 14:50:45 +00001611void
Tim Peters1f5871e2000-07-04 17:44:48 +00001612PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 PyDictObject *mp;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001615 PyDictKeysObject *oldkeys;
1616 PyObject **oldvalues;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 if (!PyDict_Check(op))
1620 return;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001621 mp = ((PyDictObject *)op);
1622 oldkeys = mp->ma_keys;
1623 oldvalues = mp->ma_values;
1624 if (oldvalues == empty_values)
1625 return;
1626 /* Empty the dict... */
1627 DK_INCREF(Py_EMPTY_KEYS);
1628 mp->ma_keys = Py_EMPTY_KEYS;
1629 mp->ma_values = empty_values;
1630 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001631 mp->ma_version_tag = DICT_NEXT_VERSION();
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001632 /* ...then clear the keys and values */
1633 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001634 n = oldkeys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001635 for (i = 0; i < n; i++)
1636 Py_CLEAR(oldvalues[i]);
1637 free_values(oldvalues);
1638 DK_DECREF(oldkeys);
1639 }
1640 else {
1641 assert(oldkeys->dk_refcnt == 1);
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001642 DK_DECREF(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001643 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02001644 assert(_PyDict_CheckConsistency(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001645}
1646
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001647/* Internal version of PyDict_Next that returns a hash value in addition
1648 * to the key and value.
1649 * Return 1 on success, return 0 when the reached the end of the dictionary
1650 * (or if op is not a dictionary)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001651 */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001652int
1653_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
1654 PyObject **pvalue, Py_hash_t *phash)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001655{
INADA Naokica2d8be2016-11-04 16:59:10 +09001656 Py_ssize_t i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001657 PyDictObject *mp;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001658 PyDictKeyEntry *entry_ptr;
1659 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001660
1661 if (!PyDict_Check(op))
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001662 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 mp = (PyDictObject *)op;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001664 i = *ppos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001665 if (mp->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09001666 if (i < 0 || i >= mp->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001667 return 0;
INADA Naokica2d8be2016-11-04 16:59:10 +09001668 /* values of split table is always dense */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001669 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
INADA Naokica2d8be2016-11-04 16:59:10 +09001670 value = mp->ma_values[i];
1671 assert(value != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001673 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09001674 Py_ssize_t n = mp->ma_keys->dk_nentries;
1675 if (i < 0 || i >= n)
1676 return 0;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001677 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
1678 while (i < n && entry_ptr->me_value == NULL) {
1679 entry_ptr++;
1680 i++;
Victor Stinner742da042016-09-07 17:40:12 -07001681 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001682 if (i >= n)
1683 return 0;
1684 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001686 *ppos = i+1;
1687 if (pkey)
1688 *pkey = entry_ptr->me_key;
1689 if (phash)
1690 *phash = entry_ptr->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001691 if (pvalue)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001692 *pvalue = value;
1693 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001694}
1695
Tim Peters080c88b2003-02-15 03:01:11 +00001696/*
1697 * Iterate over a dict. Use like so:
1698 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001699 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +00001700 * PyObject *key, *value;
1701 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +00001702 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001703 * Refer to borrowed references in key and value.
Tim Peters080c88b2003-02-15 03:01:11 +00001704 * }
1705 *
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001706 * Return 1 on success, return 0 when the reached the end of the dictionary
1707 * (or if op is not a dictionary)
1708 *
Tim Peters080c88b2003-02-15 03:01:11 +00001709 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +00001710 * mutates the dict. One exception: it is safe if the loop merely changes
1711 * the values associated with the keys (but doesn't insert new keys or
1712 * delete keys), via PyDict_SetItem().
1713 */
Guido van Rossum25831651993-05-19 14:50:45 +00001714int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001715PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001716{
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001717 return _PyDict_Next(op, ppos, pkey, pvalue, NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00001718}
1719
Eric Snow96c6af92015-05-29 22:21:39 -06001720/* Internal version of dict.pop(). */
1721PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001722_PyDict_Pop_KnownHash(PyObject *dict, PyObject *key, Py_hash_t hash, PyObject *deflt)
Eric Snow96c6af92015-05-29 22:21:39 -06001723{
Victor Stinner742da042016-09-07 17:40:12 -07001724 Py_ssize_t ix, hashpos;
Eric Snow96c6af92015-05-29 22:21:39 -06001725 PyObject *old_value, *old_key;
1726 PyDictKeyEntry *ep;
Yury Selivanov684ef2c2016-10-28 19:01:21 -04001727 PyDictObject *mp;
1728
1729 assert(PyDict_Check(dict));
1730 mp = (PyDictObject *)dict;
Eric Snow96c6af92015-05-29 22:21:39 -06001731
1732 if (mp->ma_used == 0) {
1733 if (deflt) {
1734 Py_INCREF(deflt);
1735 return deflt;
1736 }
1737 _PyErr_SetKeyError(key);
1738 return NULL;
1739 }
INADA Naoki778928b2017-08-03 23:45:15 +09001740 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner742da042016-09-07 17:40:12 -07001741 if (ix == DKIX_ERROR)
Eric Snow96c6af92015-05-29 22:21:39 -06001742 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001743 if (ix == DKIX_EMPTY || old_value == NULL) {
Eric Snow96c6af92015-05-29 22:21:39 -06001744 if (deflt) {
1745 Py_INCREF(deflt);
1746 return deflt;
1747 }
1748 _PyErr_SetKeyError(key);
1749 return NULL;
1750 }
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001751
Victor Stinner78601a32016-09-09 19:28:36 -07001752 // Split table doesn't allow deletion. Combine it.
1753 if (_PyDict_HasSplitTable(mp)) {
1754 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1755 return NULL;
1756 }
INADA Naoki778928b2017-08-03 23:45:15 +09001757 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner78601a32016-09-09 19:28:36 -07001758 assert(ix >= 0);
1759 }
1760
INADA Naoki778928b2017-08-03 23:45:15 +09001761 hashpos = lookdict_index(mp->ma_keys, hash, ix);
1762 assert(hashpos >= 0);
Victor Stinner78601a32016-09-09 19:28:36 -07001763 assert(old_value != NULL);
Eric Snow96c6af92015-05-29 22:21:39 -06001764 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001765 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner78601a32016-09-09 19:28:36 -07001766 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1767 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1768 ENSURE_ALLOWS_DELETIONS(mp);
1769 old_key = ep->me_key;
1770 ep->me_key = NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001771 ep->me_value = NULL;
Victor Stinner78601a32016-09-09 19:28:36 -07001772 Py_DECREF(old_key);
Victor Stinner611b0fa2016-09-14 15:02:01 +02001773
1774 assert(_PyDict_CheckConsistency(mp));
Eric Snow96c6af92015-05-29 22:21:39 -06001775 return old_value;
1776}
1777
Serhiy Storchaka67796522017-01-12 18:34:33 +02001778PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001779_PyDict_Pop(PyObject *dict, PyObject *key, PyObject *deflt)
Serhiy Storchaka67796522017-01-12 18:34:33 +02001780{
1781 Py_hash_t hash;
1782
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001783 if (((PyDictObject *)dict)->ma_used == 0) {
Serhiy Storchaka67796522017-01-12 18:34:33 +02001784 if (deflt) {
1785 Py_INCREF(deflt);
1786 return deflt;
1787 }
1788 _PyErr_SetKeyError(key);
1789 return NULL;
1790 }
1791 if (!PyUnicode_CheckExact(key) ||
1792 (hash = ((PyASCIIObject *) key)->hash) == -1) {
1793 hash = PyObject_Hash(key);
1794 if (hash == -1)
1795 return NULL;
1796 }
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001797 return _PyDict_Pop_KnownHash(dict, key, hash, deflt);
Serhiy Storchaka67796522017-01-12 18:34:33 +02001798}
1799
Eric Snow96c6af92015-05-29 22:21:39 -06001800/* Internal version of dict.from_keys(). It is subclass-friendly. */
1801PyObject *
1802_PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
1803{
1804 PyObject *it; /* iter(iterable) */
1805 PyObject *key;
1806 PyObject *d;
1807 int status;
1808
Victor Stinnera5ed5f02016-12-06 18:45:50 +01001809 d = _PyObject_CallNoArg(cls);
Eric Snow96c6af92015-05-29 22:21:39 -06001810 if (d == NULL)
1811 return NULL;
1812
1813 if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
1814 if (PyDict_CheckExact(iterable)) {
1815 PyDictObject *mp = (PyDictObject *)d;
1816 PyObject *oldvalue;
1817 Py_ssize_t pos = 0;
1818 PyObject *key;
1819 Py_hash_t hash;
1820
Serhiy Storchakac61ac162017-03-21 08:52:38 +02001821 if (dictresize(mp, ESTIMATE_SIZE(PyDict_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001822 Py_DECREF(d);
1823 return NULL;
1824 }
1825
1826 while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
1827 if (insertdict(mp, key, hash, value)) {
1828 Py_DECREF(d);
1829 return NULL;
1830 }
1831 }
1832 return d;
1833 }
1834 if (PyAnySet_CheckExact(iterable)) {
1835 PyDictObject *mp = (PyDictObject *)d;
1836 Py_ssize_t pos = 0;
1837 PyObject *key;
1838 Py_hash_t hash;
1839
Victor Stinner742da042016-09-07 17:40:12 -07001840 if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001841 Py_DECREF(d);
1842 return NULL;
1843 }
1844
1845 while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
1846 if (insertdict(mp, key, hash, value)) {
1847 Py_DECREF(d);
1848 return NULL;
1849 }
1850 }
1851 return d;
1852 }
1853 }
1854
1855 it = PyObject_GetIter(iterable);
1856 if (it == NULL){
1857 Py_DECREF(d);
1858 return NULL;
1859 }
1860
1861 if (PyDict_CheckExact(d)) {
1862 while ((key = PyIter_Next(it)) != NULL) {
1863 status = PyDict_SetItem(d, key, value);
1864 Py_DECREF(key);
1865 if (status < 0)
1866 goto Fail;
1867 }
1868 } else {
1869 while ((key = PyIter_Next(it)) != NULL) {
1870 status = PyObject_SetItem(d, key, value);
1871 Py_DECREF(key);
1872 if (status < 0)
1873 goto Fail;
1874 }
1875 }
1876
1877 if (PyErr_Occurred())
1878 goto Fail;
1879 Py_DECREF(it);
1880 return d;
1881
1882Fail:
1883 Py_DECREF(it);
1884 Py_DECREF(d);
1885 return NULL;
1886}
1887
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001888/* Methods */
1889
1890static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001891dict_dealloc(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001892{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001893 PyObject **values = mp->ma_values;
1894 PyDictKeysObject *keys = mp->ma_keys;
1895 Py_ssize_t i, n;
INADA Naokia6296d32017-08-24 14:55:17 +09001896
1897 /* bpo-31095: UnTrack is needed before calling any callbacks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 PyObject_GC_UnTrack(mp);
1899 Py_TRASHCAN_SAFE_BEGIN(mp)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001900 if (values != NULL) {
1901 if (values != empty_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001902 for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001903 Py_XDECREF(values[i]);
1904 }
1905 free_values(values);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001907 DK_DECREF(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 }
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02001909 else if (keys != NULL) {
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001910 assert(keys->dk_refcnt == 1);
1911 DK_DECREF(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001912 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
1914 free_list[numfree++] = mp;
1915 else
1916 Py_TYPE(mp)->tp_free((PyObject *)mp);
1917 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001918}
1919
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001920
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001921static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001922dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 Py_ssize_t i;
Victor Stinnerf91929b2013-11-19 13:07:38 +01001925 PyObject *key = NULL, *value = NULL;
1926 _PyUnicodeWriter writer;
1927 int first;
Guido van Rossum255443b1998-04-10 22:47:14 +00001928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 i = Py_ReprEnter((PyObject *)mp);
1930 if (i != 0) {
1931 return i > 0 ? PyUnicode_FromString("{...}") : NULL;
1932 }
Guido van Rossum255443b1998-04-10 22:47:14 +00001933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 if (mp->ma_used == 0) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01001935 Py_ReprLeave((PyObject *)mp);
1936 return PyUnicode_FromString("{}");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 }
Tim Petersa7259592001-06-16 05:11:17 +00001938
Victor Stinnerf91929b2013-11-19 13:07:38 +01001939 _PyUnicodeWriter_Init(&writer);
1940 writer.overallocate = 1;
1941 /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
1942 writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +00001943
Victor Stinnerf91929b2013-11-19 13:07:38 +01001944 if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
1945 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00001946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 /* Do repr() on each key+value pair, and insert ": " between them.
1948 Note that repr may mutate the dict. */
1949 i = 0;
Victor Stinnerf91929b2013-11-19 13:07:38 +01001950 first = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01001952 PyObject *s;
1953 int res;
1954
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001955 /* Prevent repr from deleting key or value during key format. */
1956 Py_INCREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 Py_INCREF(value);
Victor Stinnerf97dfd72013-07-18 01:00:45 +02001958
Victor Stinnerf91929b2013-11-19 13:07:38 +01001959 if (!first) {
1960 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
1961 goto error;
1962 }
1963 first = 0;
1964
1965 s = PyObject_Repr(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 if (s == NULL)
Victor Stinnerf91929b2013-11-19 13:07:38 +01001967 goto error;
1968 res = _PyUnicodeWriter_WriteStr(&writer, s);
1969 Py_DECREF(s);
1970 if (res < 0)
1971 goto error;
1972
1973 if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
1974 goto error;
1975
1976 s = PyObject_Repr(value);
1977 if (s == NULL)
1978 goto error;
1979 res = _PyUnicodeWriter_WriteStr(&writer, s);
1980 Py_DECREF(s);
1981 if (res < 0)
1982 goto error;
1983
1984 Py_CLEAR(key);
1985 Py_CLEAR(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 }
Tim Petersa7259592001-06-16 05:11:17 +00001987
Victor Stinnerf91929b2013-11-19 13:07:38 +01001988 writer.overallocate = 0;
1989 if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
1990 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00001991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 Py_ReprLeave((PyObject *)mp);
Victor Stinnerf91929b2013-11-19 13:07:38 +01001993
1994 return _PyUnicodeWriter_Finish(&writer);
1995
1996error:
1997 Py_ReprLeave((PyObject *)mp);
1998 _PyUnicodeWriter_Dealloc(&writer);
1999 Py_XDECREF(key);
2000 Py_XDECREF(value);
2001 return NULL;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002002}
2003
Martin v. Löwis18e16552006-02-15 17:27:45 +00002004static Py_ssize_t
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002005dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 return mp->ma_used;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002008}
2009
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002010static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002011dict_subscript(PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002012{
Victor Stinner742da042016-09-07 17:40:12 -07002013 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002014 Py_hash_t hash;
INADA Naokiba609772016-12-07 20:41:42 +09002015 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002018 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 hash = PyObject_Hash(key);
2020 if (hash == -1)
2021 return NULL;
2022 }
INADA Naoki778928b2017-08-03 23:45:15 +09002023 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002024 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002026 if (ix == DKIX_EMPTY || value == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 if (!PyDict_CheckExact(mp)) {
2028 /* Look up __missing__ method if we're a subclass. */
2029 PyObject *missing, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05002030 _Py_IDENTIFIER(__missing__);
2031 missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 if (missing != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002033 res = PyObject_CallFunctionObjArgs(missing,
2034 key, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 Py_DECREF(missing);
2036 return res;
2037 }
2038 else if (PyErr_Occurred())
2039 return NULL;
2040 }
Raymond Hettinger69492da2013-09-02 15:59:26 -07002041 _PyErr_SetKeyError(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 return NULL;
2043 }
INADA Naokiba609772016-12-07 20:41:42 +09002044 Py_INCREF(value);
2045 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002046}
2047
2048static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002049dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 if (w == NULL)
2052 return PyDict_DelItem((PyObject *)mp, v);
2053 else
2054 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002055}
2056
Guido van Rossuma9e7a811997-05-13 21:02:11 +00002057static PyMappingMethods dict_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 (lenfunc)dict_length, /*mp_length*/
2059 (binaryfunc)dict_subscript, /*mp_subscript*/
2060 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002061};
2062
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002063static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002064dict_keys(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002065{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002066 PyObject *v;
2067 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002068 PyDictKeyEntry *ep;
2069 Py_ssize_t size, n, offset;
2070 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002071
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002072 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 n = mp->ma_used;
2074 v = PyList_New(n);
2075 if (v == NULL)
2076 return NULL;
2077 if (n != mp->ma_used) {
2078 /* Durnit. The allocations caused the dict to resize.
2079 * Just start over, this shouldn't normally happen.
2080 */
2081 Py_DECREF(v);
2082 goto again;
2083 }
Victor Stinner742da042016-09-07 17:40:12 -07002084 ep = DK_ENTRIES(mp->ma_keys);
2085 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002086 if (mp->ma_values) {
2087 value_ptr = mp->ma_values;
2088 offset = sizeof(PyObject *);
2089 }
2090 else {
2091 value_ptr = &ep[0].me_value;
2092 offset = sizeof(PyDictKeyEntry);
2093 }
2094 for (i = 0, j = 0; i < size; i++) {
2095 if (*value_ptr != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 PyObject *key = ep[i].me_key;
2097 Py_INCREF(key);
2098 PyList_SET_ITEM(v, j, key);
2099 j++;
2100 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002101 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 }
2103 assert(j == n);
2104 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002105}
2106
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002107static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002108dict_values(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002109{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002110 PyObject *v;
2111 Py_ssize_t i, j;
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002112 PyDictKeyEntry *ep;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002113 Py_ssize_t size, n, offset;
2114 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002115
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002116 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 n = mp->ma_used;
2118 v = PyList_New(n);
2119 if (v == NULL)
2120 return NULL;
2121 if (n != mp->ma_used) {
2122 /* Durnit. The allocations caused the dict to resize.
2123 * Just start over, this shouldn't normally happen.
2124 */
2125 Py_DECREF(v);
2126 goto again;
2127 }
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002128 ep = DK_ENTRIES(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002129 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002130 if (mp->ma_values) {
2131 value_ptr = mp->ma_values;
2132 offset = sizeof(PyObject *);
2133 }
2134 else {
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002135 value_ptr = &ep[0].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002136 offset = sizeof(PyDictKeyEntry);
2137 }
2138 for (i = 0, j = 0; i < size; i++) {
2139 PyObject *value = *value_ptr;
2140 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2141 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 Py_INCREF(value);
2143 PyList_SET_ITEM(v, j, value);
2144 j++;
2145 }
2146 }
2147 assert(j == n);
2148 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002149}
2150
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002151static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002152dict_items(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002153{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002154 PyObject *v;
2155 Py_ssize_t i, j, n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002156 Py_ssize_t size, offset;
2157 PyObject *item, *key;
2158 PyDictKeyEntry *ep;
2159 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 /* Preallocate the list of tuples, to avoid allocations during
2162 * the loop over the items, which could trigger GC, which
2163 * could resize the dict. :-(
2164 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002165 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 n = mp->ma_used;
2167 v = PyList_New(n);
2168 if (v == NULL)
2169 return NULL;
2170 for (i = 0; i < n; i++) {
2171 item = PyTuple_New(2);
2172 if (item == NULL) {
2173 Py_DECREF(v);
2174 return NULL;
2175 }
2176 PyList_SET_ITEM(v, i, item);
2177 }
2178 if (n != mp->ma_used) {
2179 /* Durnit. The allocations caused the dict to resize.
2180 * Just start over, this shouldn't normally happen.
2181 */
2182 Py_DECREF(v);
2183 goto again;
2184 }
2185 /* Nothing we do below makes any function calls. */
Victor Stinner742da042016-09-07 17:40:12 -07002186 ep = DK_ENTRIES(mp->ma_keys);
2187 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002188 if (mp->ma_values) {
2189 value_ptr = mp->ma_values;
2190 offset = sizeof(PyObject *);
2191 }
2192 else {
2193 value_ptr = &ep[0].me_value;
2194 offset = sizeof(PyDictKeyEntry);
2195 }
2196 for (i = 0, j = 0; i < size; i++) {
2197 PyObject *value = *value_ptr;
2198 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2199 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 key = ep[i].me_key;
2201 item = PyList_GET_ITEM(v, j);
2202 Py_INCREF(key);
2203 PyTuple_SET_ITEM(item, 0, key);
2204 Py_INCREF(value);
2205 PyTuple_SET_ITEM(item, 1, value);
2206 j++;
2207 }
2208 }
2209 assert(j == n);
2210 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002211}
2212
Larry Hastings5c661892014-01-24 06:17:25 -08002213/*[clinic input]
2214@classmethod
2215dict.fromkeys
Larry Hastings5c661892014-01-24 06:17:25 -08002216 iterable: object
2217 value: object=None
2218 /
2219
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002220Create a new dictionary with keys from iterable and values set to value.
Larry Hastings5c661892014-01-24 06:17:25 -08002221[clinic start generated code]*/
2222
Larry Hastings5c661892014-01-24 06:17:25 -08002223static PyObject *
2224dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002225/*[clinic end generated code: output=8fb98e4b10384999 input=382ba4855d0f74c3]*/
Larry Hastings5c661892014-01-24 06:17:25 -08002226{
Eric Snow96c6af92015-05-29 22:21:39 -06002227 return _PyDict_FromKeys((PyObject *)type, iterable, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002228}
2229
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002230static int
Victor Stinner742da042016-09-07 17:40:12 -07002231dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
2232 const char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 PyObject *arg = NULL;
2235 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002236
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002237 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 result = -1;
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002239 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 else if (arg != NULL) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02002241 _Py_IDENTIFIER(keys);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002242 PyObject *func;
2243 if (_PyObject_LookupAttrId(arg, &PyId_keys, &func) < 0) {
2244 result = -1;
2245 }
2246 else if (func != NULL) {
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002247 Py_DECREF(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 result = PyDict_Merge(self, arg, 1);
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002249 }
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002250 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002251 result = PyDict_MergeFromSeq2(self, arg, 1);
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002252 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 }
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 if (result == 0 && kwds != NULL) {
2256 if (PyArg_ValidateKeywordArguments(kwds))
2257 result = PyDict_Merge(self, kwds, 1);
2258 else
2259 result = -1;
2260 }
2261 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002262}
2263
Victor Stinner91f0d4a2017-01-19 12:45:06 +01002264/* Note: dict.update() uses the METH_VARARGS|METH_KEYWORDS calling convention.
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002265 Using METH_FASTCALL|METH_KEYWORDS would make dict.update(**dict2) calls
2266 slower, see the issue #29312. */
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002267static PyObject *
2268dict_update(PyObject *self, PyObject *args, PyObject *kwds)
2269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 if (dict_update_common(self, args, kwds, "update") != -1)
2271 Py_RETURN_NONE;
2272 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002273}
2274
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002275/* Update unconditionally replaces existing items.
2276 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00002277 otherwise it leaves existing items unchanged.
2278
2279 PyDict_{Update,Merge} update/merge from a mapping object.
2280
Tim Petersf582b822001-12-11 18:51:08 +00002281 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00002282 producing iterable objects of length 2.
2283*/
2284
Tim Petersf582b822001-12-11 18:51:08 +00002285int
Tim Peters1fc240e2001-10-26 05:06:50 +00002286PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
2287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 PyObject *it; /* iter(seq2) */
2289 Py_ssize_t i; /* index into seq2 of current element */
2290 PyObject *item; /* seq2[i] */
2291 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 assert(d != NULL);
2294 assert(PyDict_Check(d));
2295 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 it = PyObject_GetIter(seq2);
2298 if (it == NULL)
2299 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 for (i = 0; ; ++i) {
2302 PyObject *key, *value;
2303 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 fast = NULL;
2306 item = PyIter_Next(it);
2307 if (item == NULL) {
2308 if (PyErr_Occurred())
2309 goto Fail;
2310 break;
2311 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 /* Convert item to sequence, and verify length 2. */
2314 fast = PySequence_Fast(item, "");
2315 if (fast == NULL) {
2316 if (PyErr_ExceptionMatches(PyExc_TypeError))
2317 PyErr_Format(PyExc_TypeError,
2318 "cannot convert dictionary update "
2319 "sequence element #%zd to a sequence",
2320 i);
2321 goto Fail;
2322 }
2323 n = PySequence_Fast_GET_SIZE(fast);
2324 if (n != 2) {
2325 PyErr_Format(PyExc_ValueError,
2326 "dictionary update sequence element #%zd "
2327 "has length %zd; 2 is required",
2328 i, n);
2329 goto Fail;
2330 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 /* Update/merge with this (key, value) pair. */
2333 key = PySequence_Fast_GET_ITEM(fast, 0);
2334 value = PySequence_Fast_GET_ITEM(fast, 1);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002335 Py_INCREF(key);
2336 Py_INCREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 if (override || PyDict_GetItem(d, key) == NULL) {
2338 int status = PyDict_SetItem(d, key, value);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002339 if (status < 0) {
2340 Py_DECREF(key);
2341 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 goto Fail;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002343 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 }
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002345 Py_DECREF(key);
2346 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 Py_DECREF(fast);
2348 Py_DECREF(item);
2349 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 i = 0;
Victor Stinner611b0fa2016-09-14 15:02:01 +02002352 assert(_PyDict_CheckConsistency((PyDictObject *)d));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00002354Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 Py_XDECREF(item);
2356 Py_XDECREF(fast);
2357 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002358Return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 Py_DECREF(it);
2360 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00002361}
2362
doko@ubuntu.comc96df682016-10-11 08:04:02 +02002363static int
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002364dict_merge(PyObject *a, PyObject *b, int override)
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002365{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002366 PyDictObject *mp, *other;
2367 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -07002368 PyDictKeyEntry *entry, *ep0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002369
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002370 assert(0 <= override && override <= 2);
2371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 /* We accept for the argument either a concrete dictionary object,
2373 * or an abstract "mapping" object. For the former, we can do
2374 * things quite efficiently. For the latter, we only require that
2375 * PyMapping_Keys() and PyObject_GetItem() be supported.
2376 */
2377 if (a == NULL || !PyDict_Check(a) || b == NULL) {
2378 PyErr_BadInternalCall();
2379 return -1;
2380 }
2381 mp = (PyDictObject*)a;
2382 if (PyDict_Check(b)) {
2383 other = (PyDictObject*)b;
2384 if (other == mp || other->ma_used == 0)
2385 /* a.update(a) or a.update({}); nothing to do */
2386 return 0;
2387 if (mp->ma_used == 0)
2388 /* Since the target dict is empty, PyDict_GetItem()
2389 * always returns NULL. Setting override to 1
2390 * skips the unnecessary test.
2391 */
2392 override = 1;
2393 /* Do one big resize at the start, rather than
2394 * incrementally resizing as we insert new items. Expect
2395 * that there will be no (or few) overlapping keys.
2396 */
INADA Naokib1152be2016-10-27 19:26:50 +09002397 if (USABLE_FRACTION(mp->ma_keys->dk_size) < other->ma_used) {
2398 if (dictresize(mp, ESTIMATE_SIZE(mp->ma_used + other->ma_used))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 return -1;
INADA Naokib1152be2016-10-27 19:26:50 +09002400 }
2401 }
Victor Stinner742da042016-09-07 17:40:12 -07002402 ep0 = DK_ENTRIES(other->ma_keys);
2403 for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002404 PyObject *key, *value;
2405 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002406 entry = &ep0[i];
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002407 key = entry->me_key;
2408 hash = entry->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002409 if (other->ma_values)
2410 value = other->ma_values[i];
2411 else
2412 value = entry->me_value;
2413
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002414 if (value != NULL) {
2415 int err = 0;
2416 Py_INCREF(key);
2417 Py_INCREF(value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002418 if (override == 1)
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002419 err = insertdict(mp, key, hash, value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002420 else if (_PyDict_GetItem_KnownHash(a, key, hash) == NULL) {
2421 if (PyErr_Occurred()) {
2422 Py_DECREF(value);
2423 Py_DECREF(key);
2424 return -1;
2425 }
2426 err = insertdict(mp, key, hash, value);
2427 }
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002428 else if (override != 0) {
2429 _PyErr_SetKeyError(key);
2430 Py_DECREF(value);
2431 Py_DECREF(key);
2432 return -1;
2433 }
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002434 Py_DECREF(value);
2435 Py_DECREF(key);
2436 if (err != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 return -1;
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002438
Victor Stinner742da042016-09-07 17:40:12 -07002439 if (n != other->ma_keys->dk_nentries) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002440 PyErr_SetString(PyExc_RuntimeError,
2441 "dict mutated during update");
2442 return -1;
2443 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 }
2445 }
2446 }
2447 else {
2448 /* Do it the generic, slower way */
2449 PyObject *keys = PyMapping_Keys(b);
2450 PyObject *iter;
2451 PyObject *key, *value;
2452 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 if (keys == NULL)
2455 /* Docstring says this is equivalent to E.keys() so
2456 * if E doesn't have a .keys() method we want
2457 * AttributeError to percolate up. Might as well
2458 * do the same for any other error.
2459 */
2460 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 iter = PyObject_GetIter(keys);
2463 Py_DECREF(keys);
2464 if (iter == NULL)
2465 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002468 if (override != 1 && PyDict_GetItem(a, key) != NULL) {
2469 if (override != 0) {
2470 _PyErr_SetKeyError(key);
2471 Py_DECREF(key);
2472 Py_DECREF(iter);
2473 return -1;
2474 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 Py_DECREF(key);
2476 continue;
2477 }
2478 value = PyObject_GetItem(b, key);
2479 if (value == NULL) {
2480 Py_DECREF(iter);
2481 Py_DECREF(key);
2482 return -1;
2483 }
2484 status = PyDict_SetItem(a, key, value);
2485 Py_DECREF(key);
2486 Py_DECREF(value);
2487 if (status < 0) {
2488 Py_DECREF(iter);
2489 return -1;
2490 }
2491 }
2492 Py_DECREF(iter);
2493 if (PyErr_Occurred())
2494 /* Iterator completed, via error */
2495 return -1;
2496 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02002497 assert(_PyDict_CheckConsistency((PyDictObject *)a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002499}
2500
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002501int
2502PyDict_Update(PyObject *a, PyObject *b)
2503{
2504 return dict_merge(a, b, 1);
2505}
2506
2507int
2508PyDict_Merge(PyObject *a, PyObject *b, int override)
2509{
2510 /* XXX Deprecate override not in (0, 1). */
2511 return dict_merge(a, b, override != 0);
2512}
2513
2514int
2515_PyDict_MergeEx(PyObject *a, PyObject *b, int override)
2516{
2517 return dict_merge(a, b, override);
2518}
2519
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002520static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302521dict_copy(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002524}
2525
2526PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002527PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 PyObject *copy;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002530 PyDictObject *mp;
2531 Py_ssize_t i, n;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 if (o == NULL || !PyDict_Check(o)) {
2534 PyErr_BadInternalCall();
2535 return NULL;
2536 }
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002537
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002538 mp = (PyDictObject *)o;
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002539 if (mp->ma_used == 0) {
2540 /* The dict is empty; just return a new dict. */
2541 return PyDict_New();
2542 }
2543
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002544 if (_PyDict_HasSplitTable(mp)) {
2545 PyDictObject *split_copy;
Victor Stinner742da042016-09-07 17:40:12 -07002546 Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
2547 PyObject **newvalues;
2548 newvalues = new_values(size);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002549 if (newvalues == NULL)
2550 return PyErr_NoMemory();
2551 split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
2552 if (split_copy == NULL) {
2553 free_values(newvalues);
2554 return NULL;
2555 }
2556 split_copy->ma_values = newvalues;
2557 split_copy->ma_keys = mp->ma_keys;
2558 split_copy->ma_used = mp->ma_used;
INADA Naokid1c82c52018-04-03 11:43:53 +09002559 split_copy->ma_version_tag = DICT_NEXT_VERSION();
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002560 DK_INCREF(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002561 for (i = 0, n = size; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002562 PyObject *value = mp->ma_values[i];
2563 Py_XINCREF(value);
2564 split_copy->ma_values[i] = value;
2565 }
Benjamin Peterson7ce67e42012-04-24 10:32:57 -04002566 if (_PyObject_GC_IS_TRACKED(mp))
2567 _PyObject_GC_TRACK(split_copy);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002568 return (PyObject *)split_copy;
2569 }
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002570
2571 if (PyDict_CheckExact(mp) && mp->ma_values == NULL &&
2572 (mp->ma_used >= (mp->ma_keys->dk_nentries * 2) / 3))
2573 {
2574 /* Use fast-copy if:
2575
2576 (1) 'mp' is an instance of a subclassed dict; and
2577
2578 (2) 'mp' is not a split-dict; and
2579
2580 (3) if 'mp' is non-compact ('del' operation does not resize dicts),
2581 do fast-copy only if it has at most 1/3 non-used keys.
2582
Ville Skyttä61f82e02018-04-20 23:08:45 +03002583 The last condition (3) is important to guard against a pathological
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002584 case when a large dict is almost emptied with multiple del/pop
2585 operations and copied after that. In cases like this, we defer to
2586 PyDict_Merge, which produces a compacted copy.
2587 */
2588 return clone_combined_dict(mp);
2589 }
2590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 copy = PyDict_New();
2592 if (copy == NULL)
2593 return NULL;
2594 if (PyDict_Merge(copy, o, 1) == 0)
2595 return copy;
2596 Py_DECREF(copy);
2597 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002598}
2599
Martin v. Löwis18e16552006-02-15 17:27:45 +00002600Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00002601PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00002602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 if (mp == NULL || !PyDict_Check(mp)) {
2604 PyErr_BadInternalCall();
2605 return -1;
2606 }
2607 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00002608}
2609
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002610PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002611PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 if (mp == NULL || !PyDict_Check(mp)) {
2614 PyErr_BadInternalCall();
2615 return NULL;
2616 }
2617 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002618}
2619
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002620PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002621PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 if (mp == NULL || !PyDict_Check(mp)) {
2624 PyErr_BadInternalCall();
2625 return NULL;
2626 }
2627 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002628}
2629
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002630PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002631PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 if (mp == NULL || !PyDict_Check(mp)) {
2634 PyErr_BadInternalCall();
2635 return NULL;
2636 }
2637 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002638}
2639
Tim Peterse63415e2001-05-08 04:38:29 +00002640/* Return 1 if dicts equal, 0 if not, -1 if error.
2641 * Gets out as soon as any difference is detected.
2642 * Uses only Py_EQ comparison.
2643 */
2644static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002645dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00002646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00002648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 if (a->ma_used != b->ma_used)
2650 /* can't be equal if # of entries differ */
2651 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Victor Stinner742da042016-09-07 17:40:12 -07002653 for (i = 0; i < a->ma_keys->dk_nentries; i++) {
2654 PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002655 PyObject *aval;
2656 if (a->ma_values)
2657 aval = a->ma_values[i];
2658 else
2659 aval = ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 if (aval != NULL) {
2661 int cmp;
2662 PyObject *bval;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002663 PyObject *key = ep->me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 /* temporarily bump aval's refcount to ensure it stays
2665 alive until we're done with it */
2666 Py_INCREF(aval);
2667 /* ditto for key */
2668 Py_INCREF(key);
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002669 /* reuse the known hash value */
INADA Naoki778928b2017-08-03 23:45:15 +09002670 b->ma_keys->dk_lookup(b, key, ep->me_hash, &bval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 if (bval == NULL) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002672 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 Py_DECREF(aval);
2674 if (PyErr_Occurred())
2675 return -1;
2676 return 0;
2677 }
2678 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002679 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 Py_DECREF(aval);
2681 if (cmp <= 0) /* error or not equal */
2682 return cmp;
2683 }
2684 }
2685 return 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002686}
Tim Peterse63415e2001-05-08 04:38:29 +00002687
2688static PyObject *
2689dict_richcompare(PyObject *v, PyObject *w, int op)
2690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 int cmp;
2692 PyObject *res;
Tim Peterse63415e2001-05-08 04:38:29 +00002693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 if (!PyDict_Check(v) || !PyDict_Check(w)) {
2695 res = Py_NotImplemented;
2696 }
2697 else if (op == Py_EQ || op == Py_NE) {
2698 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
2699 if (cmp < 0)
2700 return NULL;
2701 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
2702 }
2703 else
2704 res = Py_NotImplemented;
2705 Py_INCREF(res);
2706 return res;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002707}
Tim Peterse63415e2001-05-08 04:38:29 +00002708
Larry Hastings61272b72014-01-07 12:41:53 -08002709/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002710
2711@coexist
2712dict.__contains__
2713
2714 key: object
2715 /
2716
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002717True if the dictionary has the specified key, else False.
Larry Hastings61272b72014-01-07 12:41:53 -08002718[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002719
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002720static PyObject *
Larry Hastingsc2047262014-01-25 20:43:29 -08002721dict___contains__(PyDictObject *self, PyObject *key)
Serhiy Storchaka19d25972017-02-04 08:05:07 +02002722/*[clinic end generated code: output=a3d03db709ed6e6b input=fe1cb42ad831e820]*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002723{
Larry Hastingsc2047262014-01-25 20:43:29 -08002724 register PyDictObject *mp = self;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002725 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002726 Py_ssize_t ix;
INADA Naokiba609772016-12-07 20:41:42 +09002727 PyObject *value;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002730 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 hash = PyObject_Hash(key);
2732 if (hash == -1)
2733 return NULL;
2734 }
INADA Naoki778928b2017-08-03 23:45:15 +09002735 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002736 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002738 if (ix == DKIX_EMPTY || value == NULL)
Victor Stinner742da042016-09-07 17:40:12 -07002739 Py_RETURN_FALSE;
2740 Py_RETURN_TRUE;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002741}
2742
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002743/*[clinic input]
2744dict.get
2745
2746 key: object
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002747 default: object = None
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002748 /
2749
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002750Return the value for key if key is in the dictionary, else default.
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002751[clinic start generated code]*/
2752
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002753static PyObject *
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002754dict_get_impl(PyDictObject *self, PyObject *key, PyObject *default_value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002755/*[clinic end generated code: output=bba707729dee05bf input=279ddb5790b6b107]*/
Barry Warsawc38c5da1997-10-06 17:49:20 +00002756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002758 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002759 Py_ssize_t ix;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002762 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 hash = PyObject_Hash(key);
2764 if (hash == -1)
2765 return NULL;
2766 }
INADA Naoki778928b2017-08-03 23:45:15 +09002767 ix = (self->ma_keys->dk_lookup) (self, key, hash, &val);
Victor Stinner742da042016-09-07 17:40:12 -07002768 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002770 if (ix == DKIX_EMPTY || val == NULL) {
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002771 val = default_value;
INADA Naokiba609772016-12-07 20:41:42 +09002772 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 Py_INCREF(val);
2774 return val;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002775}
2776
Benjamin Peterson00e98862013-03-07 22:16:29 -05002777PyObject *
2778PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
Guido van Rossum164452c2000-08-08 16:12:54 +00002779{
Benjamin Peterson00e98862013-03-07 22:16:29 -05002780 PyDictObject *mp = (PyDictObject *)d;
INADA Naoki93f26f72016-11-02 18:45:16 +09002781 PyObject *value;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002782 Py_hash_t hash;
Guido van Rossum164452c2000-08-08 16:12:54 +00002783
Benjamin Peterson00e98862013-03-07 22:16:29 -05002784 if (!PyDict_Check(d)) {
2785 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 return NULL;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002787 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002790 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 hash = PyObject_Hash(key);
2792 if (hash == -1)
2793 return NULL;
2794 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002795
2796 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
2797 if (insertion_resize(mp) < 0)
2798 return NULL;
2799 }
2800
INADA Naoki778928b2017-08-03 23:45:15 +09002801 Py_ssize_t ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002802 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 return NULL;
INADA Naoki93f26f72016-11-02 18:45:16 +09002804
2805 if (_PyDict_HasSplitTable(mp) &&
INADA Naokiba609772016-12-07 20:41:42 +09002806 ((ix >= 0 && value == NULL && mp->ma_used != ix) ||
INADA Naoki93f26f72016-11-02 18:45:16 +09002807 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
2808 if (insertion_resize(mp) < 0) {
2809 return NULL;
2810 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002811 ix = DKIX_EMPTY;
2812 }
2813
2814 if (ix == DKIX_EMPTY) {
2815 PyDictKeyEntry *ep, *ep0;
2816 value = defaultobj;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002817 if (mp->ma_keys->dk_usable <= 0) {
Victor Stinner3c336c52016-09-12 14:17:40 +02002818 if (insertion_resize(mp) < 0) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002819 return NULL;
Victor Stinner3c336c52016-09-12 14:17:40 +02002820 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002821 }
INADA Naoki778928b2017-08-03 23:45:15 +09002822 Py_ssize_t hashpos = find_empty_slot(mp->ma_keys, hash);
INADA Naoki93f26f72016-11-02 18:45:16 +09002823 ep0 = DK_ENTRIES(mp->ma_keys);
2824 ep = &ep0[mp->ma_keys->dk_nentries];
2825 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
Benjamin Petersonb1efa532013-03-04 09:47:50 -05002826 Py_INCREF(key);
INADA Naoki93f26f72016-11-02 18:45:16 +09002827 Py_INCREF(value);
2828 MAINTAIN_TRACKING(mp, key, value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002829 ep->me_key = key;
2830 ep->me_hash = hash;
INADA Naokiba609772016-12-07 20:41:42 +09002831 if (_PyDict_HasSplitTable(mp)) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002832 assert(mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
2833 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Victor Stinner742da042016-09-07 17:40:12 -07002834 }
2835 else {
INADA Naoki93f26f72016-11-02 18:45:16 +09002836 ep->me_value = value;
Victor Stinner742da042016-09-07 17:40:12 -07002837 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002838 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07002839 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naoki93f26f72016-11-02 18:45:16 +09002840 mp->ma_keys->dk_usable--;
2841 mp->ma_keys->dk_nentries++;
2842 assert(mp->ma_keys->dk_usable >= 0);
2843 }
INADA Naokiba609772016-12-07 20:41:42 +09002844 else if (value == NULL) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002845 value = defaultobj;
2846 assert(_PyDict_HasSplitTable(mp));
2847 assert(ix == mp->ma_used);
2848 Py_INCREF(value);
2849 MAINTAIN_TRACKING(mp, key, value);
INADA Naokiba609772016-12-07 20:41:42 +09002850 mp->ma_values[ix] = value;
INADA Naoki93f26f72016-11-02 18:45:16 +09002851 mp->ma_used++;
2852 mp->ma_version_tag = DICT_NEXT_VERSION();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002854
2855 assert(_PyDict_CheckConsistency(mp));
2856 return value;
Guido van Rossum164452c2000-08-08 16:12:54 +00002857}
2858
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002859/*[clinic input]
2860dict.setdefault
2861
2862 key: object
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002863 default: object = None
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002864 /
2865
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002866Insert key with a value of default if key is not in the dictionary.
2867
2868Return the value for key if key is in the dictionary, else default.
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002869[clinic start generated code]*/
2870
Benjamin Peterson00e98862013-03-07 22:16:29 -05002871static PyObject *
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002872dict_setdefault_impl(PyDictObject *self, PyObject *key,
2873 PyObject *default_value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002874/*[clinic end generated code: output=f8c1101ebf69e220 input=0f063756e815fd9d]*/
Benjamin Peterson00e98862013-03-07 22:16:29 -05002875{
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002876 PyObject *val;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002877
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002878 val = PyDict_SetDefault((PyObject *)self, key, default_value);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002879 Py_XINCREF(val);
2880 return val;
2881}
Guido van Rossum164452c2000-08-08 16:12:54 +00002882
2883static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302884dict_clear(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 PyDict_Clear((PyObject *)mp);
2887 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002888}
2889
Guido van Rossumba6ab842000-12-12 22:02:18 +00002890static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002891dict_pop(PyDictObject *mp, PyObject *args)
Guido van Rossume027d982002-04-12 15:11:59 +00002892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 PyObject *key, *deflt = NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00002894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
2896 return NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06002897
Yury Selivanov684ef2c2016-10-28 19:01:21 -04002898 return _PyDict_Pop((PyObject*)mp, key, deflt);
Guido van Rossume027d982002-04-12 15:11:59 +00002899}
2900
2901static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302902dict_popitem(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Guido van Rossumba6ab842000-12-12 22:02:18 +00002903{
Victor Stinner742da042016-09-07 17:40:12 -07002904 Py_ssize_t i, j;
2905 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 PyObject *res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 /* Allocate the result tuple before checking the size. Believe it
2909 * or not, this allocation could trigger a garbage collection which
2910 * could empty the dict, so if we checked the size first and that
2911 * happened, the result would be an infinite loop (searching for an
2912 * entry that no longer exists). Note that the usual popitem()
2913 * idiom is "while d: k, v = d.popitem()". so needing to throw the
2914 * tuple away if the dict *is* empty isn't a significant
2915 * inefficiency -- possible, but unlikely in practice.
2916 */
2917 res = PyTuple_New(2);
2918 if (res == NULL)
2919 return NULL;
2920 if (mp->ma_used == 0) {
2921 Py_DECREF(res);
2922 PyErr_SetString(PyExc_KeyError,
2923 "popitem(): dictionary is empty");
2924 return NULL;
2925 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002926 /* Convert split table to combined table */
2927 if (mp->ma_keys->dk_lookup == lookdict_split) {
2928 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
2929 Py_DECREF(res);
2930 return NULL;
2931 }
2932 }
2933 ENSURE_ALLOWS_DELETIONS(mp);
Victor Stinner742da042016-09-07 17:40:12 -07002934
2935 /* Pop last item */
2936 ep0 = DK_ENTRIES(mp->ma_keys);
2937 i = mp->ma_keys->dk_nentries - 1;
2938 while (i >= 0 && ep0[i].me_value == NULL) {
2939 i--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 }
Victor Stinner742da042016-09-07 17:40:12 -07002941 assert(i >= 0);
2942
2943 ep = &ep0[i];
2944 j = lookdict_index(mp->ma_keys, ep->me_hash, i);
2945 assert(j >= 0);
2946 assert(dk_get_index(mp->ma_keys, j) == i);
2947 dk_set_index(mp->ma_keys, j, DKIX_DUMMY);
2948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 PyTuple_SET_ITEM(res, 0, ep->me_key);
2950 PyTuple_SET_ITEM(res, 1, ep->me_value);
Victor Stinner742da042016-09-07 17:40:12 -07002951 ep->me_key = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 ep->me_value = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002953 /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
2954 mp->ma_keys->dk_nentries = i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07002956 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner611b0fa2016-09-14 15:02:01 +02002957 assert(_PyDict_CheckConsistency(mp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 return res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002959}
2960
Jeremy Hylton8caad492000-06-23 14:18:11 +00002961static int
2962dict_traverse(PyObject *op, visitproc visit, void *arg)
2963{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002964 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson55f44522016-09-05 12:12:59 -07002965 PyDictKeysObject *keys = mp->ma_keys;
Serhiy Storchaka46825d22016-09-26 21:29:34 +03002966 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Victor Stinner742da042016-09-07 17:40:12 -07002967 Py_ssize_t i, n = keys->dk_nentries;
2968
Benjamin Peterson55f44522016-09-05 12:12:59 -07002969 if (keys->dk_lookup == lookdict) {
2970 for (i = 0; i < n; i++) {
2971 if (entries[i].me_value != NULL) {
2972 Py_VISIT(entries[i].me_value);
2973 Py_VISIT(entries[i].me_key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002974 }
2975 }
Victor Stinner742da042016-09-07 17:40:12 -07002976 }
2977 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002978 if (mp->ma_values != NULL) {
Benjamin Peterson55f44522016-09-05 12:12:59 -07002979 for (i = 0; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002980 Py_VISIT(mp->ma_values[i]);
2981 }
2982 }
2983 else {
Benjamin Peterson55f44522016-09-05 12:12:59 -07002984 for (i = 0; i < n; i++) {
2985 Py_VISIT(entries[i].me_value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002986 }
2987 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 }
2989 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002990}
2991
2992static int
2993dict_tp_clear(PyObject *op)
2994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 PyDict_Clear(op);
2996 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002997}
2998
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002999static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003000
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003001Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003002_PyDict_SizeOf(PyDictObject *mp)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003003{
Victor Stinner742da042016-09-07 17:40:12 -07003004 Py_ssize_t size, usable, res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003005
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003006 size = DK_SIZE(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07003007 usable = USABLE_FRACTION(size);
3008
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02003009 res = _PyObject_SIZE(Py_TYPE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003010 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07003011 res += usable * sizeof(PyObject*);
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003012 /* If the dictionary is split, the keys portion is accounted-for
3013 in the type object. */
3014 if (mp->ma_keys->dk_refcnt == 1)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003015 res += (sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003016 + DK_IXSIZE(mp->ma_keys) * size
3017 + sizeof(PyDictKeyEntry) * usable);
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003018 return res;
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003019}
3020
3021Py_ssize_t
3022_PyDict_KeysSize(PyDictKeysObject *keys)
3023{
Victor Stinner98ee9d52016-09-08 09:33:56 -07003024 return (sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003025 + DK_IXSIZE(keys) * DK_SIZE(keys)
3026 + USABLE_FRACTION(DK_SIZE(keys)) * sizeof(PyDictKeyEntry));
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003027}
3028
doko@ubuntu.com17210f52016-01-14 14:04:59 +01003029static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303030dict_sizeof(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003031{
3032 return PyLong_FromSsize_t(_PyDict_SizeOf(mp));
3033}
3034
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003035PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
3036
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003037PyDoc_STRVAR(sizeof__doc__,
3038"D.__sizeof__() -> size of D in memory, in bytes");
3039
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003040PyDoc_STRVAR(pop__doc__,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00003041"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00003042If key is not found, d is returned if given, otherwise KeyError is raised");
Guido van Rossume027d982002-04-12 15:11:59 +00003043
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003044PyDoc_STRVAR(popitem__doc__,
Tim Petersf7f88b12000-12-13 23:18:45 +00003045"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000030462-tuple; but raise KeyError if D is empty.");
Tim Petersf7f88b12000-12-13 23:18:45 +00003047
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003048PyDoc_STRVAR(update__doc__,
Brett Cannonf2754162013-05-11 14:46:48 -04003049"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n\
3050If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]\n\
3051If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n\
3052In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00003053
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003054PyDoc_STRVAR(clear__doc__,
3055"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00003056
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003057PyDoc_STRVAR(copy__doc__,
3058"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00003059
Guido van Rossumb90c8482007-02-10 01:11:45 +00003060/* Forward */
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303061static PyObject *dictkeys_new(PyObject *, PyObject *);
3062static PyObject *dictitems_new(PyObject *, PyObject *);
3063static PyObject *dictvalues_new(PyObject *, PyObject *);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003064
Guido van Rossum45c85d12007-07-27 16:31:40 +00003065PyDoc_STRVAR(keys__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 "D.keys() -> a set-like object providing a view on D's keys");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003067PyDoc_STRVAR(items__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 "D.items() -> a set-like object providing a view on D's items");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003069PyDoc_STRVAR(values__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 "D.values() -> an object providing a view on D's values");
Guido van Rossumb90c8482007-02-10 01:11:45 +00003071
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003072static PyMethodDef mapp_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -07003073 DICT___CONTAINS___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
3075 getitem__doc__},
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003076 {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 sizeof__doc__},
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01003078 DICT_GET_METHODDEF
3079 DICT_SETDEFAULT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 {"pop", (PyCFunction)dict_pop, METH_VARARGS,
3081 pop__doc__},
3082 {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
3083 popitem__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303084 {"keys", dictkeys_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 keys__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303086 {"items", dictitems_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 items__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303088 {"values", dictvalues_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 values__doc__},
3090 {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
3091 update__doc__},
Larry Hastings5c661892014-01-24 06:17:25 -08003092 DICT_FROMKEYS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
3094 clear__doc__},
3095 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
3096 copy__doc__},
3097 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003098};
3099
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00003100/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00003101int
3102PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003103{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003104 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07003105 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09003107 PyObject *value;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003110 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 hash = PyObject_Hash(key);
3112 if (hash == -1)
3113 return -1;
3114 }
INADA Naoki778928b2017-08-03 23:45:15 +09003115 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07003116 if (ix == DKIX_ERROR)
3117 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09003118 return (ix != DKIX_EMPTY && value != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003119}
3120
Thomas Wouterscf297e42007-02-23 15:07:44 +00003121/* Internal version of PyDict_Contains used when the hash value is already known */
3122int
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003123_PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00003124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09003126 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -07003127 Py_ssize_t ix;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003128
INADA Naoki778928b2017-08-03 23:45:15 +09003129 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07003130 if (ix == DKIX_ERROR)
3131 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09003132 return (ix != DKIX_EMPTY && value != NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00003133}
3134
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003135/* Hack to implement "key in dict" */
3136static PySequenceMethods dict_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 0, /* sq_length */
3138 0, /* sq_concat */
3139 0, /* sq_repeat */
3140 0, /* sq_item */
3141 0, /* sq_slice */
3142 0, /* sq_ass_item */
3143 0, /* sq_ass_slice */
3144 PyDict_Contains, /* sq_contains */
3145 0, /* sq_inplace_concat */
3146 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003147};
3148
Guido van Rossum09e563a2001-05-01 12:10:21 +00003149static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003150dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 PyObject *self;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003153 PyDictObject *d;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 assert(type != NULL && type->tp_alloc != NULL);
3156 self = type->tp_alloc(type, 0);
Victor Stinnera9f61a52013-07-16 22:17:26 +02003157 if (self == NULL)
3158 return NULL;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003159 d = (PyDictObject *)self;
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003160
Victor Stinnera9f61a52013-07-16 22:17:26 +02003161 /* The object has been implicitly tracked by tp_alloc */
3162 if (type == &PyDict_Type)
3163 _PyObject_GC_UNTRACK(d);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003164
3165 d->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07003166 d->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07003167 d->ma_keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003168 if (d->ma_keys == NULL) {
3169 Py_DECREF(self);
3170 return NULL;
3171 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02003172 assert(_PyDict_CheckConsistency(d));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 return self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003174}
3175
Tim Peters25786c02001-09-02 08:22:48 +00003176static int
3177dict_init(PyObject *self, PyObject *args, PyObject *kwds)
3178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00003180}
3181
Tim Peters6d6c1a32001-08-02 04:15:00 +00003182static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003183dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00003184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003186}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003187
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003188PyDoc_STRVAR(dictionary_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00003189"dict() -> new empty dictionary\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00003190"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003191" (key, value) pairs\n"
3192"dict(iterable) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00003193" d = {}\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003194" for k, v in iterable:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00003195" d[k] = v\n"
3196"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
3197" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00003198
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003199PyTypeObject PyDict_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3201 "dict",
3202 sizeof(PyDictObject),
3203 0,
3204 (destructor)dict_dealloc, /* tp_dealloc */
3205 0, /* tp_print */
3206 0, /* tp_getattr */
3207 0, /* tp_setattr */
3208 0, /* tp_reserved */
3209 (reprfunc)dict_repr, /* tp_repr */
3210 0, /* tp_as_number */
3211 &dict_as_sequence, /* tp_as_sequence */
3212 &dict_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003213 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 0, /* tp_call */
3215 0, /* tp_str */
3216 PyObject_GenericGetAttr, /* tp_getattro */
3217 0, /* tp_setattro */
3218 0, /* tp_as_buffer */
3219 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3220 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
3221 dictionary_doc, /* tp_doc */
3222 dict_traverse, /* tp_traverse */
3223 dict_tp_clear, /* tp_clear */
3224 dict_richcompare, /* tp_richcompare */
3225 0, /* tp_weaklistoffset */
3226 (getiterfunc)dict_iter, /* tp_iter */
3227 0, /* tp_iternext */
3228 mapp_methods, /* tp_methods */
3229 0, /* tp_members */
3230 0, /* tp_getset */
3231 0, /* tp_base */
3232 0, /* tp_dict */
3233 0, /* tp_descr_get */
3234 0, /* tp_descr_set */
3235 0, /* tp_dictoffset */
3236 dict_init, /* tp_init */
3237 PyType_GenericAlloc, /* tp_alloc */
3238 dict_new, /* tp_new */
3239 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003240};
3241
Victor Stinner3c1e4812012-03-26 22:10:51 +02003242PyObject *
3243_PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
3244{
3245 PyObject *kv;
3246 kv = _PyUnicode_FromId(key); /* borrowed */
Victor Stinner5b3b1002013-07-22 23:50:57 +02003247 if (kv == NULL) {
3248 PyErr_Clear();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003249 return NULL;
Victor Stinner5b3b1002013-07-22 23:50:57 +02003250 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003251 return PyDict_GetItem(dp, kv);
3252}
3253
Guido van Rossum3cca2451997-05-16 14:23:33 +00003254/* For backward compatibility with old dictionary interface */
3255
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003256PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003257PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 PyObject *kv, *rv;
3260 kv = PyUnicode_FromString(key);
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003261 if (kv == NULL) {
3262 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 return NULL;
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003264 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 rv = PyDict_GetItem(v, kv);
3266 Py_DECREF(kv);
3267 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003268}
3269
3270int
Victor Stinner3c1e4812012-03-26 22:10:51 +02003271_PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
3272{
3273 PyObject *kv;
3274 kv = _PyUnicode_FromId(key); /* borrowed */
3275 if (kv == NULL)
3276 return -1;
3277 return PyDict_SetItem(v, kv, item);
3278}
3279
3280int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003281PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 PyObject *kv;
3284 int err;
3285 kv = PyUnicode_FromString(key);
3286 if (kv == NULL)
3287 return -1;
3288 PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
3289 err = PyDict_SetItem(v, kv, item);
3290 Py_DECREF(kv);
3291 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003292}
3293
3294int
Victor Stinner5fd2e5a2013-11-06 18:58:22 +01003295_PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
3296{
3297 PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
3298 if (kv == NULL)
3299 return -1;
3300 return PyDict_DelItem(v, kv);
3301}
3302
3303int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003304PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 PyObject *kv;
3307 int err;
3308 kv = PyUnicode_FromString(key);
3309 if (kv == NULL)
3310 return -1;
3311 err = PyDict_DelItem(v, kv);
3312 Py_DECREF(kv);
3313 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003314}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003315
Raymond Hettinger019a1482004-03-18 02:41:19 +00003316/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003317
3318typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 PyObject_HEAD
3320 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
3321 Py_ssize_t di_used;
3322 Py_ssize_t di_pos;
3323 PyObject* di_result; /* reusable result tuple for iteritems */
3324 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003325} dictiterobject;
3326
3327static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003328dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 dictiterobject *di;
3331 di = PyObject_GC_New(dictiterobject, itertype);
3332 if (di == NULL)
3333 return NULL;
3334 Py_INCREF(dict);
3335 di->di_dict = dict;
3336 di->di_used = dict->ma_used;
3337 di->di_pos = 0;
3338 di->len = dict->ma_used;
3339 if (itertype == &PyDictIterItem_Type) {
3340 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
3341 if (di->di_result == NULL) {
3342 Py_DECREF(di);
3343 return NULL;
3344 }
3345 }
3346 else
3347 di->di_result = NULL;
3348 _PyObject_GC_TRACK(di);
3349 return (PyObject *)di;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003350}
3351
3352static void
3353dictiter_dealloc(dictiterobject *di)
3354{
INADA Naokia6296d32017-08-24 14:55:17 +09003355 /* bpo-31095: UnTrack is needed before calling any callbacks */
3356 _PyObject_GC_UNTRACK(di);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 Py_XDECREF(di->di_dict);
3358 Py_XDECREF(di->di_result);
3359 PyObject_GC_Del(di);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003360}
3361
3362static int
3363dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
3364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 Py_VISIT(di->di_dict);
3366 Py_VISIT(di->di_result);
3367 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003368}
3369
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003370static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303371dictiter_len(dictiterobject *di, PyObject *Py_UNUSED(ignored))
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 Py_ssize_t len = 0;
3374 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
3375 len = di->len;
3376 return PyLong_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003377}
3378
Guido van Rossumb90c8482007-02-10 01:11:45 +00003379PyDoc_STRVAR(length_hint_doc,
3380 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003381
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003382static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303383dictiter_reduce(dictiterobject *di, PyObject *Py_UNUSED(ignored));
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003384
3385PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3386
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003387static PyMethodDef dictiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS,
3389 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003390 {"__reduce__", (PyCFunction)dictiter_reduce, METH_NOARGS,
3391 reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003393};
3394
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003395static PyObject*
3396dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00003397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 PyObject *key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003399 Py_ssize_t i;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003400 PyDictKeysObject *k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 PyDictObject *d = di->di_dict;
Guido van Rossum213c7a62001-04-23 14:08:49 +00003402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 if (d == NULL)
3404 return NULL;
3405 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00003406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 if (di->di_used != d->ma_used) {
3408 PyErr_SetString(PyExc_RuntimeError,
3409 "dictionary changed size during iteration");
3410 di->di_used = -1; /* Make this state sticky */
3411 return NULL;
3412 }
Guido van Rossum2147df72002-07-16 20:30:22 +00003413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 i = di->di_pos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003415 k = d->ma_keys;
INADA Naokica2d8be2016-11-04 16:59:10 +09003416 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003417 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003418 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003419 goto fail;
3420 key = DK_ENTRIES(k)[i].me_key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003421 assert(d->ma_values[i] != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003422 }
3423 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003424 Py_ssize_t n = k->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003425 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
3426 while (i < n && entry_ptr->me_value == NULL) {
3427 entry_ptr++;
3428 i++;
3429 }
3430 if (i >= n)
3431 goto fail;
3432 key = entry_ptr->me_key;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003433 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 di->di_pos = i+1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 di->len--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 Py_INCREF(key);
3437 return key;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003438
3439fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003441 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003443}
3444
Raymond Hettinger019a1482004-03-18 02:41:19 +00003445PyTypeObject PyDictIterKey_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3447 "dict_keyiterator", /* tp_name */
3448 sizeof(dictiterobject), /* tp_basicsize */
3449 0, /* tp_itemsize */
3450 /* methods */
3451 (destructor)dictiter_dealloc, /* tp_dealloc */
3452 0, /* tp_print */
3453 0, /* tp_getattr */
3454 0, /* tp_setattr */
3455 0, /* tp_reserved */
3456 0, /* tp_repr */
3457 0, /* tp_as_number */
3458 0, /* tp_as_sequence */
3459 0, /* tp_as_mapping */
3460 0, /* tp_hash */
3461 0, /* tp_call */
3462 0, /* tp_str */
3463 PyObject_GenericGetAttr, /* tp_getattro */
3464 0, /* tp_setattro */
3465 0, /* tp_as_buffer */
3466 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3467 0, /* tp_doc */
3468 (traverseproc)dictiter_traverse, /* tp_traverse */
3469 0, /* tp_clear */
3470 0, /* tp_richcompare */
3471 0, /* tp_weaklistoffset */
3472 PyObject_SelfIter, /* tp_iter */
3473 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
3474 dictiter_methods, /* tp_methods */
3475 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003476};
3477
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003478static PyObject *
3479dictiter_iternextvalue(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 PyObject *value;
INADA Naokica2d8be2016-11-04 16:59:10 +09003482 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003485 if (d == NULL)
3486 return NULL;
3487 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 if (di->di_used != d->ma_used) {
3490 PyErr_SetString(PyExc_RuntimeError,
3491 "dictionary changed size during iteration");
3492 di->di_used = -1; /* Make this state sticky */
3493 return NULL;
3494 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 i = di->di_pos;
INADA Naokica2d8be2016-11-04 16:59:10 +09003497 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003498 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003499 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003500 goto fail;
INADA Naokica2d8be2016-11-04 16:59:10 +09003501 value = d->ma_values[i];
3502 assert(value != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003503 }
3504 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003505 Py_ssize_t n = d->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003506 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3507 while (i < n && entry_ptr->me_value == NULL) {
3508 entry_ptr++;
3509 i++;
3510 }
3511 if (i >= n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003512 goto fail;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003513 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 }
3515 di->di_pos = i+1;
3516 di->len--;
3517 Py_INCREF(value);
3518 return value;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003519
3520fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003522 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003524}
3525
3526PyTypeObject PyDictIterValue_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3528 "dict_valueiterator", /* tp_name */
3529 sizeof(dictiterobject), /* tp_basicsize */
3530 0, /* tp_itemsize */
3531 /* methods */
3532 (destructor)dictiter_dealloc, /* tp_dealloc */
3533 0, /* tp_print */
3534 0, /* tp_getattr */
3535 0, /* tp_setattr */
3536 0, /* tp_reserved */
3537 0, /* tp_repr */
3538 0, /* tp_as_number */
3539 0, /* tp_as_sequence */
3540 0, /* tp_as_mapping */
3541 0, /* tp_hash */
3542 0, /* tp_call */
3543 0, /* tp_str */
3544 PyObject_GenericGetAttr, /* tp_getattro */
3545 0, /* tp_setattro */
3546 0, /* tp_as_buffer */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003547 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 0, /* tp_doc */
3549 (traverseproc)dictiter_traverse, /* tp_traverse */
3550 0, /* tp_clear */
3551 0, /* tp_richcompare */
3552 0, /* tp_weaklistoffset */
3553 PyObject_SelfIter, /* tp_iter */
3554 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
3555 dictiter_methods, /* tp_methods */
3556 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003557};
3558
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003559static PyObject *
3560dictiter_iternextitem(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003561{
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003562 PyObject *key, *value, *result;
INADA Naokica2d8be2016-11-04 16:59:10 +09003563 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 if (d == NULL)
3567 return NULL;
3568 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 if (di->di_used != d->ma_used) {
3571 PyErr_SetString(PyExc_RuntimeError,
3572 "dictionary changed size during iteration");
3573 di->di_used = -1; /* Make this state sticky */
3574 return NULL;
3575 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 i = di->di_pos;
INADA Naokica2d8be2016-11-04 16:59:10 +09003578 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003579 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003580 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003581 goto fail;
3582 key = DK_ENTRIES(d->ma_keys)[i].me_key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003583 value = d->ma_values[i];
3584 assert(value != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003585 }
3586 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003587 Py_ssize_t n = d->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003588 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3589 while (i < n && entry_ptr->me_value == NULL) {
3590 entry_ptr++;
3591 i++;
3592 }
3593 if (i >= n)
3594 goto fail;
3595 key = entry_ptr->me_key;
3596 value = entry_ptr->me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003597 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 di->di_pos = i+1;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003599 di->len--;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003600 Py_INCREF(key);
3601 Py_INCREF(value);
3602 result = di->di_result;
3603 if (Py_REFCNT(result) == 1) {
3604 PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
3605 PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
3606 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3607 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 Py_INCREF(result);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003609 Py_DECREF(oldkey);
3610 Py_DECREF(oldvalue);
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003611 }
3612 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 result = PyTuple_New(2);
3614 if (result == NULL)
3615 return NULL;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003616 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3617 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003620
3621fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003623 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003625}
3626
3627PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3629 "dict_itemiterator", /* tp_name */
3630 sizeof(dictiterobject), /* tp_basicsize */
3631 0, /* tp_itemsize */
3632 /* methods */
3633 (destructor)dictiter_dealloc, /* tp_dealloc */
3634 0, /* tp_print */
3635 0, /* tp_getattr */
3636 0, /* tp_setattr */
3637 0, /* tp_reserved */
3638 0, /* tp_repr */
3639 0, /* tp_as_number */
3640 0, /* tp_as_sequence */
3641 0, /* tp_as_mapping */
3642 0, /* tp_hash */
3643 0, /* tp_call */
3644 0, /* tp_str */
3645 PyObject_GenericGetAttr, /* tp_getattro */
3646 0, /* tp_setattro */
3647 0, /* tp_as_buffer */
3648 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3649 0, /* tp_doc */
3650 (traverseproc)dictiter_traverse, /* tp_traverse */
3651 0, /* tp_clear */
3652 0, /* tp_richcompare */
3653 0, /* tp_weaklistoffset */
3654 PyObject_SelfIter, /* tp_iter */
3655 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
3656 dictiter_methods, /* tp_methods */
3657 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003658};
Guido van Rossumb90c8482007-02-10 01:11:45 +00003659
3660
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003661static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303662dictiter_reduce(dictiterobject *di, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003663{
3664 PyObject *list;
3665 dictiterobject tmp;
3666
3667 list = PyList_New(0);
3668 if (!list)
3669 return NULL;
3670
3671 /* copy the itertor state */
3672 tmp = *di;
3673 Py_XINCREF(tmp.di_dict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003674
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003675 /* iterate the temporary into a list */
3676 for(;;) {
3677 PyObject *element = 0;
3678 if (Py_TYPE(di) == &PyDictIterItem_Type)
3679 element = dictiter_iternextitem(&tmp);
3680 else if (Py_TYPE(di) == &PyDictIterKey_Type)
3681 element = dictiter_iternextkey(&tmp);
3682 else if (Py_TYPE(di) == &PyDictIterValue_Type)
3683 element = dictiter_iternextvalue(&tmp);
3684 else
Barry Warsawb2e57942017-09-14 18:13:16 -07003685 Py_UNREACHABLE();
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003686 if (element) {
3687 if (PyList_Append(list, element)) {
3688 Py_DECREF(element);
3689 Py_DECREF(list);
3690 Py_XDECREF(tmp.di_dict);
3691 return NULL;
3692 }
3693 Py_DECREF(element);
3694 } else
3695 break;
3696 }
3697 Py_XDECREF(tmp.di_dict);
3698 /* check for error */
3699 if (tmp.di_dict != NULL) {
3700 /* we have an error */
3701 Py_DECREF(list);
3702 return NULL;
3703 }
Antoine Pitroua7013882012-04-05 00:04:20 +02003704 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003705}
3706
Guido van Rossum3ac67412007-02-10 18:55:06 +00003707/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003708/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00003709/***********************************************/
3710
Guido van Rossumb90c8482007-02-10 01:11:45 +00003711/* The instance lay-out is the same for all three; but the type differs. */
3712
Guido van Rossumb90c8482007-02-10 01:11:45 +00003713static void
Eric Snow96c6af92015-05-29 22:21:39 -06003714dictview_dealloc(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003715{
INADA Naokia6296d32017-08-24 14:55:17 +09003716 /* bpo-31095: UnTrack is needed before calling any callbacks */
3717 _PyObject_GC_UNTRACK(dv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 Py_XDECREF(dv->dv_dict);
3719 PyObject_GC_Del(dv);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003720}
3721
3722static int
Eric Snow96c6af92015-05-29 22:21:39 -06003723dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 Py_VISIT(dv->dv_dict);
3726 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003727}
3728
Guido van Rossum83825ac2007-02-10 04:54:19 +00003729static Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003730dictview_len(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 Py_ssize_t len = 0;
3733 if (dv->dv_dict != NULL)
3734 len = dv->dv_dict->ma_used;
3735 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003736}
3737
Eric Snow96c6af92015-05-29 22:21:39 -06003738PyObject *
3739_PyDictView_New(PyObject *dict, PyTypeObject *type)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003740{
Eric Snow96c6af92015-05-29 22:21:39 -06003741 _PyDictViewObject *dv;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 if (dict == NULL) {
3743 PyErr_BadInternalCall();
3744 return NULL;
3745 }
3746 if (!PyDict_Check(dict)) {
3747 /* XXX Get rid of this restriction later */
3748 PyErr_Format(PyExc_TypeError,
3749 "%s() requires a dict argument, not '%s'",
3750 type->tp_name, dict->ob_type->tp_name);
3751 return NULL;
3752 }
Eric Snow96c6af92015-05-29 22:21:39 -06003753 dv = PyObject_GC_New(_PyDictViewObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 if (dv == NULL)
3755 return NULL;
3756 Py_INCREF(dict);
3757 dv->dv_dict = (PyDictObject *)dict;
3758 _PyObject_GC_TRACK(dv);
3759 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003760}
3761
Neal Norwitze36f2ba2007-02-26 23:12:28 +00003762/* TODO(guido): The views objects are not complete:
3763
3764 * support more set operations
3765 * support arbitrary mappings?
3766 - either these should be static or exported in dictobject.h
3767 - if public then they should probably be in builtins
3768*/
3769
Guido van Rossumaac530c2007-08-24 22:33:45 +00003770/* Return 1 if self is a subset of other, iterating over self;
3771 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00003772static int
3773all_contained_in(PyObject *self, PyObject *other)
3774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 PyObject *iter = PyObject_GetIter(self);
3776 int ok = 1;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 if (iter == NULL)
3779 return -1;
3780 for (;;) {
3781 PyObject *next = PyIter_Next(iter);
3782 if (next == NULL) {
3783 if (PyErr_Occurred())
3784 ok = -1;
3785 break;
3786 }
3787 ok = PySequence_Contains(other, next);
3788 Py_DECREF(next);
3789 if (ok <= 0)
3790 break;
3791 }
3792 Py_DECREF(iter);
3793 return ok;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003794}
3795
3796static PyObject *
3797dictview_richcompare(PyObject *self, PyObject *other, int op)
3798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 Py_ssize_t len_self, len_other;
3800 int ok;
3801 PyObject *result;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 assert(self != NULL);
3804 assert(PyDictViewSet_Check(self));
3805 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00003806
Brian Curtindfc80e32011-08-10 20:28:54 -05003807 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
3808 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003810 len_self = PyObject_Size(self);
3811 if (len_self < 0)
3812 return NULL;
3813 len_other = PyObject_Size(other);
3814 if (len_other < 0)
3815 return NULL;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003817 ok = 0;
3818 switch(op) {
Guido van Rossumaac530c2007-08-24 22:33:45 +00003819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 case Py_NE:
3821 case Py_EQ:
3822 if (len_self == len_other)
3823 ok = all_contained_in(self, other);
3824 if (op == Py_NE && ok >= 0)
3825 ok = !ok;
3826 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 case Py_LT:
3829 if (len_self < len_other)
3830 ok = all_contained_in(self, other);
3831 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 case Py_LE:
3834 if (len_self <= len_other)
3835 ok = all_contained_in(self, other);
3836 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 case Py_GT:
3839 if (len_self > len_other)
3840 ok = all_contained_in(other, self);
3841 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 case Py_GE:
3844 if (len_self >= len_other)
3845 ok = all_contained_in(other, self);
3846 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 }
3849 if (ok < 0)
3850 return NULL;
3851 result = ok ? Py_True : Py_False;
3852 Py_INCREF(result);
3853 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003854}
3855
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003856static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003857dictview_repr(_PyDictViewObject *dv)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003859 PyObject *seq;
bennorthd7773d92018-01-26 15:46:01 +00003860 PyObject *result = NULL;
3861 Py_ssize_t rc;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003862
bennorthd7773d92018-01-26 15:46:01 +00003863 rc = Py_ReprEnter((PyObject *)dv);
3864 if (rc != 0) {
3865 return rc > 0 ? PyUnicode_FromString("...") : NULL;
3866 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 seq = PySequence_List((PyObject *)dv);
bennorthd7773d92018-01-26 15:46:01 +00003868 if (seq == NULL) {
3869 goto Done;
3870 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
3872 Py_DECREF(seq);
bennorthd7773d92018-01-26 15:46:01 +00003873
3874Done:
3875 Py_ReprLeave((PyObject *)dv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003876 return result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003877}
3878
Guido van Rossum3ac67412007-02-10 18:55:06 +00003879/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003880
3881static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003882dictkeys_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 if (dv->dv_dict == NULL) {
3885 Py_RETURN_NONE;
3886 }
3887 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003888}
3889
3890static int
Eric Snow96c6af92015-05-29 22:21:39 -06003891dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00003892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 if (dv->dv_dict == NULL)
3894 return 0;
3895 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003896}
3897
Guido van Rossum83825ac2007-02-10 04:54:19 +00003898static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 (lenfunc)dictview_len, /* sq_length */
3900 0, /* sq_concat */
3901 0, /* sq_repeat */
3902 0, /* sq_item */
3903 0, /* sq_slice */
3904 0, /* sq_ass_item */
3905 0, /* sq_ass_slice */
3906 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003907};
3908
Guido van Rossum523259b2007-08-24 23:41:22 +00003909static PyObject*
3910dictviews_sub(PyObject* self, PyObject *other)
3911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 PyObject *result = PySet_New(self);
3913 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003914 _Py_IDENTIFIER(difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003916 if (result == NULL)
3917 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003918
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003919 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 if (tmp == NULL) {
3921 Py_DECREF(result);
3922 return NULL;
3923 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003925 Py_DECREF(tmp);
3926 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003927}
3928
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003929PyObject*
3930_PyDictView_Intersect(PyObject* self, PyObject *other)
Guido van Rossum523259b2007-08-24 23:41:22 +00003931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 PyObject *result = PySet_New(self);
3933 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003934 _Py_IDENTIFIER(intersection_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 if (result == NULL)
3937 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003938
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003939 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_intersection_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003940 if (tmp == NULL) {
3941 Py_DECREF(result);
3942 return NULL;
3943 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 Py_DECREF(tmp);
3946 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003947}
3948
3949static PyObject*
3950dictviews_or(PyObject* self, PyObject *other)
3951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 PyObject *result = PySet_New(self);
3953 PyObject *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02003954 _Py_IDENTIFIER(update);
Victor Stinnerd1a9cc22011-10-13 22:51:17 +02003955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 if (result == NULL)
3957 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003958
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003959 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 if (tmp == NULL) {
3961 Py_DECREF(result);
3962 return NULL;
3963 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 Py_DECREF(tmp);
3966 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003967}
3968
3969static PyObject*
3970dictviews_xor(PyObject* self, PyObject *other)
3971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 PyObject *result = PySet_New(self);
3973 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003974 _Py_IDENTIFIER(symmetric_difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 if (result == NULL)
3977 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003978
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003979 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_symmetric_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003980 if (tmp == NULL) {
3981 Py_DECREF(result);
3982 return NULL;
3983 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003985 Py_DECREF(tmp);
3986 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003987}
3988
3989static PyNumberMethods dictviews_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003990 0, /*nb_add*/
3991 (binaryfunc)dictviews_sub, /*nb_subtract*/
3992 0, /*nb_multiply*/
3993 0, /*nb_remainder*/
3994 0, /*nb_divmod*/
3995 0, /*nb_power*/
3996 0, /*nb_negative*/
3997 0, /*nb_positive*/
3998 0, /*nb_absolute*/
3999 0, /*nb_bool*/
4000 0, /*nb_invert*/
4001 0, /*nb_lshift*/
4002 0, /*nb_rshift*/
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004003 (binaryfunc)_PyDictView_Intersect, /*nb_and*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 (binaryfunc)dictviews_xor, /*nb_xor*/
4005 (binaryfunc)dictviews_or, /*nb_or*/
Guido van Rossum523259b2007-08-24 23:41:22 +00004006};
4007
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004008static PyObject*
4009dictviews_isdisjoint(PyObject *self, PyObject *other)
4010{
4011 PyObject *it;
4012 PyObject *item = NULL;
4013
4014 if (self == other) {
Eric Snow96c6af92015-05-29 22:21:39 -06004015 if (dictview_len((_PyDictViewObject *)self) == 0)
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004016 Py_RETURN_TRUE;
4017 else
4018 Py_RETURN_FALSE;
4019 }
4020
4021 /* Iterate over the shorter object (only if other is a set,
4022 * because PySequence_Contains may be expensive otherwise): */
4023 if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
Eric Snow96c6af92015-05-29 22:21:39 -06004024 Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004025 Py_ssize_t len_other = PyObject_Size(other);
4026 if (len_other == -1)
4027 return NULL;
4028
4029 if ((len_other > len_self)) {
4030 PyObject *tmp = other;
4031 other = self;
4032 self = tmp;
4033 }
4034 }
4035
4036 it = PyObject_GetIter(other);
4037 if (it == NULL)
4038 return NULL;
4039
4040 while ((item = PyIter_Next(it)) != NULL) {
4041 int contains = PySequence_Contains(self, item);
4042 Py_DECREF(item);
4043 if (contains == -1) {
4044 Py_DECREF(it);
4045 return NULL;
4046 }
4047
4048 if (contains) {
4049 Py_DECREF(it);
4050 Py_RETURN_FALSE;
4051 }
4052 }
4053 Py_DECREF(it);
4054 if (PyErr_Occurred())
4055 return NULL; /* PyIter_Next raised an exception. */
4056 Py_RETURN_TRUE;
4057}
4058
4059PyDoc_STRVAR(isdisjoint_doc,
4060"Return True if the view and the given iterable have a null intersection.");
4061
Guido van Rossumb90c8482007-02-10 01:11:45 +00004062static PyMethodDef dictkeys_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004063 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4064 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004066};
4067
4068PyTypeObject PyDictKeys_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4070 "dict_keys", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004071 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 0, /* tp_itemsize */
4073 /* methods */
4074 (destructor)dictview_dealloc, /* tp_dealloc */
4075 0, /* tp_print */
4076 0, /* tp_getattr */
4077 0, /* tp_setattr */
4078 0, /* tp_reserved */
4079 (reprfunc)dictview_repr, /* tp_repr */
4080 &dictviews_as_number, /* tp_as_number */
4081 &dictkeys_as_sequence, /* tp_as_sequence */
4082 0, /* tp_as_mapping */
4083 0, /* tp_hash */
4084 0, /* tp_call */
4085 0, /* tp_str */
4086 PyObject_GenericGetAttr, /* tp_getattro */
4087 0, /* tp_setattro */
4088 0, /* tp_as_buffer */
4089 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4090 0, /* tp_doc */
4091 (traverseproc)dictview_traverse, /* tp_traverse */
4092 0, /* tp_clear */
4093 dictview_richcompare, /* tp_richcompare */
4094 0, /* tp_weaklistoffset */
4095 (getiterfunc)dictkeys_iter, /* tp_iter */
4096 0, /* tp_iternext */
4097 dictkeys_methods, /* tp_methods */
4098 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004099};
4100
4101static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304102dictkeys_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004103{
Eric Snow96c6af92015-05-29 22:21:39 -06004104 return _PyDictView_New(dict, &PyDictKeys_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004105}
4106
Guido van Rossum3ac67412007-02-10 18:55:06 +00004107/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004108
4109static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004110dictitems_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 if (dv->dv_dict == NULL) {
4113 Py_RETURN_NONE;
4114 }
4115 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00004116}
4117
4118static int
Eric Snow96c6af92015-05-29 22:21:39 -06004119dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00004120{
Serhiy Storchaka753bca32017-05-20 12:30:02 +03004121 int result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122 PyObject *key, *value, *found;
4123 if (dv->dv_dict == NULL)
4124 return 0;
4125 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
4126 return 0;
4127 key = PyTuple_GET_ITEM(obj, 0);
4128 value = PyTuple_GET_ITEM(obj, 1);
Raymond Hettinger6692f012016-09-18 21:46:08 -07004129 found = PyDict_GetItemWithError((PyObject *)dv->dv_dict, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004130 if (found == NULL) {
4131 if (PyErr_Occurred())
4132 return -1;
4133 return 0;
4134 }
Serhiy Storchaka753bca32017-05-20 12:30:02 +03004135 Py_INCREF(found);
4136 result = PyObject_RichCompareBool(value, found, Py_EQ);
4137 Py_DECREF(found);
4138 return result;
Guido van Rossumb90c8482007-02-10 01:11:45 +00004139}
4140
Guido van Rossum83825ac2007-02-10 04:54:19 +00004141static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004142 (lenfunc)dictview_len, /* sq_length */
4143 0, /* sq_concat */
4144 0, /* sq_repeat */
4145 0, /* sq_item */
4146 0, /* sq_slice */
4147 0, /* sq_ass_item */
4148 0, /* sq_ass_slice */
4149 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004150};
4151
Guido van Rossumb90c8482007-02-10 01:11:45 +00004152static PyMethodDef dictitems_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004153 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4154 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004155 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004156};
4157
4158PyTypeObject PyDictItems_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4160 "dict_items", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004161 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004162 0, /* tp_itemsize */
4163 /* methods */
4164 (destructor)dictview_dealloc, /* tp_dealloc */
4165 0, /* tp_print */
4166 0, /* tp_getattr */
4167 0, /* tp_setattr */
4168 0, /* tp_reserved */
4169 (reprfunc)dictview_repr, /* tp_repr */
4170 &dictviews_as_number, /* tp_as_number */
4171 &dictitems_as_sequence, /* tp_as_sequence */
4172 0, /* tp_as_mapping */
4173 0, /* tp_hash */
4174 0, /* tp_call */
4175 0, /* tp_str */
4176 PyObject_GenericGetAttr, /* tp_getattro */
4177 0, /* tp_setattro */
4178 0, /* tp_as_buffer */
4179 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4180 0, /* tp_doc */
4181 (traverseproc)dictview_traverse, /* tp_traverse */
4182 0, /* tp_clear */
4183 dictview_richcompare, /* tp_richcompare */
4184 0, /* tp_weaklistoffset */
4185 (getiterfunc)dictitems_iter, /* tp_iter */
4186 0, /* tp_iternext */
4187 dictitems_methods, /* tp_methods */
4188 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004189};
4190
4191static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304192dictitems_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004193{
Eric Snow96c6af92015-05-29 22:21:39 -06004194 return _PyDictView_New(dict, &PyDictItems_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004195}
4196
Guido van Rossum3ac67412007-02-10 18:55:06 +00004197/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004198
4199static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004200dictvalues_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 if (dv->dv_dict == NULL) {
4203 Py_RETURN_NONE;
4204 }
4205 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004206}
4207
Guido van Rossum83825ac2007-02-10 04:54:19 +00004208static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 (lenfunc)dictview_len, /* sq_length */
4210 0, /* sq_concat */
4211 0, /* sq_repeat */
4212 0, /* sq_item */
4213 0, /* sq_slice */
4214 0, /* sq_ass_item */
4215 0, /* sq_ass_slice */
4216 (objobjproc)0, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004217};
4218
Guido van Rossumb90c8482007-02-10 01:11:45 +00004219static PyMethodDef dictvalues_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004220 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004221};
4222
4223PyTypeObject PyDictValues_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004224 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4225 "dict_values", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004226 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004227 0, /* tp_itemsize */
4228 /* methods */
4229 (destructor)dictview_dealloc, /* tp_dealloc */
4230 0, /* tp_print */
4231 0, /* tp_getattr */
4232 0, /* tp_setattr */
4233 0, /* tp_reserved */
4234 (reprfunc)dictview_repr, /* tp_repr */
4235 0, /* tp_as_number */
4236 &dictvalues_as_sequence, /* tp_as_sequence */
4237 0, /* tp_as_mapping */
4238 0, /* tp_hash */
4239 0, /* tp_call */
4240 0, /* tp_str */
4241 PyObject_GenericGetAttr, /* tp_getattro */
4242 0, /* tp_setattro */
4243 0, /* tp_as_buffer */
4244 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4245 0, /* tp_doc */
4246 (traverseproc)dictview_traverse, /* tp_traverse */
4247 0, /* tp_clear */
4248 0, /* tp_richcompare */
4249 0, /* tp_weaklistoffset */
4250 (getiterfunc)dictvalues_iter, /* tp_iter */
4251 0, /* tp_iternext */
4252 dictvalues_methods, /* tp_methods */
4253 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004254};
4255
4256static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304257dictvalues_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004258{
Eric Snow96c6af92015-05-29 22:21:39 -06004259 return _PyDictView_New(dict, &PyDictValues_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004260}
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004261
4262/* Returns NULL if cannot allocate a new PyDictKeysObject,
4263 but does not set an error */
4264PyDictKeysObject *
4265_PyDict_NewKeysForClass(void)
4266{
Victor Stinner742da042016-09-07 17:40:12 -07004267 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004268 if (keys == NULL)
4269 PyErr_Clear();
4270 else
4271 keys->dk_lookup = lookdict_split;
4272 return keys;
4273}
4274
4275#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
4276
4277PyObject *
4278PyObject_GenericGetDict(PyObject *obj, void *context)
4279{
4280 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
4281 if (dictptr == NULL) {
4282 PyErr_SetString(PyExc_AttributeError,
4283 "This object has no __dict__");
4284 return NULL;
4285 }
4286 dict = *dictptr;
4287 if (dict == NULL) {
4288 PyTypeObject *tp = Py_TYPE(obj);
4289 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
4290 DK_INCREF(CACHED_KEYS(tp));
4291 *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
4292 }
4293 else {
4294 *dictptr = dict = PyDict_New();
4295 }
4296 }
4297 Py_XINCREF(dict);
4298 return dict;
4299}
4300
4301int
4302_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
Victor Stinner742da042016-09-07 17:40:12 -07004303 PyObject *key, PyObject *value)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004304{
4305 PyObject *dict;
4306 int res;
4307 PyDictKeysObject *cached;
4308
4309 assert(dictptr != NULL);
4310 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
4311 assert(dictptr != NULL);
4312 dict = *dictptr;
4313 if (dict == NULL) {
4314 DK_INCREF(cached);
4315 dict = new_dict_with_shared_keys(cached);
4316 if (dict == NULL)
4317 return -1;
4318 *dictptr = dict;
4319 }
4320 if (value == NULL) {
4321 res = PyDict_DelItem(dict, key);
INADA Naoki2294f3a2017-02-12 13:51:30 +09004322 // Since key sharing dict doesn't allow deletion, PyDict_DelItem()
4323 // always converts dict to combined form.
4324 if ((cached = CACHED_KEYS(tp)) != NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004325 CACHED_KEYS(tp) = NULL;
4326 DK_DECREF(cached);
4327 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01004328 }
4329 else {
INADA Naoki2294f3a2017-02-12 13:51:30 +09004330 int was_shared = (cached == ((PyDictObject *)dict)->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004331 res = PyDict_SetItem(dict, key, value);
INADA Naoki2294f3a2017-02-12 13:51:30 +09004332 if (was_shared &&
4333 (cached = CACHED_KEYS(tp)) != NULL &&
4334 cached != ((PyDictObject *)dict)->ma_keys) {
Victor Stinner3d3f2642016-12-15 17:21:23 +01004335 /* PyDict_SetItem() may call dictresize and convert split table
4336 * into combined table. In such case, convert it to split
4337 * table again and update type's shared key only when this is
4338 * the only dict sharing key with the type.
4339 *
4340 * This is to allow using shared key in class like this:
4341 *
4342 * class C:
4343 * def __init__(self):
4344 * # one dict resize happens
4345 * self.a, self.b, self.c = 1, 2, 3
4346 * self.d, self.e, self.f = 4, 5, 6
4347 * a = C()
4348 */
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004349 if (cached->dk_refcnt == 1) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004350 CACHED_KEYS(tp) = make_keys_shared(dict);
Victor Stinner742da042016-09-07 17:40:12 -07004351 }
4352 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004353 CACHED_KEYS(tp) = NULL;
4354 }
4355 DK_DECREF(cached);
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004356 if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
4357 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004358 }
4359 }
4360 } else {
4361 dict = *dictptr;
4362 if (dict == NULL) {
4363 dict = PyDict_New();
4364 if (dict == NULL)
4365 return -1;
4366 *dictptr = dict;
4367 }
4368 if (value == NULL) {
4369 res = PyDict_DelItem(dict, key);
4370 } else {
4371 res = PyDict_SetItem(dict, key, value);
4372 }
4373 }
4374 return res;
4375}
4376
4377void
4378_PyDictKeys_DecRef(PyDictKeysObject *keys)
4379{
4380 DK_DECREF(keys);
4381}