blob: 08ec9e254ab2988690b7c731ad57c9cbaaf59a2e [file] [log] [blame]
Guido van Rossum2bc13791999-03-24 19:06:42 +00001/* Dictionary object implementation using a hash table */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002
Raymond Hettinger930427b2003-05-03 06:51:59 +00003/* The distribution includes a separate file, Objects/dictnotes.txt,
Tim Peters60b29962006-01-01 01:19:23 +00004 describing explorations into dictionary design and optimization.
Raymond Hettinger930427b2003-05-03 06:51:59 +00005 It covers typical dictionary use patterns, the parameters for
6 tuning dictionaries, and several ideas for possible optimizations.
7*/
8
Victor Stinner742da042016-09-07 17:40:12 -07009/* PyDictKeysObject
10
11This implements the dictionary's hashtable.
12
Raymond Hettingerb12785d2016-10-22 09:58:14 -070013As of Python 3.6, this is compact and ordered. Basic idea is described here:
14* https://mail.python.org/pipermail/python-dev/2012-December/123028.html
15* https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html
Victor Stinner742da042016-09-07 17:40:12 -070016
17layout:
18
19+---------------+
20| dk_refcnt |
21| dk_size |
22| dk_lookup |
23| dk_usable |
24| dk_nentries |
25+---------------+
26| dk_indices |
27| |
28+---------------+
29| dk_entries |
30| |
31+---------------+
32
33dk_indices is actual hashtable. It holds index in entries, or DKIX_EMPTY(-1)
34or DKIX_DUMMY(-2).
35Size of indices is dk_size. Type of each index in indices is vary on dk_size:
36
37* int8 for dk_size <= 128
38* int16 for 256 <= dk_size <= 2**15
39* int32 for 2**16 <= dk_size <= 2**31
40* int64 for 2**32 <= dk_size
41
42dk_entries is array of PyDictKeyEntry. It's size is USABLE_FRACTION(dk_size).
43DK_ENTRIES(dk) can be used to get pointer to entries.
44
45NOTE: Since negative value is used for DKIX_EMPTY and DKIX_DUMMY, type of
46dk_indices entry is signed integer and int16 is used for table which
47dk_size == 256.
48*/
49
Benjamin Peterson7d95e402012-04-23 11:24:50 -040050
51/*
Benjamin Peterson7d95e402012-04-23 11:24:50 -040052The DictObject can be in one of two forms.
Victor Stinner742da042016-09-07 17:40:12 -070053
Benjamin Peterson7d95e402012-04-23 11:24:50 -040054Either:
55 A combined table:
56 ma_values == NULL, dk_refcnt == 1.
57 Values are stored in the me_value field of the PyDictKeysObject.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040058Or:
59 A split table:
60 ma_values != NULL, dk_refcnt >= 1
61 Values are stored in the ma_values array.
Victor Stinner742da042016-09-07 17:40:12 -070062 Only string (unicode) keys are allowed.
63 All dicts sharing same key must have same insertion order.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040064
Victor Stinner742da042016-09-07 17:40:12 -070065There are four kinds of slots in the table (slot is index, and
66DK_ENTRIES(keys)[index] if index >= 0):
67
681. Unused. index == DKIX_EMPTY
69 Does not hold an active (key, value) pair now and never did. Unused can
70 transition to Active upon key insertion. This is each slot's initial state.
71
722. Active. index >= 0, me_key != NULL and me_value != NULL
73 Holds an active (key, value) pair. Active can transition to Dummy or
74 Pending upon key deletion (for combined and split tables respectively).
75 This is the only case in which me_value != NULL.
76
773. Dummy. index == DKIX_DUMMY (combined only)
78 Previously held an active (key, value) pair, but that was deleted and an
79 active pair has not yet overwritten the slot. Dummy can transition to
80 Active upon key insertion. Dummy slots cannot be made Unused again
81 else the probe sequence in case of collision would have no way to know
82 they were once active.
83
844. Pending. index >= 0, key != NULL, and value == NULL (split only)
85 Not yet inserted in split-table.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040086*/
87
Victor Stinner742da042016-09-07 17:40:12 -070088/*
89Preserving insertion order
Benjamin Peterson7d95e402012-04-23 11:24:50 -040090
Victor Stinner742da042016-09-07 17:40:12 -070091It's simple for combined table. Since dk_entries is mostly append only, we can
92get insertion order by just iterating dk_entries.
93
94One exception is .popitem(). It removes last item in dk_entries and decrement
95dk_nentries to achieve amortized O(1). Since there are DKIX_DUMMY remains in
96dk_indices, we can't increment dk_usable even though dk_nentries is
97decremented.
98
99In split table, inserting into pending entry is allowed only for dk_entries[ix]
100where ix == mp->ma_used. Inserting into other index and deleting item cause
101converting the dict to the combined table.
102*/
103
104/* PyDict_MINSIZE is the starting size for any new dict.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400105 * 8 allows dicts with no more than 5 active entries; experiments suggested
106 * this suffices for the majority of dicts (consisting mostly of usually-small
107 * dicts created to pass keyword arguments).
108 * Making this 8, rather than 4 reduces the number of resizes for most
109 * dictionaries, without any significant extra memory use.
110 */
Victor Stinner742da042016-09-07 17:40:12 -0700111#define PyDict_MINSIZE 8
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400112
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113#include "Python.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +0100114#include "pycore_state.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
INADA Naoki2aaf98c2018-09-26 12:59:00 +0900238static PyObject* dict_iter(PyDictObject *dict);
239
Benjamin Peterson3c569292016-09-08 13:16:41 -0700240/*Global counter used to set ma_version_tag field of dictionary.
Victor Stinner3b6a6b42016-09-08 12:51:24 -0700241 * It is incremented each time that a dictionary is created and each
242 * time that a dictionary is modified. */
243static uint64_t pydict_global_version = 0;
244
245#define DICT_NEXT_VERSION() (++pydict_global_version)
246
Victor Stinner742da042016-09-07 17:40:12 -0700247/* Dictionary reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +0000248#ifndef PyDict_MAXFREELIST
249#define PyDict_MAXFREELIST 80
250#endif
251static PyDictObject *free_list[PyDict_MAXFREELIST];
252static int numfree = 0;
Victor Stinner742da042016-09-07 17:40:12 -0700253static PyDictKeysObject *keys_free_list[PyDict_MAXFREELIST];
254static int numfreekeys = 0;
Raymond Hettinger43442782004-03-17 21:55:03 +0000255
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300256#include "clinic/dictobject.c.h"
257
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100258int
259PyDict_ClearFreeList(void)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 PyDictObject *op;
Victor Stinner742da042016-09-07 17:40:12 -0700262 int ret = numfree + numfreekeys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 while (numfree) {
264 op = free_list[--numfree];
265 assert(PyDict_CheckExact(op));
266 PyObject_GC_Del(op);
267 }
Victor Stinner742da042016-09-07 17:40:12 -0700268 while (numfreekeys) {
269 PyObject_FREE(keys_free_list[--numfreekeys]);
270 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100271 return ret;
272}
273
David Malcolm49526f42012-06-22 14:55:41 -0400274/* Print summary info about the state of the optimized allocator */
275void
276_PyDict_DebugMallocStats(FILE *out)
277{
278 _PyDebugAllocatorStats(out,
279 "free PyDictObject", numfree, sizeof(PyDictObject));
280}
281
282
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100283void
284PyDict_Fini(void)
285{
286 PyDict_ClearFreeList();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000287}
288
Victor Stinner742da042016-09-07 17:40:12 -0700289#define DK_SIZE(dk) ((dk)->dk_size)
290#if SIZEOF_VOID_P > 4
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700291#define DK_IXSIZE(dk) \
292 (DK_SIZE(dk) <= 0xff ? \
293 1 : DK_SIZE(dk) <= 0xffff ? \
294 2 : DK_SIZE(dk) <= 0xffffffff ? \
Benjamin Peterson3c569292016-09-08 13:16:41 -0700295 4 : sizeof(int64_t))
Victor Stinner742da042016-09-07 17:40:12 -0700296#else
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700297#define DK_IXSIZE(dk) \
298 (DK_SIZE(dk) <= 0xff ? \
299 1 : DK_SIZE(dk) <= 0xffff ? \
Benjamin Peterson3c569292016-09-08 13:16:41 -0700300 2 : sizeof(int32_t))
Victor Stinner742da042016-09-07 17:40:12 -0700301#endif
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700302#define DK_ENTRIES(dk) \
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700303 ((PyDictKeyEntry*)(&((int8_t*)((dk)->dk_indices))[DK_SIZE(dk) * DK_IXSIZE(dk)]))
Victor Stinner742da042016-09-07 17:40:12 -0700304
Antoine Pitrou2d169b22012-05-12 23:43:44 +0200305#define DK_DEBUG_INCREF _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA
306#define DK_DEBUG_DECREF _Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA
307
308#define DK_INCREF(dk) (DK_DEBUG_INCREF ++(dk)->dk_refcnt)
309#define DK_DECREF(dk) if (DK_DEBUG_DECREF (--(dk)->dk_refcnt) == 0) free_keys_object(dk)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400310#define DK_MASK(dk) (((dk)->dk_size)-1)
311#define IS_POWER_OF_2(x) (((x) & (x-1)) == 0)
312
Victor Stinner742da042016-09-07 17:40:12 -0700313/* lookup indices. returns DKIX_EMPTY, DKIX_DUMMY, or ix >=0 */
Benjamin Peterson73222252016-09-08 09:58:47 -0700314static inline Py_ssize_t
Victor Stinner742da042016-09-07 17:40:12 -0700315dk_get_index(PyDictKeysObject *keys, Py_ssize_t i)
316{
317 Py_ssize_t s = DK_SIZE(keys);
Victor Stinner71211e32016-09-08 10:52:46 -0700318 Py_ssize_t ix;
319
Victor Stinner742da042016-09-07 17:40:12 -0700320 if (s <= 0xff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700321 int8_t *indices = (int8_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700322 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700323 }
324 else if (s <= 0xffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700325 int16_t *indices = (int16_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700326 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700327 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700328#if SIZEOF_VOID_P > 4
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300329 else if (s > 0xffffffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700330 int64_t *indices = (int64_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700331 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700332 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700333#endif
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300334 else {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700335 int32_t *indices = (int32_t*)(keys->dk_indices);
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300336 ix = indices[i];
337 }
Victor Stinner71211e32016-09-08 10:52:46 -0700338 assert(ix >= DKIX_DUMMY);
339 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700340}
341
342/* write to indices. */
Benjamin Peterson73222252016-09-08 09:58:47 -0700343static inline void
Victor Stinner742da042016-09-07 17:40:12 -0700344dk_set_index(PyDictKeysObject *keys, Py_ssize_t i, Py_ssize_t ix)
345{
346 Py_ssize_t s = DK_SIZE(keys);
Victor Stinner71211e32016-09-08 10:52:46 -0700347
348 assert(ix >= DKIX_DUMMY);
349
Victor Stinner742da042016-09-07 17:40:12 -0700350 if (s <= 0xff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700351 int8_t *indices = (int8_t*)(keys->dk_indices);
Victor Stinner71211e32016-09-08 10:52:46 -0700352 assert(ix <= 0x7f);
Victor Stinner208857e2016-09-08 11:35:46 -0700353 indices[i] = (char)ix;
Victor Stinner742da042016-09-07 17:40:12 -0700354 }
355 else if (s <= 0xffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700356 int16_t *indices = (int16_t*)(keys->dk_indices);
Victor Stinner71211e32016-09-08 10:52:46 -0700357 assert(ix <= 0x7fff);
Victor Stinner208857e2016-09-08 11:35:46 -0700358 indices[i] = (int16_t)ix;
Victor Stinner742da042016-09-07 17:40:12 -0700359 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700360#if SIZEOF_VOID_P > 4
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300361 else if (s > 0xffffffff) {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700362 int64_t *indices = (int64_t*)(keys->dk_indices);
Victor Stinner208857e2016-09-08 11:35:46 -0700363 indices[i] = ix;
Victor Stinner742da042016-09-07 17:40:12 -0700364 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700365#endif
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300366 else {
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700367 int32_t *indices = (int32_t*)(keys->dk_indices);
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300368 assert(ix <= 0x7fffffff);
369 indices[i] = (int32_t)ix;
370 }
Victor Stinner742da042016-09-07 17:40:12 -0700371}
372
373
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200374/* USABLE_FRACTION is the maximum dictionary load.
Victor Stinner742da042016-09-07 17:40:12 -0700375 * Increasing this ratio makes dictionaries more dense resulting in more
376 * collisions. Decreasing it improves sparseness at the expense of spreading
377 * indices over more cache lines and at the cost of total memory consumed.
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200378 *
379 * USABLE_FRACTION must obey the following:
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400380 * (0 < USABLE_FRACTION(n) < n) for all n >= 2
381 *
Victor Stinner742da042016-09-07 17:40:12 -0700382 * USABLE_FRACTION should be quick to calculate.
383 * Fractions around 1/2 to 2/3 seem to work well in practice.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400384 */
Victor Stinner742da042016-09-07 17:40:12 -0700385#define USABLE_FRACTION(n) (((n) << 1)/3)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400386
Victor Stinner742da042016-09-07 17:40:12 -0700387/* ESTIMATE_SIZE is reverse function of USABLE_FRACTION.
388 * This can be used to reserve enough size to insert n entries without
389 * resizing.
390 */
INADA Naoki92c50ee2016-11-22 00:57:02 +0900391#define ESTIMATE_SIZE(n) (((n)*3+1) >> 1)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400392
Victor Stinner742da042016-09-07 17:40:12 -0700393/* Alternative fraction that is otherwise close enough to 2n/3 to make
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400394 * little difference. 8 * 2/3 == 8 * 5/8 == 5. 16 * 2/3 == 16 * 5/8 == 10.
395 * 32 * 2/3 = 21, 32 * 5/8 = 20.
396 * Its advantage is that it is faster to compute on machines with slow division.
397 * #define USABLE_FRACTION(n) (((n) >> 1) + ((n) >> 2) - ((n) >> 3))
Victor Stinner742da042016-09-07 17:40:12 -0700398 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400399
Victor Stinnera9f61a52013-07-16 22:17:26 +0200400/* GROWTH_RATE. Growth rate upon hitting maximum load.
INADA Naoki5fbc5112018-04-17 15:53:34 +0900401 * Currently set to used*3.
Victor Stinnera9f61a52013-07-16 22:17:26 +0200402 * This means that dicts double in size when growing without deletions,
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700403 * but have more head room when the number of deletions is on a par with the
INADA Naoki5fbc5112018-04-17 15:53:34 +0900404 * number of insertions. See also bpo-17563 and bpo-33205.
405 *
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700406 * GROWTH_RATE was set to used*4 up to version 3.2.
407 * GROWTH_RATE was set to used*2 in version 3.3.0
INADA Naoki5fbc5112018-04-17 15:53:34 +0900408 * GROWTH_RATE was set to used*2 + capacity/2 in 3.4.0-3.6.0.
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200409 */
INADA Naoki5fbc5112018-04-17 15:53:34 +0900410#define GROWTH_RATE(d) ((d)->ma_used*3)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400411
412#define ENSURE_ALLOWS_DELETIONS(d) \
413 if ((d)->ma_keys->dk_lookup == lookdict_unicode_nodummy) { \
414 (d)->ma_keys->dk_lookup = lookdict_unicode; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400416
417/* This immutable, empty PyDictKeysObject is used for PyDict_Clear()
418 * (which cannot fail and thus can do no allocation).
419 */
420static PyDictKeysObject empty_keys_struct = {
Serhiy Storchaka97932e42016-09-26 23:01:23 +0300421 1, /* dk_refcnt */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400422 1, /* dk_size */
423 lookdict_split, /* dk_lookup */
424 0, /* dk_usable (immutable) */
Victor Stinner742da042016-09-07 17:40:12 -0700425 0, /* dk_nentries */
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700426 {DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY,
427 DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY}, /* dk_indices */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400428};
429
430static PyObject *empty_values[1] = { NULL };
431
432#define Py_EMPTY_KEYS &empty_keys_struct
433
Victor Stinner611b0fa2016-09-14 15:02:01 +0200434/* Uncomment to check the dict content in _PyDict_CheckConsistency() */
435/* #define DEBUG_PYDICT */
436
437
T. Woutersa00c3fd2017-03-31 09:14:41 -0700438#ifndef NDEBUG
Victor Stinner611b0fa2016-09-14 15:02:01 +0200439static int
440_PyDict_CheckConsistency(PyDictObject *mp)
441{
Victor Stinner50fe3f82018-10-26 18:47:15 +0200442#define ASSERT(expr) _PyObject_ASSERT((PyObject *)mp, (expr))
443
Victor Stinner611b0fa2016-09-14 15:02:01 +0200444 PyDictKeysObject *keys = mp->ma_keys;
445 int splitted = _PyDict_HasSplitTable(mp);
446 Py_ssize_t usable = USABLE_FRACTION(keys->dk_size);
447#ifdef DEBUG_PYDICT
448 PyDictKeyEntry *entries = DK_ENTRIES(keys);
449 Py_ssize_t i;
450#endif
451
Victor Stinner50fe3f82018-10-26 18:47:15 +0200452 ASSERT(0 <= mp->ma_used && mp->ma_used <= usable);
453 ASSERT(IS_POWER_OF_2(keys->dk_size));
454 ASSERT(0 <= keys->dk_usable
Victor Stinner611b0fa2016-09-14 15:02:01 +0200455 && keys->dk_usable <= usable);
Victor Stinner50fe3f82018-10-26 18:47:15 +0200456 ASSERT(0 <= keys->dk_nentries
Victor Stinner611b0fa2016-09-14 15:02:01 +0200457 && keys->dk_nentries <= usable);
Victor Stinner50fe3f82018-10-26 18:47:15 +0200458 ASSERT(keys->dk_usable + keys->dk_nentries <= usable);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200459
460 if (!splitted) {
461 /* combined table */
Victor Stinner50fe3f82018-10-26 18:47:15 +0200462 ASSERT(keys->dk_refcnt == 1);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200463 }
464
465#ifdef DEBUG_PYDICT
466 for (i=0; i < keys->dk_size; i++) {
467 Py_ssize_t ix = dk_get_index(keys, i);
Victor Stinner50fe3f82018-10-26 18:47:15 +0200468 ASSERT(DKIX_DUMMY <= ix && ix <= usable);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200469 }
470
471 for (i=0; i < usable; i++) {
472 PyDictKeyEntry *entry = &entries[i];
473 PyObject *key = entry->me_key;
474
475 if (key != NULL) {
476 if (PyUnicode_CheckExact(key)) {
477 Py_hash_t hash = ((PyASCIIObject *)key)->hash;
Victor Stinner50fe3f82018-10-26 18:47:15 +0200478 ASSERT(hash != -1);
479 ASSERT(entry->me_hash == hash);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200480 }
481 else {
482 /* test_dict fails if PyObject_Hash() is called again */
Victor Stinner50fe3f82018-10-26 18:47:15 +0200483 ASSERT(entry->me_hash != -1);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200484 }
485 if (!splitted) {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200486 ASSERT(entry->me_value != NULL);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200487 }
488 }
489
490 if (splitted) {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200491 ASSERT(entry->me_value == NULL);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200492 }
493 }
494
495 if (splitted) {
496 /* splitted table */
497 for (i=0; i < mp->ma_used; i++) {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200498 ASSERT(mp->ma_values[i] != NULL);
Victor Stinner611b0fa2016-09-14 15:02:01 +0200499 }
500 }
501#endif
502
503 return 1;
Victor Stinner50fe3f82018-10-26 18:47:15 +0200504
505#undef ASSERT
Victor Stinner611b0fa2016-09-14 15:02:01 +0200506}
507#endif
508
509
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400510static PyDictKeysObject *new_keys_object(Py_ssize_t size)
511{
512 PyDictKeysObject *dk;
Victor Stinner742da042016-09-07 17:40:12 -0700513 Py_ssize_t es, usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400514
Victor Stinner742da042016-09-07 17:40:12 -0700515 assert(size >= PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400516 assert(IS_POWER_OF_2(size));
Victor Stinner742da042016-09-07 17:40:12 -0700517
518 usable = USABLE_FRACTION(size);
519 if (size <= 0xff) {
520 es = 1;
521 }
522 else if (size <= 0xffff) {
523 es = 2;
524 }
525#if SIZEOF_VOID_P > 4
526 else if (size <= 0xffffffff) {
527 es = 4;
528 }
529#endif
530 else {
531 es = sizeof(Py_ssize_t);
532 }
533
534 if (size == PyDict_MINSIZE && numfreekeys > 0) {
535 dk = keys_free_list[--numfreekeys];
536 }
537 else {
Victor Stinner98ee9d52016-09-08 09:33:56 -0700538 dk = PyObject_MALLOC(sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -0700539 + es * size
540 + sizeof(PyDictKeyEntry) * usable);
Victor Stinner742da042016-09-07 17:40:12 -0700541 if (dk == NULL) {
542 PyErr_NoMemory();
543 return NULL;
544 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400545 }
Antoine Pitrou2d169b22012-05-12 23:43:44 +0200546 DK_DEBUG_INCREF dk->dk_refcnt = 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400547 dk->dk_size = size;
Victor Stinner742da042016-09-07 17:40:12 -0700548 dk->dk_usable = usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400549 dk->dk_lookup = lookdict_unicode_nodummy;
Victor Stinner742da042016-09-07 17:40:12 -0700550 dk->dk_nentries = 0;
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700551 memset(&dk->dk_indices[0], 0xff, es * size);
Victor Stinner742da042016-09-07 17:40:12 -0700552 memset(DK_ENTRIES(dk), 0, sizeof(PyDictKeyEntry) * usable);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400553 return dk;
554}
555
556static void
557free_keys_object(PyDictKeysObject *keys)
558{
Victor Stinner742da042016-09-07 17:40:12 -0700559 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400560 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -0700561 for (i = 0, n = keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400562 Py_XDECREF(entries[i].me_key);
563 Py_XDECREF(entries[i].me_value);
564 }
Victor Stinner742da042016-09-07 17:40:12 -0700565 if (keys->dk_size == PyDict_MINSIZE && numfreekeys < PyDict_MAXFREELIST) {
566 keys_free_list[numfreekeys++] = keys;
567 return;
568 }
Raymond Hettingerce5179f2016-01-31 08:56:21 -0800569 PyObject_FREE(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400570}
571
572#define new_values(size) PyMem_NEW(PyObject *, size)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400573#define free_values(values) PyMem_FREE(values)
574
575/* Consumes a reference to the keys object */
576static PyObject *
577new_dict(PyDictKeysObject *keys, PyObject **values)
578{
579 PyDictObject *mp;
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200580 assert(keys != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 if (numfree) {
582 mp = free_list[--numfree];
583 assert (mp != NULL);
584 assert (Py_TYPE(mp) == &PyDict_Type);
585 _Py_NewReference((PyObject *)mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400587 else {
588 mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
589 if (mp == NULL) {
590 DK_DECREF(keys);
591 free_values(values);
592 return NULL;
593 }
594 }
595 mp->ma_keys = keys;
596 mp->ma_values = values;
597 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -0700598 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner611b0fa2016-09-14 15:02:01 +0200599 assert(_PyDict_CheckConsistency(mp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000601}
602
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400603/* Consumes a reference to the keys object */
604static PyObject *
605new_dict_with_shared_keys(PyDictKeysObject *keys)
606{
607 PyObject **values;
608 Py_ssize_t i, size;
609
Victor Stinner742da042016-09-07 17:40:12 -0700610 size = USABLE_FRACTION(DK_SIZE(keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400611 values = new_values(size);
612 if (values == NULL) {
613 DK_DECREF(keys);
614 return PyErr_NoMemory();
615 }
616 for (i = 0; i < size; i++) {
617 values[i] = NULL;
618 }
619 return new_dict(keys, values);
620}
621
Yury Selivanovb0a7a032018-01-22 11:54:41 -0500622
623static PyObject *
624clone_combined_dict(PyDictObject *orig)
625{
626 assert(PyDict_CheckExact(orig));
627 assert(orig->ma_values == NULL);
628 assert(orig->ma_keys->dk_refcnt == 1);
629
630 Py_ssize_t keys_size = _PyDict_KeysSize(orig->ma_keys);
631 PyDictKeysObject *keys = PyObject_Malloc(keys_size);
632 if (keys == NULL) {
633 PyErr_NoMemory();
634 return NULL;
635 }
636
637 memcpy(keys, orig->ma_keys, keys_size);
638
639 /* After copying key/value pairs, we need to incref all
640 keys and values and they are about to be co-owned by a
641 new dict object. */
642 PyDictKeyEntry *ep0 = DK_ENTRIES(keys);
643 Py_ssize_t n = keys->dk_nentries;
644 for (Py_ssize_t i = 0; i < n; i++) {
645 PyDictKeyEntry *entry = &ep0[i];
646 PyObject *value = entry->me_value;
647 if (value != NULL) {
648 Py_INCREF(value);
649 Py_INCREF(entry->me_key);
650 }
651 }
652
653 PyDictObject *new = (PyDictObject *)new_dict(keys, NULL);
654 if (new == NULL) {
655 /* In case of an error, `new_dict()` takes care of
656 cleaning up `keys`. */
657 return NULL;
658 }
659 new->ma_used = orig->ma_used;
660 assert(_PyDict_CheckConsistency(new));
661 if (_PyObject_GC_IS_TRACKED(orig)) {
662 /* Maintain tracking. */
663 _PyObject_GC_TRACK(new);
664 }
Yury Selivanov0b752282018-07-06 12:20:07 -0400665
666 /* Since we copied the keys table we now have an extra reference
667 in the system. Manually call _Py_INC_REFTOTAL to signal that
668 we have it now; calling DK_INCREF would be an error as
669 keys->dk_refcnt is already set to 1 (after memcpy). */
670 _Py_INC_REFTOTAL;
671
Yury Selivanovb0a7a032018-01-22 11:54:41 -0500672 return (PyObject *)new;
673}
674
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400675PyObject *
676PyDict_New(void)
677{
Victor Stinner742da042016-09-07 17:40:12 -0700678 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200679 if (keys == NULL)
680 return NULL;
681 return new_dict(keys, NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400682}
683
Victor Stinner742da042016-09-07 17:40:12 -0700684/* Search index of hash table from offset of entry table */
685static Py_ssize_t
686lookdict_index(PyDictKeysObject *k, Py_hash_t hash, Py_ssize_t index)
687{
Victor Stinner742da042016-09-07 17:40:12 -0700688 size_t mask = DK_MASK(k);
INADA Naoki073ae482017-06-23 15:22:50 +0900689 size_t perturb = (size_t)hash;
690 size_t i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700691
INADA Naoki073ae482017-06-23 15:22:50 +0900692 for (;;) {
693 Py_ssize_t ix = dk_get_index(k, i);
Victor Stinner742da042016-09-07 17:40:12 -0700694 if (ix == index) {
695 return i;
696 }
697 if (ix == DKIX_EMPTY) {
698 return DKIX_EMPTY;
699 }
INADA Naoki073ae482017-06-23 15:22:50 +0900700 perturb >>= PERTURB_SHIFT;
701 i = mask & (i*5 + perturb + 1);
Victor Stinner742da042016-09-07 17:40:12 -0700702 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700703 Py_UNREACHABLE();
Victor Stinner742da042016-09-07 17:40:12 -0700704}
705
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000706/*
707The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000708This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000709Open addressing is preferred over chaining since the link overhead for
710chaining would be substantial (100% with typical malloc overhead).
711
Tim Peterseb28ef22001-06-02 05:27:19 +0000712The initial probe index is computed as hash mod the table size. Subsequent
713probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000714
715All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000716
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000717The details in this version are due to Tim Peters, building on many past
Tim Peterseb28ef22001-06-02 05:27:19 +0000718contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000719Christian Tismer.
Fred Drake1bff34a2000-08-31 19:31:38 +0000720
Victor Stinner742da042016-09-07 17:40:12 -0700721lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a
Victor Stinnera4348cc2016-09-08 12:01:25 -0700722comparison raises an exception.
Guido van Rossum89d8c602007-09-18 17:26:56 +0000723lookdict_unicode() below is specialized to string keys, comparison of which can
INADA Naoki1b8df102017-02-20 22:48:10 +0900724never raise an exception; that function can never return DKIX_ERROR when key
725is string. Otherwise, it falls back to lookdict().
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400726lookdict_unicode_nodummy is further specialized for string keys that cannot be
727the <dummy> value.
INADA Naoki778928b2017-08-03 23:45:15 +0900728For both, when the key isn't found a DKIX_EMPTY is returned.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000729*/
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100730static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400731lookdict(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900732 Py_hash_t hash, PyObject **value_addr)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000733{
INADA Naoki778928b2017-08-03 23:45:15 +0900734 size_t i, mask, perturb;
Victor Stinner742da042016-09-07 17:40:12 -0700735 PyDictKeysObject *dk;
INADA Naoki778928b2017-08-03 23:45:15 +0900736 PyDictKeyEntry *ep0;
Tim Peterseb28ef22001-06-02 05:27:19 +0000737
Antoine Pitrou9a234902012-05-13 20:48:01 +0200738top:
Victor Stinner742da042016-09-07 17:40:12 -0700739 dk = mp->ma_keys;
Victor Stinner742da042016-09-07 17:40:12 -0700740 ep0 = DK_ENTRIES(dk);
INADA Naoki778928b2017-08-03 23:45:15 +0900741 mask = DK_MASK(dk);
742 perturb = hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700744
INADA Naoki778928b2017-08-03 23:45:15 +0900745 for (;;) {
746 Py_ssize_t ix = dk_get_index(dk, i);
Victor Stinner742da042016-09-07 17:40:12 -0700747 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700748 *value_addr = NULL;
749 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400750 }
INADA Naoki778928b2017-08-03 23:45:15 +0900751 if (ix >= 0) {
752 PyDictKeyEntry *ep = &ep0[ix];
753 assert(ep->me_key != NULL);
754 if (ep->me_key == key) {
755 *value_addr = ep->me_value;
756 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700757 }
INADA Naoki778928b2017-08-03 23:45:15 +0900758 if (ep->me_hash == hash) {
759 PyObject *startkey = ep->me_key;
760 Py_INCREF(startkey);
761 int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
762 Py_DECREF(startkey);
763 if (cmp < 0) {
764 *value_addr = NULL;
765 return DKIX_ERROR;
766 }
767 if (dk == mp->ma_keys && ep->me_key == startkey) {
768 if (cmp > 0) {
769 *value_addr = ep->me_value;
770 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700771 }
INADA Naoki778928b2017-08-03 23:45:15 +0900772 }
773 else {
774 /* The dict was mutated, restart */
775 goto top;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400776 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 }
INADA Naoki778928b2017-08-03 23:45:15 +0900779 perturb >>= PERTURB_SHIFT;
780 i = (i*5 + perturb + 1) & mask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700782 Py_UNREACHABLE();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000783}
784
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400785/* Specialized version for string-only keys */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100786static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400787lookdict_unicode(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900788 Py_hash_t hash, PyObject **value_addr)
Fred Drake1bff34a2000-08-31 19:31:38 +0000789{
Victor Stinner742da042016-09-07 17:40:12 -0700790 assert(mp->ma_values == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 /* Make sure this function doesn't have to handle non-unicode keys,
792 including subclasses of str; e.g., one reason to subclass
793 unicodes is to override __eq__, and for speed we don't cater to
794 that here. */
795 if (!PyUnicode_CheckExact(key)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400796 mp->ma_keys->dk_lookup = lookdict;
INADA Naoki778928b2017-08-03 23:45:15 +0900797 return lookdict(mp, key, hash, value_addr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 }
Tim Peters15d49292001-05-27 07:39:22 +0000799
INADA Naoki778928b2017-08-03 23:45:15 +0900800 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
801 size_t mask = DK_MASK(mp->ma_keys);
802 size_t perturb = (size_t)hash;
803 size_t i = (size_t)hash & mask;
804
805 for (;;) {
806 Py_ssize_t ix = dk_get_index(mp->ma_keys, i);
Victor Stinner742da042016-09-07 17:40:12 -0700807 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700808 *value_addr = NULL;
809 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400810 }
INADA Naoki778928b2017-08-03 23:45:15 +0900811 if (ix >= 0) {
812 PyDictKeyEntry *ep = &ep0[ix];
813 assert(ep->me_key != NULL);
814 assert(PyUnicode_CheckExact(ep->me_key));
815 if (ep->me_key == key ||
816 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
817 *value_addr = ep->me_value;
818 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700819 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400820 }
INADA Naoki778928b2017-08-03 23:45:15 +0900821 perturb >>= PERTURB_SHIFT;
822 i = mask & (i*5 + perturb + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700824 Py_UNREACHABLE();
Fred Drake1bff34a2000-08-31 19:31:38 +0000825}
826
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400827/* Faster version of lookdict_unicode when it is known that no <dummy> keys
828 * will be present. */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100829static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400830lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900831 Py_hash_t hash, PyObject **value_addr)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400832{
Victor Stinner742da042016-09-07 17:40:12 -0700833 assert(mp->ma_values == NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400834 /* Make sure this function doesn't have to handle non-unicode keys,
835 including subclasses of str; e.g., one reason to subclass
836 unicodes is to override __eq__, and for speed we don't cater to
837 that here. */
838 if (!PyUnicode_CheckExact(key)) {
839 mp->ma_keys->dk_lookup = lookdict;
INADA Naoki778928b2017-08-03 23:45:15 +0900840 return lookdict(mp, key, hash, value_addr);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400841 }
INADA Naoki778928b2017-08-03 23:45:15 +0900842
843 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
844 size_t mask = DK_MASK(mp->ma_keys);
845 size_t perturb = (size_t)hash;
846 size_t i = (size_t)hash & mask;
847
848 for (;;) {
849 Py_ssize_t ix = dk_get_index(mp->ma_keys, i);
Victor Stinner742da042016-09-07 17:40:12 -0700850 assert (ix != DKIX_DUMMY);
851 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700852 *value_addr = NULL;
853 return DKIX_EMPTY;
854 }
INADA Naoki778928b2017-08-03 23:45:15 +0900855 PyDictKeyEntry *ep = &ep0[ix];
856 assert(ep->me_key != NULL);
857 assert(PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700858 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400859 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
INADA Naokiba609772016-12-07 20:41:42 +0900860 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700861 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400862 }
INADA Naoki778928b2017-08-03 23:45:15 +0900863 perturb >>= PERTURB_SHIFT;
864 i = mask & (i*5 + perturb + 1);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400865 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700866 Py_UNREACHABLE();
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400867}
868
869/* Version of lookdict for split tables.
870 * All split tables and only split tables use this lookup function.
871 * Split tables only contain unicode keys and no dummy keys,
872 * so algorithm is the same as lookdict_unicode_nodummy.
873 */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100874static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400875lookdict_split(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900876 Py_hash_t hash, PyObject **value_addr)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400877{
Victor Stinner742da042016-09-07 17:40:12 -0700878 /* mp must split table */
879 assert(mp->ma_values != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400880 if (!PyUnicode_CheckExact(key)) {
INADA Naoki778928b2017-08-03 23:45:15 +0900881 Py_ssize_t ix = lookdict(mp, key, hash, value_addr);
Victor Stinner742da042016-09-07 17:40:12 -0700882 if (ix >= 0) {
INADA Naokiba609772016-12-07 20:41:42 +0900883 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700884 }
885 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400886 }
Victor Stinner742da042016-09-07 17:40:12 -0700887
INADA Naoki778928b2017-08-03 23:45:15 +0900888 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
889 size_t mask = DK_MASK(mp->ma_keys);
890 size_t perturb = (size_t)hash;
891 size_t i = (size_t)hash & mask;
892
893 for (;;) {
894 Py_ssize_t ix = dk_get_index(mp->ma_keys, i);
895 assert (ix != DKIX_DUMMY);
Victor Stinner742da042016-09-07 17:40:12 -0700896 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700897 *value_addr = NULL;
898 return DKIX_EMPTY;
899 }
INADA Naoki778928b2017-08-03 23:45:15 +0900900 PyDictKeyEntry *ep = &ep0[ix];
901 assert(ep->me_key != NULL);
902 assert(PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700903 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400904 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
INADA Naokiba609772016-12-07 20:41:42 +0900905 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700906 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400907 }
INADA Naoki778928b2017-08-03 23:45:15 +0900908 perturb >>= PERTURB_SHIFT;
909 i = mask & (i*5 + perturb + 1);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400910 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700911 Py_UNREACHABLE();
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400912}
913
Benjamin Petersonfb886362010-04-24 18:21:17 +0000914int
915_PyDict_HasOnlyStringKeys(PyObject *dict)
916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 Py_ssize_t pos = 0;
918 PyObject *key, *value;
Benjamin Petersonf6096542010-11-17 22:33:12 +0000919 assert(PyDict_Check(dict));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 /* Shortcut */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400921 if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 return 1;
923 while (PyDict_Next(dict, &pos, &key, &value))
924 if (!PyUnicode_Check(key))
925 return 0;
926 return 1;
Benjamin Petersonfb886362010-04-24 18:21:17 +0000927}
928
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000929#define MAINTAIN_TRACKING(mp, key, value) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 do { \
931 if (!_PyObject_GC_IS_TRACKED(mp)) { \
932 if (_PyObject_GC_MAY_BE_TRACKED(key) || \
933 _PyObject_GC_MAY_BE_TRACKED(value)) { \
934 _PyObject_GC_TRACK(mp); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 } \
936 } \
937 } while(0)
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000938
939void
940_PyDict_MaybeUntrack(PyObject *op)
941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 PyDictObject *mp;
943 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -0700944 Py_ssize_t i, numentries;
945 PyDictKeyEntry *ep0;
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
948 return;
949
950 mp = (PyDictObject *) op;
Victor Stinner742da042016-09-07 17:40:12 -0700951 ep0 = DK_ENTRIES(mp->ma_keys);
952 numentries = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400953 if (_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -0700954 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400955 if ((value = mp->ma_values[i]) == NULL)
956 continue;
957 if (_PyObject_GC_MAY_BE_TRACKED(value)) {
Victor Stinner742da042016-09-07 17:40:12 -0700958 assert(!_PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400959 return;
960 }
961 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400963 else {
Victor Stinner742da042016-09-07 17:40:12 -0700964 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400965 if ((value = ep0[i].me_value) == NULL)
966 continue;
967 if (_PyObject_GC_MAY_BE_TRACKED(value) ||
968 _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
969 return;
970 }
971 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 _PyObject_GC_UNTRACK(op);
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000973}
974
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400975/* Internal function to find slot for an item from its hash
Victor Stinner3c336c52016-09-12 14:17:40 +0200976 when it is known that the key is not present in the dict.
977
978 The dict must be combined. */
INADA Naokiba609772016-12-07 20:41:42 +0900979static Py_ssize_t
INADA Naoki778928b2017-08-03 23:45:15 +0900980find_empty_slot(PyDictKeysObject *keys, Py_hash_t hash)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000981{
INADA Naoki778928b2017-08-03 23:45:15 +0900982 assert(keys != NULL);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000983
INADA Naoki778928b2017-08-03 23:45:15 +0900984 const size_t mask = DK_MASK(keys);
985 size_t i = hash & mask;
986 Py_ssize_t ix = dk_get_index(keys, i);
987 for (size_t perturb = hash; ix >= 0;) {
INADA Naoki267941c2016-10-06 15:19:07 +0900988 perturb >>= PERTURB_SHIFT;
INADA Naoki778928b2017-08-03 23:45:15 +0900989 i = (i*5 + perturb + 1) & mask;
990 ix = dk_get_index(keys, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 }
INADA Naoki778928b2017-08-03 23:45:15 +0900992 return i;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000993}
994
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400995static int
996insertion_resize(PyDictObject *mp)
997{
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700998 return dictresize(mp, GROWTH_RATE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400999}
Antoine Pitroue965d972012-02-27 00:45:12 +01001000
1001/*
1002Internal routine to insert a new item into the table.
1003Used both by the internal resize routine and by the public insert routine.
Antoine Pitroue965d972012-02-27 00:45:12 +01001004Returns -1 if an error occurred, or 0 on success.
1005*/
1006static int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001007insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001008{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001009 PyObject *old_value;
INADA Naokiba609772016-12-07 20:41:42 +09001010 PyDictKeyEntry *ep;
Antoine Pitroue965d972012-02-27 00:45:12 +01001011
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001012 Py_INCREF(key);
1013 Py_INCREF(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001014 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
1015 if (insertion_resize(mp) < 0)
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001016 goto Fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001017 }
1018
INADA Naoki778928b2017-08-03 23:45:15 +09001019 Py_ssize_t ix = mp->ma_keys->dk_lookup(mp, key, hash, &old_value);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001020 if (ix == DKIX_ERROR)
1021 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001022
Antoine Pitroud6967322014-10-18 00:35:00 +02001023 assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001024 MAINTAIN_TRACKING(mp, key, value);
Victor Stinner742da042016-09-07 17:40:12 -07001025
1026 /* When insertion order is different from shared key, we can't share
1027 * the key anymore. Convert this instance to combine table.
1028 */
1029 if (_PyDict_HasSplitTable(mp) &&
INADA Naokiba609772016-12-07 20:41:42 +09001030 ((ix >= 0 && old_value == NULL && mp->ma_used != ix) ||
Victor Stinner742da042016-09-07 17:40:12 -07001031 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001032 if (insertion_resize(mp) < 0)
1033 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001034 ix = DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001035 }
Victor Stinner742da042016-09-07 17:40:12 -07001036
1037 if (ix == DKIX_EMPTY) {
1038 /* Insert into new slot. */
INADA Naokiba609772016-12-07 20:41:42 +09001039 assert(old_value == NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001040 if (mp->ma_keys->dk_usable <= 0) {
1041 /* Need to resize. */
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001042 if (insertion_resize(mp) < 0)
1043 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001044 }
INADA Naoki778928b2017-08-03 23:45:15 +09001045 Py_ssize_t hashpos = find_empty_slot(mp->ma_keys, hash);
INADA Naokiba609772016-12-07 20:41:42 +09001046 ep = &DK_ENTRIES(mp->ma_keys)[mp->ma_keys->dk_nentries];
Victor Stinner742da042016-09-07 17:40:12 -07001047 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
Victor Stinner742da042016-09-07 17:40:12 -07001048 ep->me_key = key;
1049 ep->me_hash = hash;
1050 if (mp->ma_values) {
1051 assert (mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
1052 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001053 }
1054 else {
Victor Stinner742da042016-09-07 17:40:12 -07001055 ep->me_value = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001056 }
1057 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001058 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07001059 mp->ma_keys->dk_usable--;
1060 mp->ma_keys->dk_nentries++;
1061 assert(mp->ma_keys->dk_usable >= 0);
Victor Stinner611b0fa2016-09-14 15:02:01 +02001062 assert(_PyDict_CheckConsistency(mp));
Victor Stinner742da042016-09-07 17:40:12 -07001063 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001064 }
Victor Stinner742da042016-09-07 17:40:12 -07001065
INADA Naokiba609772016-12-07 20:41:42 +09001066 if (_PyDict_HasSplitTable(mp)) {
1067 mp->ma_values[ix] = value;
1068 if (old_value == NULL) {
1069 /* pending state */
1070 assert(ix == mp->ma_used);
1071 mp->ma_used++;
1072 }
1073 }
1074 else {
1075 assert(old_value != NULL);
1076 DK_ENTRIES(mp->ma_keys)[ix].me_value = value;
Victor Stinner742da042016-09-07 17:40:12 -07001077 }
1078
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001079 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naokiba609772016-12-07 20:41:42 +09001080 Py_XDECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
Victor Stinner611b0fa2016-09-14 15:02:01 +02001081 assert(_PyDict_CheckConsistency(mp));
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001082 Py_DECREF(key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001083 return 0;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001084
1085Fail:
1086 Py_DECREF(value);
1087 Py_DECREF(key);
1088 return -1;
Antoine Pitroue965d972012-02-27 00:45:12 +01001089}
1090
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001091/*
luzpaza5293b42017-11-05 07:37:50 -06001092Internal routine used by dictresize() to build a hashtable of entries.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001093*/
1094static void
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001095build_indices(PyDictKeysObject *keys, PyDictKeyEntry *ep, Py_ssize_t n)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001096{
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001097 size_t mask = (size_t)DK_SIZE(keys) - 1;
1098 for (Py_ssize_t ix = 0; ix != n; ix++, ep++) {
1099 Py_hash_t hash = ep->me_hash;
1100 size_t i = hash & mask;
1101 for (size_t perturb = hash; dk_get_index(keys, i) != DKIX_EMPTY;) {
1102 perturb >>= PERTURB_SHIFT;
INADA Naoki870c2862017-06-24 09:03:19 +09001103 i = mask & (i*5 + perturb + 1);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001104 }
1105 dk_set_index(keys, i, ix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001107}
1108
1109/*
1110Restructure the table by allocating a new table and reinserting all
1111items again. When entries have been deleted, the new table may
1112actually be smaller than the old one.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001113If a table is split (its keys and hashes are shared, its values are not),
1114then the values are temporarily copied into the table, it is resized as
1115a combined table, then the me_value slots in the old table are NULLed out.
1116After resizing a table is always combined,
1117but can be resplit by make_keys_shared().
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001118*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001119static int
Victor Stinner3d3f2642016-12-15 17:21:23 +01001120dictresize(PyDictObject *mp, Py_ssize_t minsize)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001121{
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001122 Py_ssize_t newsize, numentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001123 PyDictKeysObject *oldkeys;
1124 PyObject **oldvalues;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001125 PyDictKeyEntry *oldentries, *newentries;
Tim Peters91a364d2001-05-19 07:04:38 +00001126
Victor Stinner742da042016-09-07 17:40:12 -07001127 /* Find the smallest table size > minused. */
1128 for (newsize = PyDict_MINSIZE;
Victor Stinner3d3f2642016-12-15 17:21:23 +01001129 newsize < minsize && newsize > 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 newsize <<= 1)
1131 ;
1132 if (newsize <= 0) {
1133 PyErr_NoMemory();
1134 return -1;
1135 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001136
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001137 oldkeys = mp->ma_keys;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001138
1139 /* NOTE: Current odict checks mp->ma_keys to detect resize happen.
1140 * So we can't reuse oldkeys even if oldkeys->dk_size == newsize.
1141 * TODO: Try reusing oldkeys when reimplement odict.
1142 */
1143
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001144 /* Allocate a new table. */
1145 mp->ma_keys = new_keys_object(newsize);
1146 if (mp->ma_keys == NULL) {
1147 mp->ma_keys = oldkeys;
1148 return -1;
1149 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01001150 // New table must be large enough.
1151 assert(mp->ma_keys->dk_usable >= mp->ma_used);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001152 if (oldkeys->dk_lookup == lookdict)
1153 mp->ma_keys->dk_lookup = lookdict;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001154
1155 numentries = mp->ma_used;
1156 oldentries = DK_ENTRIES(oldkeys);
1157 newentries = DK_ENTRIES(mp->ma_keys);
1158 oldvalues = mp->ma_values;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001159 if (oldvalues != NULL) {
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001160 /* Convert split table into new combined table.
1161 * We must incref keys; we can transfer values.
1162 * Note that values of split table is always dense.
1163 */
1164 for (Py_ssize_t i = 0; i < numentries; i++) {
1165 assert(oldvalues[i] != NULL);
1166 PyDictKeyEntry *ep = &oldentries[i];
1167 PyObject *key = ep->me_key;
1168 Py_INCREF(key);
1169 newentries[i].me_key = key;
1170 newentries[i].me_hash = ep->me_hash;
1171 newentries[i].me_value = oldvalues[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001173
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001174 DK_DECREF(oldkeys);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001175 mp->ma_values = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001176 if (oldvalues != empty_values) {
1177 free_values(oldvalues);
1178 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001179 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001180 else { // combined table.
1181 if (oldkeys->dk_nentries == numentries) {
1182 memcpy(newentries, oldentries, numentries * sizeof(PyDictKeyEntry));
1183 }
1184 else {
1185 PyDictKeyEntry *ep = oldentries;
1186 for (Py_ssize_t i = 0; i < numentries; i++) {
1187 while (ep->me_value == NULL)
1188 ep++;
1189 newentries[i] = *ep++;
1190 }
1191 }
1192
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001193 assert(oldkeys->dk_lookup != lookdict_split);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001194 assert(oldkeys->dk_refcnt == 1);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001195 if (oldkeys->dk_size == PyDict_MINSIZE &&
1196 numfreekeys < PyDict_MAXFREELIST) {
1197 DK_DEBUG_DECREF keys_free_list[numfreekeys++] = oldkeys;
1198 }
1199 else {
1200 DK_DEBUG_DECREF PyObject_FREE(oldkeys);
1201 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001202 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001203
1204 build_indices(mp->ma_keys, newentries, numentries);
1205 mp->ma_keys->dk_usable -= numentries;
1206 mp->ma_keys->dk_nentries = numentries;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001208}
1209
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001210/* Returns NULL if unable to split table.
1211 * A NULL return does not necessarily indicate an error */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001212static PyDictKeysObject *
1213make_keys_shared(PyObject *op)
1214{
1215 Py_ssize_t i;
1216 Py_ssize_t size;
1217 PyDictObject *mp = (PyDictObject *)op;
1218
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001219 if (!PyDict_CheckExact(op))
1220 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001221 if (!_PyDict_HasSplitTable(mp)) {
1222 PyDictKeyEntry *ep0;
1223 PyObject **values;
1224 assert(mp->ma_keys->dk_refcnt == 1);
1225 if (mp->ma_keys->dk_lookup == lookdict) {
1226 return NULL;
1227 }
1228 else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
1229 /* Remove dummy keys */
1230 if (dictresize(mp, DK_SIZE(mp->ma_keys)))
1231 return NULL;
1232 }
1233 assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
1234 /* Copy values into a new array */
Victor Stinner742da042016-09-07 17:40:12 -07001235 ep0 = DK_ENTRIES(mp->ma_keys);
1236 size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001237 values = new_values(size);
1238 if (values == NULL) {
1239 PyErr_SetString(PyExc_MemoryError,
1240 "Not enough memory to allocate new values array");
1241 return NULL;
1242 }
1243 for (i = 0; i < size; i++) {
1244 values[i] = ep0[i].me_value;
1245 ep0[i].me_value = NULL;
1246 }
1247 mp->ma_keys->dk_lookup = lookdict_split;
1248 mp->ma_values = values;
1249 }
1250 DK_INCREF(mp->ma_keys);
1251 return mp->ma_keys;
1252}
Christian Heimes99170a52007-12-19 02:07:34 +00001253
1254PyObject *
1255_PyDict_NewPresized(Py_ssize_t minused)
1256{
INADA Naoki92c50ee2016-11-22 00:57:02 +09001257 const Py_ssize_t max_presize = 128 * 1024;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001258 Py_ssize_t newsize;
1259 PyDictKeysObject *new_keys;
INADA Naoki92c50ee2016-11-22 00:57:02 +09001260
1261 /* There are no strict guarantee that returned dict can contain minused
1262 * items without resize. So we create medium size dict instead of very
1263 * large dict or MemoryError.
1264 */
1265 if (minused > USABLE_FRACTION(max_presize)) {
1266 newsize = max_presize;
1267 }
1268 else {
1269 Py_ssize_t minsize = ESTIMATE_SIZE(minused);
1270 newsize = PyDict_MINSIZE;
1271 while (newsize < minsize) {
1272 newsize <<= 1;
1273 }
1274 }
1275 assert(IS_POWER_OF_2(newsize));
1276
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001277 new_keys = new_keys_object(newsize);
1278 if (new_keys == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001280 return new_dict(new_keys, NULL);
Christian Heimes99170a52007-12-19 02:07:34 +00001281}
1282
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001283/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
1284 * that may occur (originally dicts supported only string keys, and exceptions
1285 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001286 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001287 * (suppressed) occurred while computing the key's hash, or that some error
1288 * (suppressed) occurred when comparing keys in the dict's internal probe
1289 * sequence. A nasty example of the latter is when a Python-coded comparison
1290 * function hits a stack-depth error, which can cause this to return NULL
1291 * even if the key is present.
1292 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001293PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001294PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001295{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001296 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001297 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 PyDictObject *mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 PyThreadState *tstate;
INADA Naokiba609772016-12-07 20:41:42 +09001300 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 if (!PyDict_Check(op))
1303 return NULL;
1304 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001305 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 {
1307 hash = PyObject_Hash(key);
1308 if (hash == -1) {
1309 PyErr_Clear();
1310 return NULL;
1311 }
1312 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 /* We can arrive here with a NULL tstate during initialization: try
1315 running "python -Wi" for an example related to string interning.
1316 Let's just hope that no exception occurs then... This must be
Victor Stinner50b48572018-11-01 01:51:40 +01001317 _PyThreadState_GET() and not PyThreadState_Get() because the latter
Victor Stinner9204fb82018-10-30 15:13:17 +01001318 abort Python if tstate is NULL. */
Victor Stinner50b48572018-11-01 01:51:40 +01001319 tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 if (tstate != NULL && tstate->curexc_type != NULL) {
1321 /* preserve the existing exception */
1322 PyObject *err_type, *err_value, *err_tb;
1323 PyErr_Fetch(&err_type, &err_value, &err_tb);
INADA Naoki778928b2017-08-03 23:45:15 +09001324 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 /* ignore errors */
1326 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001327 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 return NULL;
1329 }
1330 else {
INADA Naoki778928b2017-08-03 23:45:15 +09001331 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001332 if (ix < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 PyErr_Clear();
1334 return NULL;
1335 }
1336 }
INADA Naokiba609772016-12-07 20:41:42 +09001337 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001338}
1339
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001340/* Same as PyDict_GetItemWithError() but with hash supplied by caller.
1341 This returns NULL *with* an exception set if an exception occurred.
1342 It returns NULL *without* an exception set if the key wasn't present.
1343*/
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001344PyObject *
1345_PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1346{
Victor Stinner742da042016-09-07 17:40:12 -07001347 Py_ssize_t ix;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001348 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001349 PyObject *value;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001350
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001351 if (!PyDict_Check(op)) {
1352 PyErr_BadInternalCall();
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001353 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001354 }
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001355
INADA Naoki778928b2017-08-03 23:45:15 +09001356 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001357 if (ix < 0) {
1358 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001359 }
INADA Naokiba609772016-12-07 20:41:42 +09001360 return value;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001361}
1362
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001363/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
1364 This returns NULL *with* an exception set if an exception occurred.
1365 It returns NULL *without* an exception set if the key wasn't present.
1366*/
1367PyObject *
1368PyDict_GetItemWithError(PyObject *op, PyObject *key)
1369{
Victor Stinner742da042016-09-07 17:40:12 -07001370 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001371 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 PyDictObject*mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001373 PyObject *value;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 if (!PyDict_Check(op)) {
1376 PyErr_BadInternalCall();
1377 return NULL;
1378 }
1379 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001380 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 {
1382 hash = PyObject_Hash(key);
1383 if (hash == -1) {
1384 return NULL;
1385 }
1386 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001387
INADA Naoki778928b2017-08-03 23:45:15 +09001388 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001389 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001391 return value;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001392}
1393
Brett Cannonfd074152012-04-14 14:10:13 -04001394PyObject *
1395_PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
1396{
1397 PyObject *kv;
1398 kv = _PyUnicode_FromId(key); /* borrowed */
1399 if (kv == NULL)
1400 return NULL;
1401 return PyDict_GetItemWithError(dp, kv);
1402}
1403
Victor Stinnerb4efc962015-11-20 09:24:02 +01001404/* Fast version of global value lookup (LOAD_GLOBAL).
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001405 * Lookup in globals, then builtins.
Victor Stinnerb4efc962015-11-20 09:24:02 +01001406 *
1407 * Raise an exception and return NULL if an error occurred (ex: computing the
1408 * key hash failed, key comparison failed, ...). Return NULL if the key doesn't
1409 * exist. Return the value if the key exists.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001410 */
1411PyObject *
1412_PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001413{
Victor Stinner742da042016-09-07 17:40:12 -07001414 Py_ssize_t ix;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001415 Py_hash_t hash;
INADA Naokiba609772016-12-07 20:41:42 +09001416 PyObject *value;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001417
1418 if (!PyUnicode_CheckExact(key) ||
1419 (hash = ((PyASCIIObject *) key)->hash) == -1)
1420 {
1421 hash = PyObject_Hash(key);
1422 if (hash == -1)
1423 return NULL;
Antoine Pitroue965d972012-02-27 00:45:12 +01001424 }
Victor Stinnerb4efc962015-11-20 09:24:02 +01001425
1426 /* namespace 1: globals */
INADA Naoki778928b2017-08-03 23:45:15 +09001427 ix = globals->ma_keys->dk_lookup(globals, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001428 if (ix == DKIX_ERROR)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001429 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001430 if (ix != DKIX_EMPTY && value != NULL)
1431 return value;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001432
1433 /* namespace 2: builtins */
INADA Naoki778928b2017-08-03 23:45:15 +09001434 ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001435 if (ix < 0)
Victor Stinnerb4efc962015-11-20 09:24:02 +01001436 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001437 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001438}
1439
Antoine Pitroue965d972012-02-27 00:45:12 +01001440/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
1441 * dictionary if it's merely replacing the value for an existing key.
1442 * This means that it's safe to loop over a dictionary with PyDict_Next()
1443 * and occasionally replace a value -- but you can't insert new keys or
1444 * remove them.
1445 */
1446int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001447PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001448{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001449 PyDictObject *mp;
1450 Py_hash_t hash;
Antoine Pitroue965d972012-02-27 00:45:12 +01001451 if (!PyDict_Check(op)) {
1452 PyErr_BadInternalCall();
1453 return -1;
1454 }
1455 assert(key);
1456 assert(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001457 mp = (PyDictObject *)op;
1458 if (!PyUnicode_CheckExact(key) ||
1459 (hash = ((PyASCIIObject *) key)->hash) == -1)
1460 {
Antoine Pitroue965d972012-02-27 00:45:12 +01001461 hash = PyObject_Hash(key);
1462 if (hash == -1)
1463 return -1;
1464 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001465
1466 /* insertdict() handles any resizing that might be necessary */
1467 return insertdict(mp, key, hash, value);
Antoine Pitroue965d972012-02-27 00:45:12 +01001468}
1469
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001470int
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001471_PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
1472 Py_hash_t hash)
1473{
1474 PyDictObject *mp;
1475
1476 if (!PyDict_Check(op)) {
1477 PyErr_BadInternalCall();
1478 return -1;
1479 }
1480 assert(key);
1481 assert(value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001482 assert(hash != -1);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001483 mp = (PyDictObject *)op;
1484
1485 /* insertdict() handles any resizing that might be necessary */
1486 return insertdict(mp, key, hash, value);
1487}
1488
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001489static int
INADA Naoki778928b2017-08-03 23:45:15 +09001490delitem_common(PyDictObject *mp, Py_hash_t hash, Py_ssize_t ix,
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001491 PyObject *old_value)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001492{
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001493 PyObject *old_key;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001494 PyDictKeyEntry *ep;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001495
INADA Naoki778928b2017-08-03 23:45:15 +09001496 Py_ssize_t hashpos = lookdict_index(mp->ma_keys, hash, ix);
1497 assert(hashpos >= 0);
1498
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001499 mp->ma_used--;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001500 mp->ma_version_tag = DICT_NEXT_VERSION();
1501 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1502 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1503 ENSURE_ALLOWS_DELETIONS(mp);
1504 old_key = ep->me_key;
1505 ep->me_key = NULL;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001506 ep->me_value = NULL;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001507 Py_DECREF(old_key);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001508 Py_DECREF(old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001509
1510 assert(_PyDict_CheckConsistency(mp));
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001511 return 0;
1512}
1513
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001514int
Tim Peters1f5871e2000-07-04 17:44:48 +00001515PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001516{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001517 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 assert(key);
1519 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001520 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 hash = PyObject_Hash(key);
1522 if (hash == -1)
1523 return -1;
1524 }
Victor Stinner742da042016-09-07 17:40:12 -07001525
1526 return _PyDict_DelItem_KnownHash(op, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001527}
1528
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001529int
1530_PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1531{
INADA Naoki778928b2017-08-03 23:45:15 +09001532 Py_ssize_t ix;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001533 PyDictObject *mp;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001534 PyObject *old_value;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001535
1536 if (!PyDict_Check(op)) {
1537 PyErr_BadInternalCall();
1538 return -1;
1539 }
1540 assert(key);
1541 assert(hash != -1);
1542 mp = (PyDictObject *)op;
INADA Naoki778928b2017-08-03 23:45:15 +09001543 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner742da042016-09-07 17:40:12 -07001544 if (ix == DKIX_ERROR)
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001545 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09001546 if (ix == DKIX_EMPTY || old_value == NULL) {
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001547 _PyErr_SetKeyError(key);
1548 return -1;
1549 }
Victor Stinner78601a32016-09-09 19:28:36 -07001550
1551 // Split table doesn't allow deletion. Combine it.
1552 if (_PyDict_HasSplitTable(mp)) {
1553 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1554 return -1;
1555 }
INADA Naoki778928b2017-08-03 23:45:15 +09001556 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner78601a32016-09-09 19:28:36 -07001557 assert(ix >= 0);
1558 }
1559
INADA Naoki778928b2017-08-03 23:45:15 +09001560 return delitem_common(mp, hash, ix, old_value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001561}
1562
Antoine Pitroud741ed42016-12-27 14:23:43 +01001563/* This function promises that the predicate -> deletion sequence is atomic
1564 * (i.e. protected by the GIL), assuming the predicate itself doesn't
1565 * release the GIL.
1566 */
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001567int
1568_PyDict_DelItemIf(PyObject *op, PyObject *key,
1569 int (*predicate)(PyObject *value))
1570{
Antoine Pitroud741ed42016-12-27 14:23:43 +01001571 Py_ssize_t hashpos, ix;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001572 PyDictObject *mp;
1573 Py_hash_t hash;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001574 PyObject *old_value;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001575 int res;
1576
1577 if (!PyDict_Check(op)) {
1578 PyErr_BadInternalCall();
1579 return -1;
1580 }
1581 assert(key);
1582 hash = PyObject_Hash(key);
1583 if (hash == -1)
1584 return -1;
1585 mp = (PyDictObject *)op;
INADA Naoki778928b2017-08-03 23:45:15 +09001586 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001587 if (ix == DKIX_ERROR)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001588 return -1;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001589 if (ix == DKIX_EMPTY || old_value == NULL) {
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001590 _PyErr_SetKeyError(key);
1591 return -1;
1592 }
Antoine Pitroud741ed42016-12-27 14:23:43 +01001593
1594 // Split table doesn't allow deletion. Combine it.
1595 if (_PyDict_HasSplitTable(mp)) {
1596 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1597 return -1;
1598 }
INADA Naoki778928b2017-08-03 23:45:15 +09001599 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001600 assert(ix >= 0);
1601 }
1602
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001603 res = predicate(old_value);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001604 if (res == -1)
1605 return -1;
INADA Naoki778928b2017-08-03 23:45:15 +09001606
1607 hashpos = lookdict_index(mp->ma_keys, hash, ix);
1608 assert(hashpos >= 0);
1609
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001610 if (res > 0)
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001611 return delitem_common(mp, hashpos, ix, old_value);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001612 else
1613 return 0;
1614}
1615
1616
Guido van Rossum25831651993-05-19 14:50:45 +00001617void
Tim Peters1f5871e2000-07-04 17:44:48 +00001618PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 PyDictObject *mp;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001621 PyDictKeysObject *oldkeys;
1622 PyObject **oldvalues;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +00001624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 if (!PyDict_Check(op))
1626 return;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001627 mp = ((PyDictObject *)op);
1628 oldkeys = mp->ma_keys;
1629 oldvalues = mp->ma_values;
1630 if (oldvalues == empty_values)
1631 return;
1632 /* Empty the dict... */
1633 DK_INCREF(Py_EMPTY_KEYS);
1634 mp->ma_keys = Py_EMPTY_KEYS;
1635 mp->ma_values = empty_values;
1636 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001637 mp->ma_version_tag = DICT_NEXT_VERSION();
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001638 /* ...then clear the keys and values */
1639 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001640 n = oldkeys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001641 for (i = 0; i < n; i++)
1642 Py_CLEAR(oldvalues[i]);
1643 free_values(oldvalues);
1644 DK_DECREF(oldkeys);
1645 }
1646 else {
1647 assert(oldkeys->dk_refcnt == 1);
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001648 DK_DECREF(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001649 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02001650 assert(_PyDict_CheckConsistency(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001651}
1652
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001653/* Internal version of PyDict_Next that returns a hash value in addition
1654 * to the key and value.
1655 * Return 1 on success, return 0 when the reached the end of the dictionary
1656 * (or if op is not a dictionary)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001657 */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001658int
1659_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
1660 PyObject **pvalue, Py_hash_t *phash)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001661{
INADA Naokica2d8be2016-11-04 16:59:10 +09001662 Py_ssize_t i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001663 PyDictObject *mp;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001664 PyDictKeyEntry *entry_ptr;
1665 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001666
1667 if (!PyDict_Check(op))
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001668 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 mp = (PyDictObject *)op;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001670 i = *ppos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001671 if (mp->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09001672 if (i < 0 || i >= mp->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001673 return 0;
INADA Naokica2d8be2016-11-04 16:59:10 +09001674 /* values of split table is always dense */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001675 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
INADA Naokica2d8be2016-11-04 16:59:10 +09001676 value = mp->ma_values[i];
1677 assert(value != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001679 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09001680 Py_ssize_t n = mp->ma_keys->dk_nentries;
1681 if (i < 0 || i >= n)
1682 return 0;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001683 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
1684 while (i < n && entry_ptr->me_value == NULL) {
1685 entry_ptr++;
1686 i++;
Victor Stinner742da042016-09-07 17:40:12 -07001687 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001688 if (i >= n)
1689 return 0;
1690 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001692 *ppos = i+1;
1693 if (pkey)
1694 *pkey = entry_ptr->me_key;
1695 if (phash)
1696 *phash = entry_ptr->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001697 if (pvalue)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001698 *pvalue = value;
1699 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001700}
1701
Tim Peters080c88b2003-02-15 03:01:11 +00001702/*
1703 * Iterate over a dict. Use like so:
1704 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001705 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +00001706 * PyObject *key, *value;
1707 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +00001708 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001709 * Refer to borrowed references in key and value.
Tim Peters080c88b2003-02-15 03:01:11 +00001710 * }
1711 *
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001712 * Return 1 on success, return 0 when the reached the end of the dictionary
1713 * (or if op is not a dictionary)
1714 *
Tim Peters080c88b2003-02-15 03:01:11 +00001715 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +00001716 * mutates the dict. One exception: it is safe if the loop merely changes
1717 * the values associated with the keys (but doesn't insert new keys or
1718 * delete keys), via PyDict_SetItem().
1719 */
Guido van Rossum25831651993-05-19 14:50:45 +00001720int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001721PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001722{
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001723 return _PyDict_Next(op, ppos, pkey, pvalue, NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00001724}
1725
Eric Snow96c6af92015-05-29 22:21:39 -06001726/* Internal version of dict.pop(). */
1727PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001728_PyDict_Pop_KnownHash(PyObject *dict, PyObject *key, Py_hash_t hash, PyObject *deflt)
Eric Snow96c6af92015-05-29 22:21:39 -06001729{
Victor Stinner742da042016-09-07 17:40:12 -07001730 Py_ssize_t ix, hashpos;
Eric Snow96c6af92015-05-29 22:21:39 -06001731 PyObject *old_value, *old_key;
1732 PyDictKeyEntry *ep;
Yury Selivanov684ef2c2016-10-28 19:01:21 -04001733 PyDictObject *mp;
1734
1735 assert(PyDict_Check(dict));
1736 mp = (PyDictObject *)dict;
Eric Snow96c6af92015-05-29 22:21:39 -06001737
1738 if (mp->ma_used == 0) {
1739 if (deflt) {
1740 Py_INCREF(deflt);
1741 return deflt;
1742 }
1743 _PyErr_SetKeyError(key);
1744 return NULL;
1745 }
INADA Naoki778928b2017-08-03 23:45:15 +09001746 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner742da042016-09-07 17:40:12 -07001747 if (ix == DKIX_ERROR)
Eric Snow96c6af92015-05-29 22:21:39 -06001748 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001749 if (ix == DKIX_EMPTY || old_value == NULL) {
Eric Snow96c6af92015-05-29 22:21:39 -06001750 if (deflt) {
1751 Py_INCREF(deflt);
1752 return deflt;
1753 }
1754 _PyErr_SetKeyError(key);
1755 return NULL;
1756 }
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001757
Victor Stinner78601a32016-09-09 19:28:36 -07001758 // Split table doesn't allow deletion. Combine it.
1759 if (_PyDict_HasSplitTable(mp)) {
1760 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1761 return NULL;
1762 }
INADA Naoki778928b2017-08-03 23:45:15 +09001763 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner78601a32016-09-09 19:28:36 -07001764 assert(ix >= 0);
1765 }
1766
INADA Naoki778928b2017-08-03 23:45:15 +09001767 hashpos = lookdict_index(mp->ma_keys, hash, ix);
1768 assert(hashpos >= 0);
Victor Stinner78601a32016-09-09 19:28:36 -07001769 assert(old_value != NULL);
Eric Snow96c6af92015-05-29 22:21:39 -06001770 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001771 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner78601a32016-09-09 19:28:36 -07001772 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1773 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1774 ENSURE_ALLOWS_DELETIONS(mp);
1775 old_key = ep->me_key;
1776 ep->me_key = NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001777 ep->me_value = NULL;
Victor Stinner78601a32016-09-09 19:28:36 -07001778 Py_DECREF(old_key);
Victor Stinner611b0fa2016-09-14 15:02:01 +02001779
1780 assert(_PyDict_CheckConsistency(mp));
Eric Snow96c6af92015-05-29 22:21:39 -06001781 return old_value;
1782}
1783
Serhiy Storchaka67796522017-01-12 18:34:33 +02001784PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001785_PyDict_Pop(PyObject *dict, PyObject *key, PyObject *deflt)
Serhiy Storchaka67796522017-01-12 18:34:33 +02001786{
1787 Py_hash_t hash;
1788
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001789 if (((PyDictObject *)dict)->ma_used == 0) {
Serhiy Storchaka67796522017-01-12 18:34:33 +02001790 if (deflt) {
1791 Py_INCREF(deflt);
1792 return deflt;
1793 }
1794 _PyErr_SetKeyError(key);
1795 return NULL;
1796 }
1797 if (!PyUnicode_CheckExact(key) ||
1798 (hash = ((PyASCIIObject *) key)->hash) == -1) {
1799 hash = PyObject_Hash(key);
1800 if (hash == -1)
1801 return NULL;
1802 }
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001803 return _PyDict_Pop_KnownHash(dict, key, hash, deflt);
Serhiy Storchaka67796522017-01-12 18:34:33 +02001804}
1805
Eric Snow96c6af92015-05-29 22:21:39 -06001806/* Internal version of dict.from_keys(). It is subclass-friendly. */
1807PyObject *
1808_PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
1809{
1810 PyObject *it; /* iter(iterable) */
1811 PyObject *key;
1812 PyObject *d;
1813 int status;
1814
Victor Stinnera5ed5f02016-12-06 18:45:50 +01001815 d = _PyObject_CallNoArg(cls);
Eric Snow96c6af92015-05-29 22:21:39 -06001816 if (d == NULL)
1817 return NULL;
1818
1819 if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
1820 if (PyDict_CheckExact(iterable)) {
1821 PyDictObject *mp = (PyDictObject *)d;
1822 PyObject *oldvalue;
1823 Py_ssize_t pos = 0;
1824 PyObject *key;
1825 Py_hash_t hash;
1826
Serhiy Storchakac61ac162017-03-21 08:52:38 +02001827 if (dictresize(mp, ESTIMATE_SIZE(PyDict_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001828 Py_DECREF(d);
1829 return NULL;
1830 }
1831
1832 while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
1833 if (insertdict(mp, key, hash, value)) {
1834 Py_DECREF(d);
1835 return NULL;
1836 }
1837 }
1838 return d;
1839 }
1840 if (PyAnySet_CheckExact(iterable)) {
1841 PyDictObject *mp = (PyDictObject *)d;
1842 Py_ssize_t pos = 0;
1843 PyObject *key;
1844 Py_hash_t hash;
1845
Victor Stinner742da042016-09-07 17:40:12 -07001846 if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001847 Py_DECREF(d);
1848 return NULL;
1849 }
1850
1851 while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
1852 if (insertdict(mp, key, hash, value)) {
1853 Py_DECREF(d);
1854 return NULL;
1855 }
1856 }
1857 return d;
1858 }
1859 }
1860
1861 it = PyObject_GetIter(iterable);
1862 if (it == NULL){
1863 Py_DECREF(d);
1864 return NULL;
1865 }
1866
1867 if (PyDict_CheckExact(d)) {
1868 while ((key = PyIter_Next(it)) != NULL) {
1869 status = PyDict_SetItem(d, key, value);
1870 Py_DECREF(key);
1871 if (status < 0)
1872 goto Fail;
1873 }
1874 } else {
1875 while ((key = PyIter_Next(it)) != NULL) {
1876 status = PyObject_SetItem(d, key, value);
1877 Py_DECREF(key);
1878 if (status < 0)
1879 goto Fail;
1880 }
1881 }
1882
1883 if (PyErr_Occurred())
1884 goto Fail;
1885 Py_DECREF(it);
1886 return d;
1887
1888Fail:
1889 Py_DECREF(it);
1890 Py_DECREF(d);
1891 return NULL;
1892}
1893
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001894/* Methods */
1895
1896static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001897dict_dealloc(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001898{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001899 PyObject **values = mp->ma_values;
1900 PyDictKeysObject *keys = mp->ma_keys;
1901 Py_ssize_t i, n;
INADA Naokia6296d32017-08-24 14:55:17 +09001902
1903 /* bpo-31095: UnTrack is needed before calling any callbacks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 PyObject_GC_UnTrack(mp);
1905 Py_TRASHCAN_SAFE_BEGIN(mp)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001906 if (values != NULL) {
1907 if (values != empty_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001908 for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001909 Py_XDECREF(values[i]);
1910 }
1911 free_values(values);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001913 DK_DECREF(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 }
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02001915 else if (keys != NULL) {
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001916 assert(keys->dk_refcnt == 1);
1917 DK_DECREF(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001918 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
1920 free_list[numfree++] = mp;
1921 else
1922 Py_TYPE(mp)->tp_free((PyObject *)mp);
1923 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001924}
1925
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001926
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001927static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001928dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 Py_ssize_t i;
Victor Stinnerf91929b2013-11-19 13:07:38 +01001931 PyObject *key = NULL, *value = NULL;
1932 _PyUnicodeWriter writer;
1933 int first;
Guido van Rossum255443b1998-04-10 22:47:14 +00001934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 i = Py_ReprEnter((PyObject *)mp);
1936 if (i != 0) {
1937 return i > 0 ? PyUnicode_FromString("{...}") : NULL;
1938 }
Guido van Rossum255443b1998-04-10 22:47:14 +00001939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 if (mp->ma_used == 0) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01001941 Py_ReprLeave((PyObject *)mp);
1942 return PyUnicode_FromString("{}");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 }
Tim Petersa7259592001-06-16 05:11:17 +00001944
Victor Stinnerf91929b2013-11-19 13:07:38 +01001945 _PyUnicodeWriter_Init(&writer);
1946 writer.overallocate = 1;
1947 /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
1948 writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +00001949
Victor Stinnerf91929b2013-11-19 13:07:38 +01001950 if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
1951 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 /* Do repr() on each key+value pair, and insert ": " between them.
1954 Note that repr may mutate the dict. */
1955 i = 0;
Victor Stinnerf91929b2013-11-19 13:07:38 +01001956 first = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01001958 PyObject *s;
1959 int res;
1960
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001961 /* Prevent repr from deleting key or value during key format. */
1962 Py_INCREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 Py_INCREF(value);
Victor Stinnerf97dfd72013-07-18 01:00:45 +02001964
Victor Stinnerf91929b2013-11-19 13:07:38 +01001965 if (!first) {
1966 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
1967 goto error;
1968 }
1969 first = 0;
1970
1971 s = PyObject_Repr(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 if (s == NULL)
Victor Stinnerf91929b2013-11-19 13:07:38 +01001973 goto error;
1974 res = _PyUnicodeWriter_WriteStr(&writer, s);
1975 Py_DECREF(s);
1976 if (res < 0)
1977 goto error;
1978
1979 if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
1980 goto error;
1981
1982 s = PyObject_Repr(value);
1983 if (s == NULL)
1984 goto error;
1985 res = _PyUnicodeWriter_WriteStr(&writer, s);
1986 Py_DECREF(s);
1987 if (res < 0)
1988 goto error;
1989
1990 Py_CLEAR(key);
1991 Py_CLEAR(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 }
Tim Petersa7259592001-06-16 05:11:17 +00001993
Victor Stinnerf91929b2013-11-19 13:07:38 +01001994 writer.overallocate = 0;
1995 if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
1996 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 Py_ReprLeave((PyObject *)mp);
Victor Stinnerf91929b2013-11-19 13:07:38 +01001999
2000 return _PyUnicodeWriter_Finish(&writer);
2001
2002error:
2003 Py_ReprLeave((PyObject *)mp);
2004 _PyUnicodeWriter_Dealloc(&writer);
2005 Py_XDECREF(key);
2006 Py_XDECREF(value);
2007 return NULL;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002008}
2009
Martin v. Löwis18e16552006-02-15 17:27:45 +00002010static Py_ssize_t
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002011dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 return mp->ma_used;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002014}
2015
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002016static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002017dict_subscript(PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002018{
Victor Stinner742da042016-09-07 17:40:12 -07002019 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002020 Py_hash_t hash;
INADA Naokiba609772016-12-07 20:41:42 +09002021 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002024 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 hash = PyObject_Hash(key);
2026 if (hash == -1)
2027 return NULL;
2028 }
INADA Naoki778928b2017-08-03 23:45:15 +09002029 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002030 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002032 if (ix == DKIX_EMPTY || value == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 if (!PyDict_CheckExact(mp)) {
2034 /* Look up __missing__ method if we're a subclass. */
2035 PyObject *missing, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05002036 _Py_IDENTIFIER(__missing__);
2037 missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 if (missing != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002039 res = PyObject_CallFunctionObjArgs(missing,
2040 key, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 Py_DECREF(missing);
2042 return res;
2043 }
2044 else if (PyErr_Occurred())
2045 return NULL;
2046 }
Raymond Hettinger69492da2013-09-02 15:59:26 -07002047 _PyErr_SetKeyError(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 return NULL;
2049 }
INADA Naokiba609772016-12-07 20:41:42 +09002050 Py_INCREF(value);
2051 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002052}
2053
2054static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002055dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 if (w == NULL)
2058 return PyDict_DelItem((PyObject *)mp, v);
2059 else
2060 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002061}
2062
Guido van Rossuma9e7a811997-05-13 21:02:11 +00002063static PyMappingMethods dict_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 (lenfunc)dict_length, /*mp_length*/
2065 (binaryfunc)dict_subscript, /*mp_subscript*/
2066 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002067};
2068
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002069static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002070dict_keys(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002071{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002072 PyObject *v;
2073 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002074 PyDictKeyEntry *ep;
2075 Py_ssize_t size, n, offset;
2076 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002077
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002078 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 n = mp->ma_used;
2080 v = PyList_New(n);
2081 if (v == NULL)
2082 return NULL;
2083 if (n != mp->ma_used) {
2084 /* Durnit. The allocations caused the dict to resize.
2085 * Just start over, this shouldn't normally happen.
2086 */
2087 Py_DECREF(v);
2088 goto again;
2089 }
Victor Stinner742da042016-09-07 17:40:12 -07002090 ep = DK_ENTRIES(mp->ma_keys);
2091 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002092 if (mp->ma_values) {
2093 value_ptr = mp->ma_values;
2094 offset = sizeof(PyObject *);
2095 }
2096 else {
2097 value_ptr = &ep[0].me_value;
2098 offset = sizeof(PyDictKeyEntry);
2099 }
2100 for (i = 0, j = 0; i < size; i++) {
2101 if (*value_ptr != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 PyObject *key = ep[i].me_key;
2103 Py_INCREF(key);
2104 PyList_SET_ITEM(v, j, key);
2105 j++;
2106 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002107 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 }
2109 assert(j == n);
2110 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002111}
2112
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002113static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002114dict_values(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002115{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002116 PyObject *v;
2117 Py_ssize_t i, j;
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002118 PyDictKeyEntry *ep;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002119 Py_ssize_t size, n, offset;
2120 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002121
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002122 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 n = mp->ma_used;
2124 v = PyList_New(n);
2125 if (v == NULL)
2126 return NULL;
2127 if (n != mp->ma_used) {
2128 /* Durnit. The allocations caused the dict to resize.
2129 * Just start over, this shouldn't normally happen.
2130 */
2131 Py_DECREF(v);
2132 goto again;
2133 }
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002134 ep = DK_ENTRIES(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002135 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002136 if (mp->ma_values) {
2137 value_ptr = mp->ma_values;
2138 offset = sizeof(PyObject *);
2139 }
2140 else {
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002141 value_ptr = &ep[0].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002142 offset = sizeof(PyDictKeyEntry);
2143 }
2144 for (i = 0, j = 0; i < size; i++) {
2145 PyObject *value = *value_ptr;
2146 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2147 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 Py_INCREF(value);
2149 PyList_SET_ITEM(v, j, value);
2150 j++;
2151 }
2152 }
2153 assert(j == n);
2154 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002155}
2156
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002157static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002158dict_items(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002159{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002160 PyObject *v;
2161 Py_ssize_t i, j, n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002162 Py_ssize_t size, offset;
2163 PyObject *item, *key;
2164 PyDictKeyEntry *ep;
2165 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 /* Preallocate the list of tuples, to avoid allocations during
2168 * the loop over the items, which could trigger GC, which
2169 * could resize the dict. :-(
2170 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002171 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 n = mp->ma_used;
2173 v = PyList_New(n);
2174 if (v == NULL)
2175 return NULL;
2176 for (i = 0; i < n; i++) {
2177 item = PyTuple_New(2);
2178 if (item == NULL) {
2179 Py_DECREF(v);
2180 return NULL;
2181 }
2182 PyList_SET_ITEM(v, i, item);
2183 }
2184 if (n != mp->ma_used) {
2185 /* Durnit. The allocations caused the dict to resize.
2186 * Just start over, this shouldn't normally happen.
2187 */
2188 Py_DECREF(v);
2189 goto again;
2190 }
2191 /* Nothing we do below makes any function calls. */
Victor Stinner742da042016-09-07 17:40:12 -07002192 ep = DK_ENTRIES(mp->ma_keys);
2193 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002194 if (mp->ma_values) {
2195 value_ptr = mp->ma_values;
2196 offset = sizeof(PyObject *);
2197 }
2198 else {
2199 value_ptr = &ep[0].me_value;
2200 offset = sizeof(PyDictKeyEntry);
2201 }
2202 for (i = 0, j = 0; i < size; i++) {
2203 PyObject *value = *value_ptr;
2204 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2205 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 key = ep[i].me_key;
2207 item = PyList_GET_ITEM(v, j);
2208 Py_INCREF(key);
2209 PyTuple_SET_ITEM(item, 0, key);
2210 Py_INCREF(value);
2211 PyTuple_SET_ITEM(item, 1, value);
2212 j++;
2213 }
2214 }
2215 assert(j == n);
2216 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002217}
2218
Larry Hastings5c661892014-01-24 06:17:25 -08002219/*[clinic input]
2220@classmethod
2221dict.fromkeys
Larry Hastings5c661892014-01-24 06:17:25 -08002222 iterable: object
2223 value: object=None
2224 /
2225
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002226Create a new dictionary with keys from iterable and values set to value.
Larry Hastings5c661892014-01-24 06:17:25 -08002227[clinic start generated code]*/
2228
Larry Hastings5c661892014-01-24 06:17:25 -08002229static PyObject *
2230dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002231/*[clinic end generated code: output=8fb98e4b10384999 input=382ba4855d0f74c3]*/
Larry Hastings5c661892014-01-24 06:17:25 -08002232{
Eric Snow96c6af92015-05-29 22:21:39 -06002233 return _PyDict_FromKeys((PyObject *)type, iterable, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002234}
2235
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002236static int
Victor Stinner742da042016-09-07 17:40:12 -07002237dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
2238 const char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 PyObject *arg = NULL;
2241 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002242
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002243 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 result = -1;
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002245 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 else if (arg != NULL) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02002247 _Py_IDENTIFIER(keys);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002248 PyObject *func;
2249 if (_PyObject_LookupAttrId(arg, &PyId_keys, &func) < 0) {
2250 result = -1;
2251 }
2252 else if (func != NULL) {
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002253 Py_DECREF(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 result = PyDict_Merge(self, arg, 1);
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002255 }
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002256 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002257 result = PyDict_MergeFromSeq2(self, arg, 1);
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002258 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 }
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 if (result == 0 && kwds != NULL) {
2262 if (PyArg_ValidateKeywordArguments(kwds))
2263 result = PyDict_Merge(self, kwds, 1);
2264 else
2265 result = -1;
2266 }
2267 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002268}
2269
Victor Stinner91f0d4a2017-01-19 12:45:06 +01002270/* Note: dict.update() uses the METH_VARARGS|METH_KEYWORDS calling convention.
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002271 Using METH_FASTCALL|METH_KEYWORDS would make dict.update(**dict2) calls
2272 slower, see the issue #29312. */
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002273static PyObject *
2274dict_update(PyObject *self, PyObject *args, PyObject *kwds)
2275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 if (dict_update_common(self, args, kwds, "update") != -1)
2277 Py_RETURN_NONE;
2278 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002279}
2280
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002281/* Update unconditionally replaces existing items.
2282 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00002283 otherwise it leaves existing items unchanged.
2284
2285 PyDict_{Update,Merge} update/merge from a mapping object.
2286
Tim Petersf582b822001-12-11 18:51:08 +00002287 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00002288 producing iterable objects of length 2.
2289*/
2290
Tim Petersf582b822001-12-11 18:51:08 +00002291int
Tim Peters1fc240e2001-10-26 05:06:50 +00002292PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
2293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 PyObject *it; /* iter(seq2) */
2295 Py_ssize_t i; /* index into seq2 of current element */
2296 PyObject *item; /* seq2[i] */
2297 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 assert(d != NULL);
2300 assert(PyDict_Check(d));
2301 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 it = PyObject_GetIter(seq2);
2304 if (it == NULL)
2305 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 for (i = 0; ; ++i) {
2308 PyObject *key, *value;
2309 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 fast = NULL;
2312 item = PyIter_Next(it);
2313 if (item == NULL) {
2314 if (PyErr_Occurred())
2315 goto Fail;
2316 break;
2317 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 /* Convert item to sequence, and verify length 2. */
2320 fast = PySequence_Fast(item, "");
2321 if (fast == NULL) {
2322 if (PyErr_ExceptionMatches(PyExc_TypeError))
2323 PyErr_Format(PyExc_TypeError,
2324 "cannot convert dictionary update "
2325 "sequence element #%zd to a sequence",
2326 i);
2327 goto Fail;
2328 }
2329 n = PySequence_Fast_GET_SIZE(fast);
2330 if (n != 2) {
2331 PyErr_Format(PyExc_ValueError,
2332 "dictionary update sequence element #%zd "
2333 "has length %zd; 2 is required",
2334 i, n);
2335 goto Fail;
2336 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 /* Update/merge with this (key, value) pair. */
2339 key = PySequence_Fast_GET_ITEM(fast, 0);
2340 value = PySequence_Fast_GET_ITEM(fast, 1);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002341 Py_INCREF(key);
2342 Py_INCREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 if (override || PyDict_GetItem(d, key) == NULL) {
2344 int status = PyDict_SetItem(d, key, value);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002345 if (status < 0) {
2346 Py_DECREF(key);
2347 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 goto Fail;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002349 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 }
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002351 Py_DECREF(key);
2352 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 Py_DECREF(fast);
2354 Py_DECREF(item);
2355 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 i = 0;
Victor Stinner611b0fa2016-09-14 15:02:01 +02002358 assert(_PyDict_CheckConsistency((PyDictObject *)d));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00002360Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 Py_XDECREF(item);
2362 Py_XDECREF(fast);
2363 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002364Return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 Py_DECREF(it);
2366 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00002367}
2368
doko@ubuntu.comc96df682016-10-11 08:04:02 +02002369static int
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002370dict_merge(PyObject *a, PyObject *b, int override)
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002371{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002372 PyDictObject *mp, *other;
2373 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -07002374 PyDictKeyEntry *entry, *ep0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002375
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002376 assert(0 <= override && override <= 2);
2377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 /* We accept for the argument either a concrete dictionary object,
2379 * or an abstract "mapping" object. For the former, we can do
2380 * things quite efficiently. For the latter, we only require that
2381 * PyMapping_Keys() and PyObject_GetItem() be supported.
2382 */
2383 if (a == NULL || !PyDict_Check(a) || b == NULL) {
2384 PyErr_BadInternalCall();
2385 return -1;
2386 }
2387 mp = (PyDictObject*)a;
INADA Naoki2aaf98c2018-09-26 12:59:00 +09002388 if (PyDict_Check(b) && (Py_TYPE(b)->tp_iter == (getiterfunc)dict_iter)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 other = (PyDictObject*)b;
2390 if (other == mp || other->ma_used == 0)
2391 /* a.update(a) or a.update({}); nothing to do */
2392 return 0;
2393 if (mp->ma_used == 0)
2394 /* Since the target dict is empty, PyDict_GetItem()
2395 * always returns NULL. Setting override to 1
2396 * skips the unnecessary test.
2397 */
2398 override = 1;
2399 /* Do one big resize at the start, rather than
2400 * incrementally resizing as we insert new items. Expect
2401 * that there will be no (or few) overlapping keys.
2402 */
INADA Naokib1152be2016-10-27 19:26:50 +09002403 if (USABLE_FRACTION(mp->ma_keys->dk_size) < other->ma_used) {
2404 if (dictresize(mp, ESTIMATE_SIZE(mp->ma_used + other->ma_used))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 return -1;
INADA Naokib1152be2016-10-27 19:26:50 +09002406 }
2407 }
Victor Stinner742da042016-09-07 17:40:12 -07002408 ep0 = DK_ENTRIES(other->ma_keys);
2409 for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002410 PyObject *key, *value;
2411 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002412 entry = &ep0[i];
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002413 key = entry->me_key;
2414 hash = entry->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002415 if (other->ma_values)
2416 value = other->ma_values[i];
2417 else
2418 value = entry->me_value;
2419
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002420 if (value != NULL) {
2421 int err = 0;
2422 Py_INCREF(key);
2423 Py_INCREF(value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002424 if (override == 1)
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002425 err = insertdict(mp, key, hash, value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002426 else if (_PyDict_GetItem_KnownHash(a, key, hash) == NULL) {
2427 if (PyErr_Occurred()) {
2428 Py_DECREF(value);
2429 Py_DECREF(key);
2430 return -1;
2431 }
2432 err = insertdict(mp, key, hash, value);
2433 }
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002434 else if (override != 0) {
2435 _PyErr_SetKeyError(key);
2436 Py_DECREF(value);
2437 Py_DECREF(key);
2438 return -1;
2439 }
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002440 Py_DECREF(value);
2441 Py_DECREF(key);
2442 if (err != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 return -1;
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002444
Victor Stinner742da042016-09-07 17:40:12 -07002445 if (n != other->ma_keys->dk_nentries) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002446 PyErr_SetString(PyExc_RuntimeError,
2447 "dict mutated during update");
2448 return -1;
2449 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 }
2451 }
2452 }
2453 else {
2454 /* Do it the generic, slower way */
2455 PyObject *keys = PyMapping_Keys(b);
2456 PyObject *iter;
2457 PyObject *key, *value;
2458 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 if (keys == NULL)
2461 /* Docstring says this is equivalent to E.keys() so
2462 * if E doesn't have a .keys() method we want
2463 * AttributeError to percolate up. Might as well
2464 * do the same for any other error.
2465 */
2466 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 iter = PyObject_GetIter(keys);
2469 Py_DECREF(keys);
2470 if (iter == NULL)
2471 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002474 if (override != 1 && PyDict_GetItem(a, key) != NULL) {
2475 if (override != 0) {
2476 _PyErr_SetKeyError(key);
2477 Py_DECREF(key);
2478 Py_DECREF(iter);
2479 return -1;
2480 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 Py_DECREF(key);
2482 continue;
2483 }
2484 value = PyObject_GetItem(b, key);
2485 if (value == NULL) {
2486 Py_DECREF(iter);
2487 Py_DECREF(key);
2488 return -1;
2489 }
2490 status = PyDict_SetItem(a, key, value);
2491 Py_DECREF(key);
2492 Py_DECREF(value);
2493 if (status < 0) {
2494 Py_DECREF(iter);
2495 return -1;
2496 }
2497 }
2498 Py_DECREF(iter);
2499 if (PyErr_Occurred())
2500 /* Iterator completed, via error */
2501 return -1;
2502 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02002503 assert(_PyDict_CheckConsistency((PyDictObject *)a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002505}
2506
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002507int
2508PyDict_Update(PyObject *a, PyObject *b)
2509{
2510 return dict_merge(a, b, 1);
2511}
2512
2513int
2514PyDict_Merge(PyObject *a, PyObject *b, int override)
2515{
2516 /* XXX Deprecate override not in (0, 1). */
2517 return dict_merge(a, b, override != 0);
2518}
2519
2520int
2521_PyDict_MergeEx(PyObject *a, PyObject *b, int override)
2522{
2523 return dict_merge(a, b, override);
2524}
2525
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002526static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302527dict_copy(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002530}
2531
2532PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002533PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 PyObject *copy;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002536 PyDictObject *mp;
2537 Py_ssize_t i, n;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 if (o == NULL || !PyDict_Check(o)) {
2540 PyErr_BadInternalCall();
2541 return NULL;
2542 }
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002543
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002544 mp = (PyDictObject *)o;
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002545 if (mp->ma_used == 0) {
2546 /* The dict is empty; just return a new dict. */
2547 return PyDict_New();
2548 }
2549
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002550 if (_PyDict_HasSplitTable(mp)) {
2551 PyDictObject *split_copy;
Victor Stinner742da042016-09-07 17:40:12 -07002552 Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
2553 PyObject **newvalues;
2554 newvalues = new_values(size);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002555 if (newvalues == NULL)
2556 return PyErr_NoMemory();
2557 split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
2558 if (split_copy == NULL) {
2559 free_values(newvalues);
2560 return NULL;
2561 }
2562 split_copy->ma_values = newvalues;
2563 split_copy->ma_keys = mp->ma_keys;
2564 split_copy->ma_used = mp->ma_used;
INADA Naokid1c82c52018-04-03 11:43:53 +09002565 split_copy->ma_version_tag = DICT_NEXT_VERSION();
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002566 DK_INCREF(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002567 for (i = 0, n = size; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002568 PyObject *value = mp->ma_values[i];
2569 Py_XINCREF(value);
2570 split_copy->ma_values[i] = value;
2571 }
Benjamin Peterson7ce67e42012-04-24 10:32:57 -04002572 if (_PyObject_GC_IS_TRACKED(mp))
2573 _PyObject_GC_TRACK(split_copy);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002574 return (PyObject *)split_copy;
2575 }
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002576
2577 if (PyDict_CheckExact(mp) && mp->ma_values == NULL &&
2578 (mp->ma_used >= (mp->ma_keys->dk_nentries * 2) / 3))
2579 {
2580 /* Use fast-copy if:
2581
2582 (1) 'mp' is an instance of a subclassed dict; and
2583
2584 (2) 'mp' is not a split-dict; and
2585
2586 (3) if 'mp' is non-compact ('del' operation does not resize dicts),
2587 do fast-copy only if it has at most 1/3 non-used keys.
2588
Ville Skyttä61f82e02018-04-20 23:08:45 +03002589 The last condition (3) is important to guard against a pathological
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002590 case when a large dict is almost emptied with multiple del/pop
2591 operations and copied after that. In cases like this, we defer to
2592 PyDict_Merge, which produces a compacted copy.
2593 */
2594 return clone_combined_dict(mp);
2595 }
2596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 copy = PyDict_New();
2598 if (copy == NULL)
2599 return NULL;
2600 if (PyDict_Merge(copy, o, 1) == 0)
2601 return copy;
2602 Py_DECREF(copy);
2603 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002604}
2605
Martin v. Löwis18e16552006-02-15 17:27:45 +00002606Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00002607PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00002608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 if (mp == NULL || !PyDict_Check(mp)) {
2610 PyErr_BadInternalCall();
2611 return -1;
2612 }
2613 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00002614}
2615
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002616PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002617PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 if (mp == NULL || !PyDict_Check(mp)) {
2620 PyErr_BadInternalCall();
2621 return NULL;
2622 }
2623 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002624}
2625
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002626PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002627PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 if (mp == NULL || !PyDict_Check(mp)) {
2630 PyErr_BadInternalCall();
2631 return NULL;
2632 }
2633 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002634}
2635
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002636PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002637PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 if (mp == NULL || !PyDict_Check(mp)) {
2640 PyErr_BadInternalCall();
2641 return NULL;
2642 }
2643 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002644}
2645
Tim Peterse63415e2001-05-08 04:38:29 +00002646/* Return 1 if dicts equal, 0 if not, -1 if error.
2647 * Gets out as soon as any difference is detected.
2648 * Uses only Py_EQ comparison.
2649 */
2650static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002651dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00002652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00002654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 if (a->ma_used != b->ma_used)
2656 /* can't be equal if # of entries differ */
2657 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Victor Stinner742da042016-09-07 17:40:12 -07002659 for (i = 0; i < a->ma_keys->dk_nentries; i++) {
2660 PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002661 PyObject *aval;
2662 if (a->ma_values)
2663 aval = a->ma_values[i];
2664 else
2665 aval = ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 if (aval != NULL) {
2667 int cmp;
2668 PyObject *bval;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002669 PyObject *key = ep->me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 /* temporarily bump aval's refcount to ensure it stays
2671 alive until we're done with it */
2672 Py_INCREF(aval);
2673 /* ditto for key */
2674 Py_INCREF(key);
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002675 /* reuse the known hash value */
INADA Naoki778928b2017-08-03 23:45:15 +09002676 b->ma_keys->dk_lookup(b, key, ep->me_hash, &bval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 if (bval == NULL) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002678 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 Py_DECREF(aval);
2680 if (PyErr_Occurred())
2681 return -1;
2682 return 0;
2683 }
2684 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002685 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 Py_DECREF(aval);
2687 if (cmp <= 0) /* error or not equal */
2688 return cmp;
2689 }
2690 }
2691 return 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002692}
Tim Peterse63415e2001-05-08 04:38:29 +00002693
2694static PyObject *
2695dict_richcompare(PyObject *v, PyObject *w, int op)
2696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 int cmp;
2698 PyObject *res;
Tim Peterse63415e2001-05-08 04:38:29 +00002699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 if (!PyDict_Check(v) || !PyDict_Check(w)) {
2701 res = Py_NotImplemented;
2702 }
2703 else if (op == Py_EQ || op == Py_NE) {
2704 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
2705 if (cmp < 0)
2706 return NULL;
2707 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
2708 }
2709 else
2710 res = Py_NotImplemented;
2711 Py_INCREF(res);
2712 return res;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002713}
Tim Peterse63415e2001-05-08 04:38:29 +00002714
Larry Hastings61272b72014-01-07 12:41:53 -08002715/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002716
2717@coexist
2718dict.__contains__
2719
2720 key: object
2721 /
2722
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002723True if the dictionary has the specified key, else False.
Larry Hastings61272b72014-01-07 12:41:53 -08002724[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002725
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002726static PyObject *
Larry Hastingsc2047262014-01-25 20:43:29 -08002727dict___contains__(PyDictObject *self, PyObject *key)
Serhiy Storchaka19d25972017-02-04 08:05:07 +02002728/*[clinic end generated code: output=a3d03db709ed6e6b input=fe1cb42ad831e820]*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002729{
Larry Hastingsc2047262014-01-25 20:43:29 -08002730 register PyDictObject *mp = self;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002731 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002732 Py_ssize_t ix;
INADA Naokiba609772016-12-07 20:41:42 +09002733 PyObject *value;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002736 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 hash = PyObject_Hash(key);
2738 if (hash == -1)
2739 return NULL;
2740 }
INADA Naoki778928b2017-08-03 23:45:15 +09002741 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002742 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002744 if (ix == DKIX_EMPTY || value == NULL)
Victor Stinner742da042016-09-07 17:40:12 -07002745 Py_RETURN_FALSE;
2746 Py_RETURN_TRUE;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002747}
2748
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002749/*[clinic input]
2750dict.get
2751
2752 key: object
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002753 default: object = None
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002754 /
2755
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002756Return the value for key if key is in the dictionary, else default.
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002757[clinic start generated code]*/
2758
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002759static PyObject *
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002760dict_get_impl(PyDictObject *self, PyObject *key, PyObject *default_value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002761/*[clinic end generated code: output=bba707729dee05bf input=279ddb5790b6b107]*/
Barry Warsawc38c5da1997-10-06 17:49:20 +00002762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002764 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002765 Py_ssize_t ix;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002768 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 hash = PyObject_Hash(key);
2770 if (hash == -1)
2771 return NULL;
2772 }
INADA Naoki778928b2017-08-03 23:45:15 +09002773 ix = (self->ma_keys->dk_lookup) (self, key, hash, &val);
Victor Stinner742da042016-09-07 17:40:12 -07002774 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002776 if (ix == DKIX_EMPTY || val == NULL) {
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002777 val = default_value;
INADA Naokiba609772016-12-07 20:41:42 +09002778 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 Py_INCREF(val);
2780 return val;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002781}
2782
Benjamin Peterson00e98862013-03-07 22:16:29 -05002783PyObject *
2784PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
Guido van Rossum164452c2000-08-08 16:12:54 +00002785{
Benjamin Peterson00e98862013-03-07 22:16:29 -05002786 PyDictObject *mp = (PyDictObject *)d;
INADA Naoki93f26f72016-11-02 18:45:16 +09002787 PyObject *value;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002788 Py_hash_t hash;
Guido van Rossum164452c2000-08-08 16:12:54 +00002789
Benjamin Peterson00e98862013-03-07 22:16:29 -05002790 if (!PyDict_Check(d)) {
2791 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 return NULL;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002793 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002796 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 hash = PyObject_Hash(key);
2798 if (hash == -1)
2799 return NULL;
2800 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002801
2802 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
2803 if (insertion_resize(mp) < 0)
2804 return NULL;
2805 }
2806
INADA Naoki778928b2017-08-03 23:45:15 +09002807 Py_ssize_t ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002808 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 return NULL;
INADA Naoki93f26f72016-11-02 18:45:16 +09002810
2811 if (_PyDict_HasSplitTable(mp) &&
INADA Naokiba609772016-12-07 20:41:42 +09002812 ((ix >= 0 && value == NULL && mp->ma_used != ix) ||
INADA Naoki93f26f72016-11-02 18:45:16 +09002813 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
2814 if (insertion_resize(mp) < 0) {
2815 return NULL;
2816 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002817 ix = DKIX_EMPTY;
2818 }
2819
2820 if (ix == DKIX_EMPTY) {
2821 PyDictKeyEntry *ep, *ep0;
2822 value = defaultobj;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002823 if (mp->ma_keys->dk_usable <= 0) {
Victor Stinner3c336c52016-09-12 14:17:40 +02002824 if (insertion_resize(mp) < 0) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002825 return NULL;
Victor Stinner3c336c52016-09-12 14:17:40 +02002826 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002827 }
INADA Naoki778928b2017-08-03 23:45:15 +09002828 Py_ssize_t hashpos = find_empty_slot(mp->ma_keys, hash);
INADA Naoki93f26f72016-11-02 18:45:16 +09002829 ep0 = DK_ENTRIES(mp->ma_keys);
2830 ep = &ep0[mp->ma_keys->dk_nentries];
2831 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
Benjamin Petersonb1efa532013-03-04 09:47:50 -05002832 Py_INCREF(key);
INADA Naoki93f26f72016-11-02 18:45:16 +09002833 Py_INCREF(value);
2834 MAINTAIN_TRACKING(mp, key, value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002835 ep->me_key = key;
2836 ep->me_hash = hash;
INADA Naokiba609772016-12-07 20:41:42 +09002837 if (_PyDict_HasSplitTable(mp)) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002838 assert(mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
2839 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Victor Stinner742da042016-09-07 17:40:12 -07002840 }
2841 else {
INADA Naoki93f26f72016-11-02 18:45:16 +09002842 ep->me_value = value;
Victor Stinner742da042016-09-07 17:40:12 -07002843 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002844 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07002845 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naoki93f26f72016-11-02 18:45:16 +09002846 mp->ma_keys->dk_usable--;
2847 mp->ma_keys->dk_nentries++;
2848 assert(mp->ma_keys->dk_usable >= 0);
2849 }
INADA Naokiba609772016-12-07 20:41:42 +09002850 else if (value == NULL) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002851 value = defaultobj;
2852 assert(_PyDict_HasSplitTable(mp));
2853 assert(ix == mp->ma_used);
2854 Py_INCREF(value);
2855 MAINTAIN_TRACKING(mp, key, value);
INADA Naokiba609772016-12-07 20:41:42 +09002856 mp->ma_values[ix] = value;
INADA Naoki93f26f72016-11-02 18:45:16 +09002857 mp->ma_used++;
2858 mp->ma_version_tag = DICT_NEXT_VERSION();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002860
2861 assert(_PyDict_CheckConsistency(mp));
2862 return value;
Guido van Rossum164452c2000-08-08 16:12:54 +00002863}
2864
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002865/*[clinic input]
2866dict.setdefault
2867
2868 key: object
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002869 default: object = None
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002870 /
2871
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002872Insert key with a value of default if key is not in the dictionary.
2873
2874Return the value for key if key is in the dictionary, else default.
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002875[clinic start generated code]*/
2876
Benjamin Peterson00e98862013-03-07 22:16:29 -05002877static PyObject *
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002878dict_setdefault_impl(PyDictObject *self, PyObject *key,
2879 PyObject *default_value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002880/*[clinic end generated code: output=f8c1101ebf69e220 input=0f063756e815fd9d]*/
Benjamin Peterson00e98862013-03-07 22:16:29 -05002881{
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002882 PyObject *val;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002883
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002884 val = PyDict_SetDefault((PyObject *)self, key, default_value);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002885 Py_XINCREF(val);
2886 return val;
2887}
Guido van Rossum164452c2000-08-08 16:12:54 +00002888
2889static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302890dict_clear(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 PyDict_Clear((PyObject *)mp);
2893 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002894}
2895
Guido van Rossumba6ab842000-12-12 22:02:18 +00002896static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002897dict_pop(PyDictObject *mp, PyObject *args)
Guido van Rossume027d982002-04-12 15:11:59 +00002898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 PyObject *key, *deflt = NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00002900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
2902 return NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06002903
Yury Selivanov684ef2c2016-10-28 19:01:21 -04002904 return _PyDict_Pop((PyObject*)mp, key, deflt);
Guido van Rossume027d982002-04-12 15:11:59 +00002905}
2906
2907static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302908dict_popitem(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Guido van Rossumba6ab842000-12-12 22:02:18 +00002909{
Victor Stinner742da042016-09-07 17:40:12 -07002910 Py_ssize_t i, j;
2911 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 PyObject *res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 /* Allocate the result tuple before checking the size. Believe it
2915 * or not, this allocation could trigger a garbage collection which
2916 * could empty the dict, so if we checked the size first and that
2917 * happened, the result would be an infinite loop (searching for an
2918 * entry that no longer exists). Note that the usual popitem()
2919 * idiom is "while d: k, v = d.popitem()". so needing to throw the
2920 * tuple away if the dict *is* empty isn't a significant
2921 * inefficiency -- possible, but unlikely in practice.
2922 */
2923 res = PyTuple_New(2);
2924 if (res == NULL)
2925 return NULL;
2926 if (mp->ma_used == 0) {
2927 Py_DECREF(res);
2928 PyErr_SetString(PyExc_KeyError,
2929 "popitem(): dictionary is empty");
2930 return NULL;
2931 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002932 /* Convert split table to combined table */
2933 if (mp->ma_keys->dk_lookup == lookdict_split) {
2934 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
2935 Py_DECREF(res);
2936 return NULL;
2937 }
2938 }
2939 ENSURE_ALLOWS_DELETIONS(mp);
Victor Stinner742da042016-09-07 17:40:12 -07002940
2941 /* Pop last item */
2942 ep0 = DK_ENTRIES(mp->ma_keys);
2943 i = mp->ma_keys->dk_nentries - 1;
2944 while (i >= 0 && ep0[i].me_value == NULL) {
2945 i--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 }
Victor Stinner742da042016-09-07 17:40:12 -07002947 assert(i >= 0);
2948
2949 ep = &ep0[i];
2950 j = lookdict_index(mp->ma_keys, ep->me_hash, i);
2951 assert(j >= 0);
2952 assert(dk_get_index(mp->ma_keys, j) == i);
2953 dk_set_index(mp->ma_keys, j, DKIX_DUMMY);
2954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 PyTuple_SET_ITEM(res, 0, ep->me_key);
2956 PyTuple_SET_ITEM(res, 1, ep->me_value);
Victor Stinner742da042016-09-07 17:40:12 -07002957 ep->me_key = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 ep->me_value = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002959 /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
2960 mp->ma_keys->dk_nentries = i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07002962 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner611b0fa2016-09-14 15:02:01 +02002963 assert(_PyDict_CheckConsistency(mp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 return res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002965}
2966
Jeremy Hylton8caad492000-06-23 14:18:11 +00002967static int
2968dict_traverse(PyObject *op, visitproc visit, void *arg)
2969{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002970 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson55f44522016-09-05 12:12:59 -07002971 PyDictKeysObject *keys = mp->ma_keys;
Serhiy Storchaka46825d22016-09-26 21:29:34 +03002972 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Victor Stinner742da042016-09-07 17:40:12 -07002973 Py_ssize_t i, n = keys->dk_nentries;
2974
Benjamin Peterson55f44522016-09-05 12:12:59 -07002975 if (keys->dk_lookup == lookdict) {
2976 for (i = 0; i < n; i++) {
2977 if (entries[i].me_value != NULL) {
2978 Py_VISIT(entries[i].me_value);
2979 Py_VISIT(entries[i].me_key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002980 }
2981 }
Victor Stinner742da042016-09-07 17:40:12 -07002982 }
2983 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002984 if (mp->ma_values != NULL) {
Benjamin Peterson55f44522016-09-05 12:12:59 -07002985 for (i = 0; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002986 Py_VISIT(mp->ma_values[i]);
2987 }
2988 }
2989 else {
Benjamin Peterson55f44522016-09-05 12:12:59 -07002990 for (i = 0; i < n; i++) {
2991 Py_VISIT(entries[i].me_value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002992 }
2993 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 }
2995 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002996}
2997
2998static int
2999dict_tp_clear(PyObject *op)
3000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 PyDict_Clear(op);
3002 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00003003}
3004
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003005static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003006
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003007Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003008_PyDict_SizeOf(PyDictObject *mp)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003009{
Victor Stinner742da042016-09-07 17:40:12 -07003010 Py_ssize_t size, usable, res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003011
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003012 size = DK_SIZE(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07003013 usable = USABLE_FRACTION(size);
3014
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02003015 res = _PyObject_SIZE(Py_TYPE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003016 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07003017 res += usable * sizeof(PyObject*);
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003018 /* If the dictionary is split, the keys portion is accounted-for
3019 in the type object. */
3020 if (mp->ma_keys->dk_refcnt == 1)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003021 res += (sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003022 + DK_IXSIZE(mp->ma_keys) * size
3023 + sizeof(PyDictKeyEntry) * usable);
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003024 return res;
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003025}
3026
3027Py_ssize_t
3028_PyDict_KeysSize(PyDictKeysObject *keys)
3029{
Victor Stinner98ee9d52016-09-08 09:33:56 -07003030 return (sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003031 + DK_IXSIZE(keys) * DK_SIZE(keys)
3032 + USABLE_FRACTION(DK_SIZE(keys)) * sizeof(PyDictKeyEntry));
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003033}
3034
doko@ubuntu.com17210f52016-01-14 14:04:59 +01003035static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303036dict_sizeof(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003037{
3038 return PyLong_FromSsize_t(_PyDict_SizeOf(mp));
3039}
3040
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003041PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
3042
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003043PyDoc_STRVAR(sizeof__doc__,
3044"D.__sizeof__() -> size of D in memory, in bytes");
3045
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003046PyDoc_STRVAR(pop__doc__,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00003047"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00003048If key is not found, d is returned if given, otherwise KeyError is raised");
Guido van Rossume027d982002-04-12 15:11:59 +00003049
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003050PyDoc_STRVAR(popitem__doc__,
Tim Petersf7f88b12000-12-13 23:18:45 +00003051"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000030522-tuple; but raise KeyError if D is empty.");
Tim Petersf7f88b12000-12-13 23:18:45 +00003053
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003054PyDoc_STRVAR(update__doc__,
Brett Cannonf2754162013-05-11 14:46:48 -04003055"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n\
3056If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]\n\
3057If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n\
3058In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00003059
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003060PyDoc_STRVAR(clear__doc__,
3061"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00003062
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003063PyDoc_STRVAR(copy__doc__,
3064"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00003065
Guido van Rossumb90c8482007-02-10 01:11:45 +00003066/* Forward */
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303067static PyObject *dictkeys_new(PyObject *, PyObject *);
3068static PyObject *dictitems_new(PyObject *, PyObject *);
3069static PyObject *dictvalues_new(PyObject *, PyObject *);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003070
Guido van Rossum45c85d12007-07-27 16:31:40 +00003071PyDoc_STRVAR(keys__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 "D.keys() -> a set-like object providing a view on D's keys");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003073PyDoc_STRVAR(items__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 "D.items() -> a set-like object providing a view on D's items");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003075PyDoc_STRVAR(values__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 "D.values() -> an object providing a view on D's values");
Guido van Rossumb90c8482007-02-10 01:11:45 +00003077
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003078static PyMethodDef mapp_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -07003079 DICT___CONTAINS___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
3081 getitem__doc__},
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003082 {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 sizeof__doc__},
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01003084 DICT_GET_METHODDEF
3085 DICT_SETDEFAULT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 {"pop", (PyCFunction)dict_pop, METH_VARARGS,
3087 pop__doc__},
3088 {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
3089 popitem__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303090 {"keys", dictkeys_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 keys__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303092 {"items", dictitems_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 items__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303094 {"values", dictvalues_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 values__doc__},
3096 {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
3097 update__doc__},
Larry Hastings5c661892014-01-24 06:17:25 -08003098 DICT_FROMKEYS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
3100 clear__doc__},
3101 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
3102 copy__doc__},
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003103 DICT___REVERSED___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003105};
3106
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00003107/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00003108int
3109PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003110{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003111 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07003112 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09003114 PyObject *value;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003117 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 hash = PyObject_Hash(key);
3119 if (hash == -1)
3120 return -1;
3121 }
INADA Naoki778928b2017-08-03 23:45:15 +09003122 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07003123 if (ix == DKIX_ERROR)
3124 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09003125 return (ix != DKIX_EMPTY && value != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003126}
3127
Thomas Wouterscf297e42007-02-23 15:07:44 +00003128/* Internal version of PyDict_Contains used when the hash value is already known */
3129int
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003130_PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00003131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09003133 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -07003134 Py_ssize_t ix;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003135
INADA Naoki778928b2017-08-03 23:45:15 +09003136 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07003137 if (ix == DKIX_ERROR)
3138 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09003139 return (ix != DKIX_EMPTY && value != NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00003140}
3141
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003142/* Hack to implement "key in dict" */
3143static PySequenceMethods dict_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 0, /* sq_length */
3145 0, /* sq_concat */
3146 0, /* sq_repeat */
3147 0, /* sq_item */
3148 0, /* sq_slice */
3149 0, /* sq_ass_item */
3150 0, /* sq_ass_slice */
3151 PyDict_Contains, /* sq_contains */
3152 0, /* sq_inplace_concat */
3153 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003154};
3155
Guido van Rossum09e563a2001-05-01 12:10:21 +00003156static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003157dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 PyObject *self;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003160 PyDictObject *d;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 assert(type != NULL && type->tp_alloc != NULL);
3163 self = type->tp_alloc(type, 0);
Victor Stinnera9f61a52013-07-16 22:17:26 +02003164 if (self == NULL)
3165 return NULL;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003166 d = (PyDictObject *)self;
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003167
Victor Stinnera9f61a52013-07-16 22:17:26 +02003168 /* The object has been implicitly tracked by tp_alloc */
3169 if (type == &PyDict_Type)
3170 _PyObject_GC_UNTRACK(d);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003171
3172 d->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07003173 d->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07003174 d->ma_keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003175 if (d->ma_keys == NULL) {
3176 Py_DECREF(self);
3177 return NULL;
3178 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02003179 assert(_PyDict_CheckConsistency(d));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 return self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003181}
3182
Tim Peters25786c02001-09-02 08:22:48 +00003183static int
3184dict_init(PyObject *self, PyObject *args, PyObject *kwds)
3185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00003187}
3188
Tim Peters6d6c1a32001-08-02 04:15:00 +00003189static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003190dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00003191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003193}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003194
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003195PyDoc_STRVAR(dictionary_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00003196"dict() -> new empty dictionary\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00003197"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003198" (key, value) pairs\n"
3199"dict(iterable) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00003200" d = {}\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003201" for k, v in iterable:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00003202" d[k] = v\n"
3203"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
3204" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00003205
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003206PyTypeObject PyDict_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3208 "dict",
3209 sizeof(PyDictObject),
3210 0,
3211 (destructor)dict_dealloc, /* tp_dealloc */
3212 0, /* tp_print */
3213 0, /* tp_getattr */
3214 0, /* tp_setattr */
3215 0, /* tp_reserved */
3216 (reprfunc)dict_repr, /* tp_repr */
3217 0, /* tp_as_number */
3218 &dict_as_sequence, /* tp_as_sequence */
3219 &dict_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003220 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 0, /* tp_call */
3222 0, /* tp_str */
3223 PyObject_GenericGetAttr, /* tp_getattro */
3224 0, /* tp_setattro */
3225 0, /* tp_as_buffer */
3226 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3227 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
3228 dictionary_doc, /* tp_doc */
3229 dict_traverse, /* tp_traverse */
3230 dict_tp_clear, /* tp_clear */
3231 dict_richcompare, /* tp_richcompare */
3232 0, /* tp_weaklistoffset */
3233 (getiterfunc)dict_iter, /* tp_iter */
3234 0, /* tp_iternext */
3235 mapp_methods, /* tp_methods */
3236 0, /* tp_members */
3237 0, /* tp_getset */
3238 0, /* tp_base */
3239 0, /* tp_dict */
3240 0, /* tp_descr_get */
3241 0, /* tp_descr_set */
3242 0, /* tp_dictoffset */
3243 dict_init, /* tp_init */
3244 PyType_GenericAlloc, /* tp_alloc */
3245 dict_new, /* tp_new */
3246 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003247};
3248
Victor Stinner3c1e4812012-03-26 22:10:51 +02003249PyObject *
3250_PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
3251{
3252 PyObject *kv;
3253 kv = _PyUnicode_FromId(key); /* borrowed */
Victor Stinner5b3b1002013-07-22 23:50:57 +02003254 if (kv == NULL) {
3255 PyErr_Clear();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003256 return NULL;
Victor Stinner5b3b1002013-07-22 23:50:57 +02003257 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003258 return PyDict_GetItem(dp, kv);
3259}
3260
Guido van Rossum3cca2451997-05-16 14:23:33 +00003261/* For backward compatibility with old dictionary interface */
3262
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003263PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003264PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 PyObject *kv, *rv;
3267 kv = PyUnicode_FromString(key);
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003268 if (kv == NULL) {
3269 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 return NULL;
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003271 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 rv = PyDict_GetItem(v, kv);
3273 Py_DECREF(kv);
3274 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003275}
3276
3277int
Victor Stinner3c1e4812012-03-26 22:10:51 +02003278_PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
3279{
3280 PyObject *kv;
3281 kv = _PyUnicode_FromId(key); /* borrowed */
3282 if (kv == NULL)
3283 return -1;
3284 return PyDict_SetItem(v, kv, item);
3285}
3286
3287int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003288PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 PyObject *kv;
3291 int err;
3292 kv = PyUnicode_FromString(key);
3293 if (kv == NULL)
3294 return -1;
3295 PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
3296 err = PyDict_SetItem(v, kv, item);
3297 Py_DECREF(kv);
3298 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003299}
3300
3301int
Victor Stinner5fd2e5a2013-11-06 18:58:22 +01003302_PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
3303{
3304 PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
3305 if (kv == NULL)
3306 return -1;
3307 return PyDict_DelItem(v, kv);
3308}
3309
3310int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003311PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 PyObject *kv;
3314 int err;
3315 kv = PyUnicode_FromString(key);
3316 if (kv == NULL)
3317 return -1;
3318 err = PyDict_DelItem(v, kv);
3319 Py_DECREF(kv);
3320 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003321}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003322
Raymond Hettinger019a1482004-03-18 02:41:19 +00003323/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003324
3325typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 PyObject_HEAD
3327 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
3328 Py_ssize_t di_used;
3329 Py_ssize_t di_pos;
3330 PyObject* di_result; /* reusable result tuple for iteritems */
3331 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003332} dictiterobject;
3333
3334static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003335dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 dictiterobject *di;
3338 di = PyObject_GC_New(dictiterobject, itertype);
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003339 if (di == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 return NULL;
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003341 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 Py_INCREF(dict);
3343 di->di_dict = dict;
3344 di->di_used = dict->ma_used;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 di->len = dict->ma_used;
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003346 if ((itertype == &PyDictRevIterKey_Type ||
3347 itertype == &PyDictRevIterItem_Type ||
3348 itertype == &PyDictRevIterValue_Type) && dict->ma_used) {
3349 di->di_pos = dict->ma_keys->dk_nentries - 1;
3350 }
3351 else {
3352 di->di_pos = 0;
3353 }
3354 if (itertype == &PyDictIterItem_Type ||
3355 itertype == &PyDictRevIterItem_Type) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
3357 if (di->di_result == NULL) {
3358 Py_DECREF(di);
3359 return NULL;
3360 }
3361 }
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003362 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 di->di_result = NULL;
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003364 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 _PyObject_GC_TRACK(di);
3366 return (PyObject *)di;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003367}
3368
3369static void
3370dictiter_dealloc(dictiterobject *di)
3371{
INADA Naokia6296d32017-08-24 14:55:17 +09003372 /* bpo-31095: UnTrack is needed before calling any callbacks */
3373 _PyObject_GC_UNTRACK(di);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 Py_XDECREF(di->di_dict);
3375 Py_XDECREF(di->di_result);
3376 PyObject_GC_Del(di);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003377}
3378
3379static int
3380dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
3381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 Py_VISIT(di->di_dict);
3383 Py_VISIT(di->di_result);
3384 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003385}
3386
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003387static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303388dictiter_len(dictiterobject *di, PyObject *Py_UNUSED(ignored))
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 Py_ssize_t len = 0;
3391 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
3392 len = di->len;
3393 return PyLong_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003394}
3395
Guido van Rossumb90c8482007-02-10 01:11:45 +00003396PyDoc_STRVAR(length_hint_doc,
3397 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003398
KristjĂ¡n Valur JĂ³nsson31668b82012-04-03 10:49:41 +00003399static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303400dictiter_reduce(dictiterobject *di, PyObject *Py_UNUSED(ignored));
KristjĂ¡n Valur JĂ³nsson31668b82012-04-03 10:49:41 +00003401
3402PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3403
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003404static PyMethodDef dictiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS,
3406 length_hint_doc},
KristjĂ¡n Valur JĂ³nsson31668b82012-04-03 10:49:41 +00003407 {"__reduce__", (PyCFunction)dictiter_reduce, METH_NOARGS,
3408 reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003410};
3411
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003412static PyObject*
3413dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00003414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 PyObject *key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003416 Py_ssize_t i;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003417 PyDictKeysObject *k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 PyDictObject *d = di->di_dict;
Guido van Rossum213c7a62001-04-23 14:08:49 +00003419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003420 if (d == NULL)
3421 return NULL;
3422 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00003423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 if (di->di_used != d->ma_used) {
3425 PyErr_SetString(PyExc_RuntimeError,
3426 "dictionary changed size during iteration");
3427 di->di_used = -1; /* Make this state sticky */
3428 return NULL;
3429 }
Guido van Rossum2147df72002-07-16 20:30:22 +00003430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 i = di->di_pos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003432 k = d->ma_keys;
INADA Naokica2d8be2016-11-04 16:59:10 +09003433 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003434 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003435 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003436 goto fail;
3437 key = DK_ENTRIES(k)[i].me_key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003438 assert(d->ma_values[i] != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003439 }
3440 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003441 Py_ssize_t n = k->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003442 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
3443 while (i < n && entry_ptr->me_value == NULL) {
3444 entry_ptr++;
3445 i++;
3446 }
3447 if (i >= n)
3448 goto fail;
3449 key = entry_ptr->me_key;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003450 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 di->di_pos = i+1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 di->len--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 Py_INCREF(key);
3454 return key;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003455
3456fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003458 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003459 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003460}
3461
Raymond Hettinger019a1482004-03-18 02:41:19 +00003462PyTypeObject PyDictIterKey_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3464 "dict_keyiterator", /* tp_name */
3465 sizeof(dictiterobject), /* tp_basicsize */
3466 0, /* tp_itemsize */
3467 /* methods */
3468 (destructor)dictiter_dealloc, /* tp_dealloc */
3469 0, /* tp_print */
3470 0, /* tp_getattr */
3471 0, /* tp_setattr */
3472 0, /* tp_reserved */
3473 0, /* tp_repr */
3474 0, /* tp_as_number */
3475 0, /* tp_as_sequence */
3476 0, /* tp_as_mapping */
3477 0, /* tp_hash */
3478 0, /* tp_call */
3479 0, /* tp_str */
3480 PyObject_GenericGetAttr, /* tp_getattro */
3481 0, /* tp_setattro */
3482 0, /* tp_as_buffer */
3483 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3484 0, /* tp_doc */
3485 (traverseproc)dictiter_traverse, /* tp_traverse */
3486 0, /* tp_clear */
3487 0, /* tp_richcompare */
3488 0, /* tp_weaklistoffset */
3489 PyObject_SelfIter, /* tp_iter */
3490 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
3491 dictiter_methods, /* tp_methods */
3492 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003493};
3494
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003495static PyObject *
3496dictiter_iternextvalue(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 PyObject *value;
INADA Naokica2d8be2016-11-04 16:59:10 +09003499 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 if (d == NULL)
3503 return NULL;
3504 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 if (di->di_used != d->ma_used) {
3507 PyErr_SetString(PyExc_RuntimeError,
3508 "dictionary changed size during iteration");
3509 di->di_used = -1; /* Make this state sticky */
3510 return NULL;
3511 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 i = di->di_pos;
INADA Naokica2d8be2016-11-04 16:59:10 +09003514 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003515 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003516 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003517 goto fail;
INADA Naokica2d8be2016-11-04 16:59:10 +09003518 value = d->ma_values[i];
3519 assert(value != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003520 }
3521 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003522 Py_ssize_t n = d->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003523 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3524 while (i < n && entry_ptr->me_value == NULL) {
3525 entry_ptr++;
3526 i++;
3527 }
3528 if (i >= n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 goto fail;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003530 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 }
3532 di->di_pos = i+1;
3533 di->len--;
3534 Py_INCREF(value);
3535 return value;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003536
3537fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003539 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003541}
3542
3543PyTypeObject PyDictIterValue_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3545 "dict_valueiterator", /* tp_name */
3546 sizeof(dictiterobject), /* tp_basicsize */
3547 0, /* tp_itemsize */
3548 /* methods */
3549 (destructor)dictiter_dealloc, /* tp_dealloc */
3550 0, /* tp_print */
3551 0, /* tp_getattr */
3552 0, /* tp_setattr */
3553 0, /* tp_reserved */
3554 0, /* tp_repr */
3555 0, /* tp_as_number */
3556 0, /* tp_as_sequence */
3557 0, /* tp_as_mapping */
3558 0, /* tp_hash */
3559 0, /* tp_call */
3560 0, /* tp_str */
3561 PyObject_GenericGetAttr, /* tp_getattro */
3562 0, /* tp_setattro */
3563 0, /* tp_as_buffer */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003564 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 0, /* tp_doc */
3566 (traverseproc)dictiter_traverse, /* tp_traverse */
3567 0, /* tp_clear */
3568 0, /* tp_richcompare */
3569 0, /* tp_weaklistoffset */
3570 PyObject_SelfIter, /* tp_iter */
3571 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
3572 dictiter_methods, /* tp_methods */
3573 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003574};
3575
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003576static PyObject *
3577dictiter_iternextitem(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003578{
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003579 PyObject *key, *value, *result;
INADA Naokica2d8be2016-11-04 16:59:10 +09003580 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 if (d == NULL)
3584 return NULL;
3585 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 if (di->di_used != d->ma_used) {
3588 PyErr_SetString(PyExc_RuntimeError,
3589 "dictionary changed size during iteration");
3590 di->di_used = -1; /* Make this state sticky */
3591 return NULL;
3592 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 i = di->di_pos;
INADA Naokica2d8be2016-11-04 16:59:10 +09003595 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003596 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003597 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003598 goto fail;
3599 key = DK_ENTRIES(d->ma_keys)[i].me_key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003600 value = d->ma_values[i];
3601 assert(value != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003602 }
3603 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003604 Py_ssize_t n = d->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003605 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3606 while (i < n && entry_ptr->me_value == NULL) {
3607 entry_ptr++;
3608 i++;
3609 }
3610 if (i >= n)
3611 goto fail;
3612 key = entry_ptr->me_key;
3613 value = entry_ptr->me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003614 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 di->di_pos = i+1;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003616 di->len--;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003617 Py_INCREF(key);
3618 Py_INCREF(value);
3619 result = di->di_result;
3620 if (Py_REFCNT(result) == 1) {
3621 PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
3622 PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
3623 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3624 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003625 Py_INCREF(result);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003626 Py_DECREF(oldkey);
3627 Py_DECREF(oldvalue);
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003628 }
3629 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 result = PyTuple_New(2);
3631 if (result == NULL)
3632 return NULL;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003633 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3634 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003636 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003637
3638fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003639 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003640 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003642}
3643
3644PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3646 "dict_itemiterator", /* tp_name */
3647 sizeof(dictiterobject), /* tp_basicsize */
3648 0, /* tp_itemsize */
3649 /* methods */
3650 (destructor)dictiter_dealloc, /* tp_dealloc */
3651 0, /* tp_print */
3652 0, /* tp_getattr */
3653 0, /* tp_setattr */
3654 0, /* tp_reserved */
3655 0, /* tp_repr */
3656 0, /* tp_as_number */
3657 0, /* tp_as_sequence */
3658 0, /* tp_as_mapping */
3659 0, /* tp_hash */
3660 0, /* tp_call */
3661 0, /* tp_str */
3662 PyObject_GenericGetAttr, /* tp_getattro */
3663 0, /* tp_setattro */
3664 0, /* tp_as_buffer */
3665 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3666 0, /* tp_doc */
3667 (traverseproc)dictiter_traverse, /* tp_traverse */
3668 0, /* tp_clear */
3669 0, /* tp_richcompare */
3670 0, /* tp_weaklistoffset */
3671 PyObject_SelfIter, /* tp_iter */
3672 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
3673 dictiter_methods, /* tp_methods */
3674 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003675};
Guido van Rossumb90c8482007-02-10 01:11:45 +00003676
3677
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003678/* dictreviter */
3679
3680static PyObject *
3681dictreviter_iternext(dictiterobject *di)
3682{
3683 PyDictObject *d = di->di_dict;
3684
3685 if (d == NULL) {
3686 return NULL;
3687 }
3688 assert (PyDict_Check(d));
3689
3690 if (di->di_used != d->ma_used) {
3691 PyErr_SetString(PyExc_RuntimeError,
3692 "dictionary changed size during iteration");
3693 di->di_used = -1; /* Make this state sticky */
3694 return NULL;
3695 }
3696
3697 Py_ssize_t i = di->di_pos;
3698 PyDictKeysObject *k = d->ma_keys;
3699 PyObject *key, *value, *result;
3700
3701 if (d->ma_values) {
3702 if (i < 0) {
3703 goto fail;
3704 }
3705 key = DK_ENTRIES(k)[i].me_key;
3706 value = d->ma_values[i];
3707 assert (value != NULL);
3708 }
3709 else {
3710 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
3711 while (i >= 0 && entry_ptr->me_value == NULL) {
3712 entry_ptr--;
3713 i--;
3714 }
3715 if (i < 0) {
3716 goto fail;
3717 }
3718 key = entry_ptr->me_key;
3719 value = entry_ptr->me_value;
3720 }
3721 di->di_pos = i-1;
3722 di->len--;
3723
3724 if (Py_TYPE(di) == &PyDictRevIterKey_Type) {
3725 Py_INCREF(key);
3726 return key;
3727 }
3728 else if (Py_TYPE(di) == &PyDictRevIterValue_Type) {
3729 Py_INCREF(value);
3730 return value;
3731 }
3732 else if (Py_TYPE(di) == &PyDictRevIterItem_Type) {
3733 Py_INCREF(key);
3734 Py_INCREF(value);
3735 result = di->di_result;
3736 if (Py_REFCNT(result) == 1) {
3737 PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
3738 PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
3739 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3740 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
3741 Py_INCREF(result);
3742 Py_DECREF(oldkey);
3743 Py_DECREF(oldvalue);
3744 }
3745 else {
3746 result = PyTuple_New(2);
3747 if (result == NULL) {
3748 return NULL;
3749 }
3750 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3751 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
3752 }
3753 return result;
3754 }
3755 else {
3756 Py_UNREACHABLE();
3757 }
3758
3759fail:
3760 di->di_dict = NULL;
3761 Py_DECREF(d);
3762 return NULL;
3763}
3764
3765PyTypeObject PyDictRevIterKey_Type = {
3766 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3767 "dict_reversekeyiterator",
3768 sizeof(dictiterobject),
3769 .tp_dealloc = (destructor)dictiter_dealloc,
3770 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3771 .tp_traverse = (traverseproc)dictiter_traverse,
3772 .tp_iter = PyObject_SelfIter,
3773 .tp_iternext = (iternextfunc)dictreviter_iternext,
3774 .tp_methods = dictiter_methods
3775};
3776
3777
3778/*[clinic input]
3779dict.__reversed__
3780
3781Return a reverse iterator over the dict keys.
3782[clinic start generated code]*/
3783
3784static PyObject *
3785dict___reversed___impl(PyDictObject *self)
3786/*[clinic end generated code: output=e674483336d1ed51 input=23210ef3477d8c4d]*/
3787{
3788 assert (PyDict_Check(self));
3789 return dictiter_new(self, &PyDictRevIterKey_Type);
3790}
3791
KristjĂ¡n Valur JĂ³nsson31668b82012-04-03 10:49:41 +00003792static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303793dictiter_reduce(dictiterobject *di, PyObject *Py_UNUSED(ignored))
KristjĂ¡n Valur JĂ³nsson31668b82012-04-03 10:49:41 +00003794{
Sergey Fedoseev63958442018-10-20 05:43:33 +05003795 /* copy the iterator state */
3796 dictiterobject tmp = *di;
KristjĂ¡n Valur JĂ³nsson31668b82012-04-03 10:49:41 +00003797 Py_XINCREF(tmp.di_dict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003798
Sergey Fedoseev63958442018-10-20 05:43:33 +05003799 PyObject *list = PySequence_List((PyObject*)&tmp);
KristjĂ¡n Valur JĂ³nsson31668b82012-04-03 10:49:41 +00003800 Py_XDECREF(tmp.di_dict);
Sergey Fedoseev63958442018-10-20 05:43:33 +05003801 if (list == NULL) {
KristjĂ¡n Valur JĂ³nsson31668b82012-04-03 10:49:41 +00003802 return NULL;
3803 }
Antoine Pitroua7013882012-04-05 00:04:20 +02003804 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
KristjĂ¡n Valur JĂ³nsson31668b82012-04-03 10:49:41 +00003805}
3806
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01003807PyTypeObject PyDictRevIterItem_Type = {
3808 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3809 "dict_reverseitemiterator",
3810 sizeof(dictiterobject),
3811 .tp_dealloc = (destructor)dictiter_dealloc,
3812 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3813 .tp_traverse = (traverseproc)dictiter_traverse,
3814 .tp_iter = PyObject_SelfIter,
3815 .tp_iternext = (iternextfunc)dictreviter_iternext,
3816 .tp_methods = dictiter_methods
3817};
3818
3819PyTypeObject PyDictRevIterValue_Type = {
3820 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3821 "dict_reversevalueiterator",
3822 sizeof(dictiterobject),
3823 .tp_dealloc = (destructor)dictiter_dealloc,
3824 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
3825 .tp_traverse = (traverseproc)dictiter_traverse,
3826 .tp_iter = PyObject_SelfIter,
3827 .tp_iternext = (iternextfunc)dictreviter_iternext,
3828 .tp_methods = dictiter_methods
3829};
3830
Guido van Rossum3ac67412007-02-10 18:55:06 +00003831/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003832/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00003833/***********************************************/
3834
Guido van Rossumb90c8482007-02-10 01:11:45 +00003835/* The instance lay-out is the same for all three; but the type differs. */
3836
Guido van Rossumb90c8482007-02-10 01:11:45 +00003837static void
Eric Snow96c6af92015-05-29 22:21:39 -06003838dictview_dealloc(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003839{
INADA Naokia6296d32017-08-24 14:55:17 +09003840 /* bpo-31095: UnTrack is needed before calling any callbacks */
3841 _PyObject_GC_UNTRACK(dv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 Py_XDECREF(dv->dv_dict);
3843 PyObject_GC_Del(dv);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003844}
3845
3846static int
Eric Snow96c6af92015-05-29 22:21:39 -06003847dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 Py_VISIT(dv->dv_dict);
3850 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003851}
3852
Guido van Rossum83825ac2007-02-10 04:54:19 +00003853static Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003854dictview_len(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003856 Py_ssize_t len = 0;
3857 if (dv->dv_dict != NULL)
3858 len = dv->dv_dict->ma_used;
3859 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003860}
3861
Eric Snow96c6af92015-05-29 22:21:39 -06003862PyObject *
3863_PyDictView_New(PyObject *dict, PyTypeObject *type)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003864{
Eric Snow96c6af92015-05-29 22:21:39 -06003865 _PyDictViewObject *dv;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 if (dict == NULL) {
3867 PyErr_BadInternalCall();
3868 return NULL;
3869 }
3870 if (!PyDict_Check(dict)) {
3871 /* XXX Get rid of this restriction later */
3872 PyErr_Format(PyExc_TypeError,
3873 "%s() requires a dict argument, not '%s'",
3874 type->tp_name, dict->ob_type->tp_name);
3875 return NULL;
3876 }
Eric Snow96c6af92015-05-29 22:21:39 -06003877 dv = PyObject_GC_New(_PyDictViewObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 if (dv == NULL)
3879 return NULL;
3880 Py_INCREF(dict);
3881 dv->dv_dict = (PyDictObject *)dict;
3882 _PyObject_GC_TRACK(dv);
3883 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003884}
3885
Neal Norwitze36f2ba2007-02-26 23:12:28 +00003886/* TODO(guido): The views objects are not complete:
3887
3888 * support more set operations
3889 * support arbitrary mappings?
3890 - either these should be static or exported in dictobject.h
3891 - if public then they should probably be in builtins
3892*/
3893
Guido van Rossumaac530c2007-08-24 22:33:45 +00003894/* Return 1 if self is a subset of other, iterating over self;
3895 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00003896static int
3897all_contained_in(PyObject *self, PyObject *other)
3898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 PyObject *iter = PyObject_GetIter(self);
3900 int ok = 1;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 if (iter == NULL)
3903 return -1;
3904 for (;;) {
3905 PyObject *next = PyIter_Next(iter);
3906 if (next == NULL) {
3907 if (PyErr_Occurred())
3908 ok = -1;
3909 break;
3910 }
3911 ok = PySequence_Contains(other, next);
3912 Py_DECREF(next);
3913 if (ok <= 0)
3914 break;
3915 }
3916 Py_DECREF(iter);
3917 return ok;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003918}
3919
3920static PyObject *
3921dictview_richcompare(PyObject *self, PyObject *other, int op)
3922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 Py_ssize_t len_self, len_other;
3924 int ok;
3925 PyObject *result;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927 assert(self != NULL);
3928 assert(PyDictViewSet_Check(self));
3929 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00003930
Brian Curtindfc80e32011-08-10 20:28:54 -05003931 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
3932 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003934 len_self = PyObject_Size(self);
3935 if (len_self < 0)
3936 return NULL;
3937 len_other = PyObject_Size(other);
3938 if (len_other < 0)
3939 return NULL;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 ok = 0;
3942 switch(op) {
Guido van Rossumaac530c2007-08-24 22:33:45 +00003943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 case Py_NE:
3945 case Py_EQ:
3946 if (len_self == len_other)
3947 ok = all_contained_in(self, other);
3948 if (op == Py_NE && ok >= 0)
3949 ok = !ok;
3950 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 case Py_LT:
3953 if (len_self < len_other)
3954 ok = all_contained_in(self, other);
3955 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003957 case Py_LE:
3958 if (len_self <= len_other)
3959 ok = all_contained_in(self, other);
3960 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 case Py_GT:
3963 if (len_self > len_other)
3964 ok = all_contained_in(other, self);
3965 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 case Py_GE:
3968 if (len_self >= len_other)
3969 ok = all_contained_in(other, self);
3970 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 }
3973 if (ok < 0)
3974 return NULL;
3975 result = ok ? Py_True : Py_False;
3976 Py_INCREF(result);
3977 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003978}
3979
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003980static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003981dictview_repr(_PyDictViewObject *dv)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003983 PyObject *seq;
bennorthd7773d92018-01-26 15:46:01 +00003984 PyObject *result = NULL;
3985 Py_ssize_t rc;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003986
bennorthd7773d92018-01-26 15:46:01 +00003987 rc = Py_ReprEnter((PyObject *)dv);
3988 if (rc != 0) {
3989 return rc > 0 ? PyUnicode_FromString("...") : NULL;
3990 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003991 seq = PySequence_List((PyObject *)dv);
bennorthd7773d92018-01-26 15:46:01 +00003992 if (seq == NULL) {
3993 goto Done;
3994 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003995 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
3996 Py_DECREF(seq);
bennorthd7773d92018-01-26 15:46:01 +00003997
3998Done:
3999 Py_ReprLeave((PyObject *)dv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004000 return result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00004001}
4002
Guido van Rossum3ac67412007-02-10 18:55:06 +00004003/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004004
4005static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004006dictkeys_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004008 if (dv->dv_dict == NULL) {
4009 Py_RETURN_NONE;
4010 }
4011 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00004012}
4013
4014static int
Eric Snow96c6af92015-05-29 22:21:39 -06004015dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00004016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 if (dv->dv_dict == NULL)
4018 return 0;
4019 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004020}
4021
Guido van Rossum83825ac2007-02-10 04:54:19 +00004022static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 (lenfunc)dictview_len, /* sq_length */
4024 0, /* sq_concat */
4025 0, /* sq_repeat */
4026 0, /* sq_item */
4027 0, /* sq_slice */
4028 0, /* sq_ass_item */
4029 0, /* sq_ass_slice */
4030 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004031};
4032
Guido van Rossum523259b2007-08-24 23:41:22 +00004033static PyObject*
4034dictviews_sub(PyObject* self, PyObject *other)
4035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004036 PyObject *result = PySet_New(self);
4037 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004038 _Py_IDENTIFIER(difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004040 if (result == NULL)
4041 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004042
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08004043 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 if (tmp == NULL) {
4045 Py_DECREF(result);
4046 return NULL;
4047 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 Py_DECREF(tmp);
4050 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004051}
4052
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004053PyObject*
4054_PyDictView_Intersect(PyObject* self, PyObject *other)
Guido van Rossum523259b2007-08-24 23:41:22 +00004055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 PyObject *result = PySet_New(self);
4057 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004058 _Py_IDENTIFIER(intersection_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004060 if (result == NULL)
4061 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004062
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08004063 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_intersection_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004064 if (tmp == NULL) {
4065 Py_DECREF(result);
4066 return NULL;
4067 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 Py_DECREF(tmp);
4070 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004071}
4072
4073static PyObject*
4074dictviews_or(PyObject* self, PyObject *other)
4075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004076 PyObject *result = PySet_New(self);
4077 PyObject *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02004078 _Py_IDENTIFIER(update);
Victor Stinnerd1a9cc22011-10-13 22:51:17 +02004079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 if (result == NULL)
4081 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004082
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08004083 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004084 if (tmp == NULL) {
4085 Py_DECREF(result);
4086 return NULL;
4087 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004089 Py_DECREF(tmp);
4090 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004091}
4092
4093static PyObject*
4094dictviews_xor(PyObject* self, PyObject *other)
4095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 PyObject *result = PySet_New(self);
4097 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004098 _Py_IDENTIFIER(symmetric_difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 if (result == NULL)
4101 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004102
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08004103 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_symmetric_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 if (tmp == NULL) {
4105 Py_DECREF(result);
4106 return NULL;
4107 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 Py_DECREF(tmp);
4110 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004111}
4112
4113static PyNumberMethods dictviews_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004114 0, /*nb_add*/
4115 (binaryfunc)dictviews_sub, /*nb_subtract*/
4116 0, /*nb_multiply*/
4117 0, /*nb_remainder*/
4118 0, /*nb_divmod*/
4119 0, /*nb_power*/
4120 0, /*nb_negative*/
4121 0, /*nb_positive*/
4122 0, /*nb_absolute*/
4123 0, /*nb_bool*/
4124 0, /*nb_invert*/
4125 0, /*nb_lshift*/
4126 0, /*nb_rshift*/
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004127 (binaryfunc)_PyDictView_Intersect, /*nb_and*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 (binaryfunc)dictviews_xor, /*nb_xor*/
4129 (binaryfunc)dictviews_or, /*nb_or*/
Guido van Rossum523259b2007-08-24 23:41:22 +00004130};
4131
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004132static PyObject*
4133dictviews_isdisjoint(PyObject *self, PyObject *other)
4134{
4135 PyObject *it;
4136 PyObject *item = NULL;
4137
4138 if (self == other) {
Eric Snow96c6af92015-05-29 22:21:39 -06004139 if (dictview_len((_PyDictViewObject *)self) == 0)
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004140 Py_RETURN_TRUE;
4141 else
4142 Py_RETURN_FALSE;
4143 }
4144
4145 /* Iterate over the shorter object (only if other is a set,
4146 * because PySequence_Contains may be expensive otherwise): */
4147 if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
Eric Snow96c6af92015-05-29 22:21:39 -06004148 Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004149 Py_ssize_t len_other = PyObject_Size(other);
4150 if (len_other == -1)
4151 return NULL;
4152
4153 if ((len_other > len_self)) {
4154 PyObject *tmp = other;
4155 other = self;
4156 self = tmp;
4157 }
4158 }
4159
4160 it = PyObject_GetIter(other);
4161 if (it == NULL)
4162 return NULL;
4163
4164 while ((item = PyIter_Next(it)) != NULL) {
4165 int contains = PySequence_Contains(self, item);
4166 Py_DECREF(item);
4167 if (contains == -1) {
4168 Py_DECREF(it);
4169 return NULL;
4170 }
4171
4172 if (contains) {
4173 Py_DECREF(it);
4174 Py_RETURN_FALSE;
4175 }
4176 }
4177 Py_DECREF(it);
4178 if (PyErr_Occurred())
4179 return NULL; /* PyIter_Next raised an exception. */
4180 Py_RETURN_TRUE;
4181}
4182
4183PyDoc_STRVAR(isdisjoint_doc,
4184"Return True if the view and the given iterable have a null intersection.");
4185
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004186static PyObject* dictkeys_reversed(_PyDictViewObject *dv);
4187
4188PyDoc_STRVAR(reversed_keys_doc,
4189"Return a reverse iterator over the dict keys.");
4190
Guido van Rossumb90c8482007-02-10 01:11:45 +00004191static PyMethodDef dictkeys_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004192 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4193 isdisjoint_doc},
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004194 {"__reversed__", (PyCFunction)dictkeys_reversed, METH_NOARGS,
4195 reversed_keys_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004196 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004197};
4198
4199PyTypeObject PyDictKeys_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004200 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4201 "dict_keys", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004202 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004203 0, /* tp_itemsize */
4204 /* methods */
4205 (destructor)dictview_dealloc, /* tp_dealloc */
4206 0, /* tp_print */
4207 0, /* tp_getattr */
4208 0, /* tp_setattr */
4209 0, /* tp_reserved */
4210 (reprfunc)dictview_repr, /* tp_repr */
4211 &dictviews_as_number, /* tp_as_number */
4212 &dictkeys_as_sequence, /* tp_as_sequence */
4213 0, /* tp_as_mapping */
4214 0, /* tp_hash */
4215 0, /* tp_call */
4216 0, /* tp_str */
4217 PyObject_GenericGetAttr, /* tp_getattro */
4218 0, /* tp_setattro */
4219 0, /* tp_as_buffer */
4220 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4221 0, /* tp_doc */
4222 (traverseproc)dictview_traverse, /* tp_traverse */
4223 0, /* tp_clear */
4224 dictview_richcompare, /* tp_richcompare */
4225 0, /* tp_weaklistoffset */
4226 (getiterfunc)dictkeys_iter, /* tp_iter */
4227 0, /* tp_iternext */
4228 dictkeys_methods, /* tp_methods */
4229 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004230};
4231
4232static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304233dictkeys_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004234{
Eric Snow96c6af92015-05-29 22:21:39 -06004235 return _PyDictView_New(dict, &PyDictKeys_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004236}
4237
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004238static PyObject *
4239dictkeys_reversed(_PyDictViewObject *dv)
4240{
4241 if (dv->dv_dict == NULL) {
4242 Py_RETURN_NONE;
4243 }
4244 return dictiter_new(dv->dv_dict, &PyDictRevIterKey_Type);
4245}
4246
Guido van Rossum3ac67412007-02-10 18:55:06 +00004247/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004248
4249static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004250dictitems_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004252 if (dv->dv_dict == NULL) {
4253 Py_RETURN_NONE;
4254 }
4255 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00004256}
4257
4258static int
Eric Snow96c6af92015-05-29 22:21:39 -06004259dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00004260{
Serhiy Storchaka753bca32017-05-20 12:30:02 +03004261 int result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 PyObject *key, *value, *found;
4263 if (dv->dv_dict == NULL)
4264 return 0;
4265 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
4266 return 0;
4267 key = PyTuple_GET_ITEM(obj, 0);
4268 value = PyTuple_GET_ITEM(obj, 1);
Raymond Hettinger6692f012016-09-18 21:46:08 -07004269 found = PyDict_GetItemWithError((PyObject *)dv->dv_dict, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004270 if (found == NULL) {
4271 if (PyErr_Occurred())
4272 return -1;
4273 return 0;
4274 }
Serhiy Storchaka753bca32017-05-20 12:30:02 +03004275 Py_INCREF(found);
4276 result = PyObject_RichCompareBool(value, found, Py_EQ);
4277 Py_DECREF(found);
4278 return result;
Guido van Rossumb90c8482007-02-10 01:11:45 +00004279}
4280
Guido van Rossum83825ac2007-02-10 04:54:19 +00004281static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004282 (lenfunc)dictview_len, /* sq_length */
4283 0, /* sq_concat */
4284 0, /* sq_repeat */
4285 0, /* sq_item */
4286 0, /* sq_slice */
4287 0, /* sq_ass_item */
4288 0, /* sq_ass_slice */
4289 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004290};
4291
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004292static PyObject* dictitems_reversed(_PyDictViewObject *dv);
4293
4294PyDoc_STRVAR(reversed_items_doc,
4295"Return a reverse iterator over the dict items.");
4296
Guido van Rossumb90c8482007-02-10 01:11:45 +00004297static PyMethodDef dictitems_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004298 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4299 isdisjoint_doc},
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004300 {"__reversed__", (PyCFunction)dictitems_reversed, METH_NOARGS,
4301 reversed_items_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004302 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004303};
4304
4305PyTypeObject PyDictItems_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004306 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4307 "dict_items", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004308 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309 0, /* tp_itemsize */
4310 /* methods */
4311 (destructor)dictview_dealloc, /* tp_dealloc */
4312 0, /* tp_print */
4313 0, /* tp_getattr */
4314 0, /* tp_setattr */
4315 0, /* tp_reserved */
4316 (reprfunc)dictview_repr, /* tp_repr */
4317 &dictviews_as_number, /* tp_as_number */
4318 &dictitems_as_sequence, /* tp_as_sequence */
4319 0, /* tp_as_mapping */
4320 0, /* tp_hash */
4321 0, /* tp_call */
4322 0, /* tp_str */
4323 PyObject_GenericGetAttr, /* tp_getattro */
4324 0, /* tp_setattro */
4325 0, /* tp_as_buffer */
4326 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4327 0, /* tp_doc */
4328 (traverseproc)dictview_traverse, /* tp_traverse */
4329 0, /* tp_clear */
4330 dictview_richcompare, /* tp_richcompare */
4331 0, /* tp_weaklistoffset */
4332 (getiterfunc)dictitems_iter, /* tp_iter */
4333 0, /* tp_iternext */
4334 dictitems_methods, /* tp_methods */
4335 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004336};
4337
4338static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304339dictitems_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004340{
Eric Snow96c6af92015-05-29 22:21:39 -06004341 return _PyDictView_New(dict, &PyDictItems_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004342}
4343
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004344static PyObject *
4345dictitems_reversed(_PyDictViewObject *dv)
4346{
4347 if (dv->dv_dict == NULL) {
4348 Py_RETURN_NONE;
4349 }
4350 return dictiter_new(dv->dv_dict, &PyDictRevIterItem_Type);
4351}
4352
Guido van Rossum3ac67412007-02-10 18:55:06 +00004353/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004354
4355static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004356dictvalues_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 if (dv->dv_dict == NULL) {
4359 Py_RETURN_NONE;
4360 }
4361 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004362}
4363
Guido van Rossum83825ac2007-02-10 04:54:19 +00004364static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004365 (lenfunc)dictview_len, /* sq_length */
4366 0, /* sq_concat */
4367 0, /* sq_repeat */
4368 0, /* sq_item */
4369 0, /* sq_slice */
4370 0, /* sq_ass_item */
4371 0, /* sq_ass_slice */
4372 (objobjproc)0, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004373};
4374
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004375static PyObject* dictvalues_reversed(_PyDictViewObject *dv);
4376
4377PyDoc_STRVAR(reversed_values_doc,
4378"Return a reverse iterator over the dict values.");
4379
Guido van Rossumb90c8482007-02-10 01:11:45 +00004380static PyMethodDef dictvalues_methods[] = {
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004381 {"__reversed__", (PyCFunction)dictvalues_reversed, METH_NOARGS,
4382 reversed_values_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004384};
4385
4386PyTypeObject PyDictValues_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004387 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4388 "dict_values", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004389 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004390 0, /* tp_itemsize */
4391 /* methods */
4392 (destructor)dictview_dealloc, /* tp_dealloc */
4393 0, /* tp_print */
4394 0, /* tp_getattr */
4395 0, /* tp_setattr */
4396 0, /* tp_reserved */
4397 (reprfunc)dictview_repr, /* tp_repr */
4398 0, /* tp_as_number */
4399 &dictvalues_as_sequence, /* tp_as_sequence */
4400 0, /* tp_as_mapping */
4401 0, /* tp_hash */
4402 0, /* tp_call */
4403 0, /* tp_str */
4404 PyObject_GenericGetAttr, /* tp_getattro */
4405 0, /* tp_setattro */
4406 0, /* tp_as_buffer */
4407 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4408 0, /* tp_doc */
4409 (traverseproc)dictview_traverse, /* tp_traverse */
4410 0, /* tp_clear */
4411 0, /* tp_richcompare */
4412 0, /* tp_weaklistoffset */
4413 (getiterfunc)dictvalues_iter, /* tp_iter */
4414 0, /* tp_iternext */
4415 dictvalues_methods, /* tp_methods */
4416 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004417};
4418
4419static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304420dictvalues_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004421{
Eric Snow96c6af92015-05-29 22:21:39 -06004422 return _PyDictView_New(dict, &PyDictValues_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004423}
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004424
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01004425static PyObject *
4426dictvalues_reversed(_PyDictViewObject *dv)
4427{
4428 if (dv->dv_dict == NULL) {
4429 Py_RETURN_NONE;
4430 }
4431 return dictiter_new(dv->dv_dict, &PyDictRevIterValue_Type);
4432}
4433
4434
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004435/* Returns NULL if cannot allocate a new PyDictKeysObject,
4436 but does not set an error */
4437PyDictKeysObject *
4438_PyDict_NewKeysForClass(void)
4439{
Victor Stinner742da042016-09-07 17:40:12 -07004440 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004441 if (keys == NULL)
4442 PyErr_Clear();
4443 else
4444 keys->dk_lookup = lookdict_split;
4445 return keys;
4446}
4447
4448#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
4449
4450PyObject *
4451PyObject_GenericGetDict(PyObject *obj, void *context)
4452{
4453 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
4454 if (dictptr == NULL) {
4455 PyErr_SetString(PyExc_AttributeError,
4456 "This object has no __dict__");
4457 return NULL;
4458 }
4459 dict = *dictptr;
4460 if (dict == NULL) {
4461 PyTypeObject *tp = Py_TYPE(obj);
4462 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
4463 DK_INCREF(CACHED_KEYS(tp));
4464 *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
4465 }
4466 else {
4467 *dictptr = dict = PyDict_New();
4468 }
4469 }
4470 Py_XINCREF(dict);
4471 return dict;
4472}
4473
4474int
4475_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
Victor Stinner742da042016-09-07 17:40:12 -07004476 PyObject *key, PyObject *value)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004477{
4478 PyObject *dict;
4479 int res;
4480 PyDictKeysObject *cached;
4481
4482 assert(dictptr != NULL);
4483 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
4484 assert(dictptr != NULL);
4485 dict = *dictptr;
4486 if (dict == NULL) {
4487 DK_INCREF(cached);
4488 dict = new_dict_with_shared_keys(cached);
4489 if (dict == NULL)
4490 return -1;
4491 *dictptr = dict;
4492 }
4493 if (value == NULL) {
4494 res = PyDict_DelItem(dict, key);
INADA Naoki2294f3a2017-02-12 13:51:30 +09004495 // Since key sharing dict doesn't allow deletion, PyDict_DelItem()
4496 // always converts dict to combined form.
4497 if ((cached = CACHED_KEYS(tp)) != NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004498 CACHED_KEYS(tp) = NULL;
4499 DK_DECREF(cached);
4500 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01004501 }
4502 else {
INADA Naoki2294f3a2017-02-12 13:51:30 +09004503 int was_shared = (cached == ((PyDictObject *)dict)->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004504 res = PyDict_SetItem(dict, key, value);
INADA Naoki2294f3a2017-02-12 13:51:30 +09004505 if (was_shared &&
4506 (cached = CACHED_KEYS(tp)) != NULL &&
4507 cached != ((PyDictObject *)dict)->ma_keys) {
Victor Stinner3d3f2642016-12-15 17:21:23 +01004508 /* PyDict_SetItem() may call dictresize and convert split table
4509 * into combined table. In such case, convert it to split
4510 * table again and update type's shared key only when this is
4511 * the only dict sharing key with the type.
4512 *
4513 * This is to allow using shared key in class like this:
4514 *
4515 * class C:
4516 * def __init__(self):
4517 * # one dict resize happens
4518 * self.a, self.b, self.c = 1, 2, 3
4519 * self.d, self.e, self.f = 4, 5, 6
4520 * a = C()
4521 */
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004522 if (cached->dk_refcnt == 1) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004523 CACHED_KEYS(tp) = make_keys_shared(dict);
Victor Stinner742da042016-09-07 17:40:12 -07004524 }
4525 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004526 CACHED_KEYS(tp) = NULL;
4527 }
4528 DK_DECREF(cached);
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004529 if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
4530 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004531 }
4532 }
4533 } else {
4534 dict = *dictptr;
4535 if (dict == NULL) {
4536 dict = PyDict_New();
4537 if (dict == NULL)
4538 return -1;
4539 *dictptr = dict;
4540 }
4541 if (value == NULL) {
4542 res = PyDict_DelItem(dict, key);
4543 } else {
4544 res = PyDict_SetItem(dict, key, value);
4545 }
4546 }
4547 return res;
4548}
4549
4550void
4551_PyDictKeys_DecRef(PyDictKeysObject *keys)
4552{
4553 DK_DECREF(keys);
4554}