blob: 370895d6bcc8fd9e33d0e6e3fe578a50e7747ad5 [file] [log] [blame]
Guido van Rossum2bc13791999-03-24 19:06:42 +00001/* Dictionary object implementation using a hash table */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002
Raymond Hettinger930427b2003-05-03 06:51:59 +00003/* The distribution includes a separate file, Objects/dictnotes.txt,
Tim Peters60b29962006-01-01 01:19:23 +00004 describing explorations into dictionary design and optimization.
Raymond Hettinger930427b2003-05-03 06:51:59 +00005 It covers typical dictionary use patterns, the parameters for
6 tuning dictionaries, and several ideas for possible optimizations.
7*/
8
Victor Stinner742da042016-09-07 17:40:12 -07009/* PyDictKeysObject
10
11This implements the dictionary's hashtable.
12
Raymond Hettingerb12785d2016-10-22 09:58:14 -070013As of Python 3.6, this is compact and ordered. Basic idea is described here:
14* https://mail.python.org/pipermail/python-dev/2012-December/123028.html
15* https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html
Victor Stinner742da042016-09-07 17:40:12 -070016
17layout:
18
19+---------------+
20| dk_refcnt |
21| dk_size |
22| dk_lookup |
23| dk_usable |
24| dk_nentries |
25+---------------+
26| dk_indices |
27| |
28+---------------+
29| dk_entries |
30| |
31+---------------+
32
33dk_indices is actual hashtable. It holds index in entries, or DKIX_EMPTY(-1)
34or DKIX_DUMMY(-2).
35Size of indices is dk_size. Type of each index in indices is vary on dk_size:
36
37* int8 for dk_size <= 128
38* int16 for 256 <= dk_size <= 2**15
39* int32 for 2**16 <= dk_size <= 2**31
40* int64 for 2**32 <= dk_size
41
42dk_entries is array of PyDictKeyEntry. It's size is USABLE_FRACTION(dk_size).
43DK_ENTRIES(dk) can be used to get pointer to entries.
44
45NOTE: Since negative value is used for DKIX_EMPTY and DKIX_DUMMY, type of
46dk_indices entry is signed integer and int16 is used for table which
47dk_size == 256.
48*/
49
Benjamin Peterson7d95e402012-04-23 11:24:50 -040050
51/*
Benjamin Peterson7d95e402012-04-23 11:24:50 -040052The DictObject can be in one of two forms.
Victor Stinner742da042016-09-07 17:40:12 -070053
Benjamin Peterson7d95e402012-04-23 11:24:50 -040054Either:
55 A combined table:
56 ma_values == NULL, dk_refcnt == 1.
57 Values are stored in the me_value field of the PyDictKeysObject.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040058Or:
59 A split table:
60 ma_values != NULL, dk_refcnt >= 1
61 Values are stored in the ma_values array.
Victor Stinner742da042016-09-07 17:40:12 -070062 Only string (unicode) keys are allowed.
63 All dicts sharing same key must have same insertion order.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040064
Victor Stinner742da042016-09-07 17:40:12 -070065There are four kinds of slots in the table (slot is index, and
66DK_ENTRIES(keys)[index] if index >= 0):
67
681. Unused. index == DKIX_EMPTY
69 Does not hold an active (key, value) pair now and never did. Unused can
70 transition to Active upon key insertion. This is each slot's initial state.
71
722. Active. index >= 0, me_key != NULL and me_value != NULL
73 Holds an active (key, value) pair. Active can transition to Dummy or
74 Pending upon key deletion (for combined and split tables respectively).
75 This is the only case in which me_value != NULL.
76
773. Dummy. index == DKIX_DUMMY (combined only)
78 Previously held an active (key, value) pair, but that was deleted and an
79 active pair has not yet overwritten the slot. Dummy can transition to
80 Active upon key insertion. Dummy slots cannot be made Unused again
81 else the probe sequence in case of collision would have no way to know
82 they were once active.
83
844. Pending. index >= 0, key != NULL, and value == NULL (split only)
85 Not yet inserted in split-table.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040086*/
87
Victor Stinner742da042016-09-07 17:40:12 -070088/*
89Preserving insertion order
Benjamin Peterson7d95e402012-04-23 11:24:50 -040090
Victor Stinner742da042016-09-07 17:40:12 -070091It's simple for combined table. Since dk_entries is mostly append only, we can
92get insertion order by just iterating dk_entries.
93
94One exception is .popitem(). It removes last item in dk_entries and decrement
95dk_nentries to achieve amortized O(1). Since there are DKIX_DUMMY remains in
96dk_indices, we can't increment dk_usable even though dk_nentries is
97decremented.
98
99In split table, inserting into pending entry is allowed only for dk_entries[ix]
100where ix == mp->ma_used. Inserting into other index and deleting item cause
101converting the dict to the combined table.
102*/
103
104/* PyDict_MINSIZE is the starting size for any new dict.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400105 * 8 allows dicts with no more than 5 active entries; experiments suggested
106 * this suffices for the majority of dicts (consisting mostly of usually-small
107 * dicts created to pass keyword arguments).
108 * Making this 8, rather than 4 reduces the number of resizes for most
109 * dictionaries, without any significant extra memory use.
110 */
Victor Stinner742da042016-09-07 17:40:12 -0700111#define PyDict_MINSIZE 8
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400112
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113#include "Python.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600114#include "internal/pystate.h"
Eric Snow96c6af92015-05-29 22:21:39 -0600115#include "dict-common.h"
Victor Stinner990397e2016-09-09 20:22:59 -0700116#include "stringlib/eq.h" /* to get unicode_eq() */
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000117
Larry Hastings61272b72014-01-07 12:41:53 -0800118/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -0800119class dict "PyDictObject *" "&PyDict_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800120[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -0800121/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f157a5a0ce9589d6]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800122
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400123
124/*
125To ensure the lookup algorithm terminates, there must be at least one Unused
126slot (NULL key) in the table.
127To avoid slowing down lookups on a near-full table, we resize the table when
128it's USABLE_FRACTION (currently two-thirds) full.
129*/
Guido van Rossum16e93a81997-01-28 00:00:11 +0000130
Tim Peterseb28ef22001-06-02 05:27:19 +0000131#define PERTURB_SHIFT 5
132
Guido van Rossum16e93a81997-01-28 00:00:11 +0000133/*
Tim Peterseb28ef22001-06-02 05:27:19 +0000134Major subtleties ahead: Most hash schemes depend on having a "good" hash
135function, in the sense of simulating randomness. Python doesn't: its most
R David Murray537ad7a2016-07-10 12:33:18 -0400136important hash functions (for ints) are very regular in common
Tim Peterseb28ef22001-06-02 05:27:19 +0000137cases:
Tim Peters15d49292001-05-27 07:39:22 +0000138
R David Murray537ad7a2016-07-10 12:33:18 -0400139 >>>[hash(i) for i in range(4)]
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000140 [0, 1, 2, 3]
Tim Peters15d49292001-05-27 07:39:22 +0000141
Tim Peterseb28ef22001-06-02 05:27:19 +0000142This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
143the low-order i bits as the initial table index is extremely fast, and there
R David Murray537ad7a2016-07-10 12:33:18 -0400144are no collisions at all for dicts indexed by a contiguous range of ints. So
145this gives better-than-random behavior in common cases, and that's very
146desirable.
Tim Peters15d49292001-05-27 07:39:22 +0000147
Tim Peterseb28ef22001-06-02 05:27:19 +0000148OTOH, when collisions occur, the tendency to fill contiguous slices of the
149hash table makes a good collision resolution strategy crucial. Taking only
150the last i bits of the hash code is also vulnerable: for example, consider
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151the list [i << 16 for i in range(20000)] as a set of keys. Since ints are
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000152their own hash codes, and this fits in a dict of size 2**15, the last 15 bits
153 of every hash code are all 0: they *all* map to the same table index.
Tim Peters15d49292001-05-27 07:39:22 +0000154
Tim Peterseb28ef22001-06-02 05:27:19 +0000155But catering to unusual cases should not slow the usual ones, so we just take
156the last i bits anyway. It's up to collision resolution to do the rest. If
157we *usually* find the key we're looking for on the first try (and, it turns
158out, we usually do -- the table load factor is kept under 2/3, so the odds
159are solidly in our favor), then it makes best sense to keep the initial index
160computation dirt cheap.
Tim Peters15d49292001-05-27 07:39:22 +0000161
Tim Peterseb28ef22001-06-02 05:27:19 +0000162The first half of collision resolution is to visit table indices via this
163recurrence:
Tim Peters15d49292001-05-27 07:39:22 +0000164
Tim Peterseb28ef22001-06-02 05:27:19 +0000165 j = ((5*j) + 1) mod 2**i
Tim Peters15d49292001-05-27 07:39:22 +0000166
Tim Peterseb28ef22001-06-02 05:27:19 +0000167For any initial j in range(2**i), repeating that 2**i times generates each
168int in range(2**i) exactly once (see any text on random-number generation for
169proof). By itself, this doesn't help much: like linear probing (setting
170j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
171order. This would be bad, except that's not the only thing we do, and it's
172actually *good* in the common cases where hash keys are consecutive. In an
173example that's really too small to make this entirely clear, for a table of
174size 2**3 the order of indices is:
Tim Peters15d49292001-05-27 07:39:22 +0000175
Tim Peterseb28ef22001-06-02 05:27:19 +0000176 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
177
178If two things come in at index 5, the first place we look after is index 2,
179not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
180Linear probing is deadly in this case because there the fixed probe order
181is the *same* as the order consecutive keys are likely to arrive. But it's
182extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
183and certain that consecutive hash codes do not.
184
185The other half of the strategy is to get the other bits of the hash code
186into play. This is done by initializing a (unsigned) vrbl "perturb" to the
187full hash code, and changing the recurrence to:
188
Tim Peterseb28ef22001-06-02 05:27:19 +0000189 perturb >>= PERTURB_SHIFT;
INADA Naoki267941c2016-10-06 15:19:07 +0900190 j = (5*j) + 1 + perturb;
Tim Peterseb28ef22001-06-02 05:27:19 +0000191 use j % 2**i as the next table index;
192
193Now the probe sequence depends (eventually) on every bit in the hash code,
194and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
195because it quickly magnifies small differences in the bits that didn't affect
196the initial index. Note that because perturb is unsigned, if the recurrence
197is executed often enough perturb eventually becomes and remains 0. At that
198point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
199that's certain to find an empty slot eventually (since it generates every int
200in range(2**i), and we make sure there's always at least one empty slot).
201
202Selecting a good value for PERTURB_SHIFT is a balancing act. You want it
203small so that the high bits of the hash code continue to affect the probe
204sequence across iterations; but you want it large so that in really bad cases
205the high-order hash bits have an effect on early iterations. 5 was "the
206best" in minimizing total collisions across experiments Tim Peters ran (on
207both normal and pathological cases), but 4 and 6 weren't significantly worse.
208
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000209Historical: Reimer Behrends contributed the idea of using a polynomial-based
Tim Peterseb28ef22001-06-02 05:27:19 +0000210approach, using repeated multiplication by x in GF(2**n) where an irreducible
211polynomial for each table size was chosen such that x was a primitive root.
212Christian Tismer later extended that to use division by x instead, as an
213efficient way to get the high bits of the hash code into play. This scheme
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000214also gave excellent collision statistics, but was more expensive: two
215if-tests were required inside the loop; computing "the next" index took about
216the same number of operations but without as much potential parallelism
217(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
218above, and then shifting perturb can be done while the table index is being
219masked); and the PyDictObject struct required a member to hold the table's
220polynomial. In Tim's experiments the current scheme ran faster, produced
221equally good collision statistics, needed less code & used less memory.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000222
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000223*/
Tim Petersdea48ec2001-05-22 20:40:22 +0000224
Fred Drake1bff34a2000-08-31 19:31:38 +0000225/* forward declarations */
Victor Stinner742da042016-09-07 17:40:12 -0700226static Py_ssize_t lookdict(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900227 Py_hash_t hash, PyObject **value_addr);
Victor Stinner742da042016-09-07 17:40:12 -0700228static Py_ssize_t lookdict_unicode(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900229 Py_hash_t hash, PyObject **value_addr);
Victor Stinner742da042016-09-07 17:40:12 -0700230static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400231lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900232 Py_hash_t hash, PyObject **value_addr);
Victor Stinner742da042016-09-07 17:40:12 -0700233static Py_ssize_t lookdict_split(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900234 Py_hash_t hash, PyObject **value_addr);
Fred Drake1bff34a2000-08-31 19:31:38 +0000235
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400236static int dictresize(PyDictObject *mp, Py_ssize_t minused);
Tim Petersdea48ec2001-05-22 20:40:22 +0000237
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{
442 PyDictKeysObject *keys = mp->ma_keys;
443 int splitted = _PyDict_HasSplitTable(mp);
444 Py_ssize_t usable = USABLE_FRACTION(keys->dk_size);
445#ifdef DEBUG_PYDICT
446 PyDictKeyEntry *entries = DK_ENTRIES(keys);
447 Py_ssize_t i;
448#endif
449
450 assert(0 <= mp->ma_used && mp->ma_used <= usable);
451 assert(IS_POWER_OF_2(keys->dk_size));
452 assert(0 <= keys->dk_usable
453 && keys->dk_usable <= usable);
454 assert(0 <= keys->dk_nentries
455 && keys->dk_nentries <= usable);
456 assert(keys->dk_usable + keys->dk_nentries <= usable);
457
458 if (!splitted) {
459 /* combined table */
460 assert(keys->dk_refcnt == 1);
461 }
462
463#ifdef DEBUG_PYDICT
464 for (i=0; i < keys->dk_size; i++) {
465 Py_ssize_t ix = dk_get_index(keys, i);
466 assert(DKIX_DUMMY <= ix && ix <= usable);
467 }
468
469 for (i=0; i < usable; i++) {
470 PyDictKeyEntry *entry = &entries[i];
471 PyObject *key = entry->me_key;
472
473 if (key != NULL) {
474 if (PyUnicode_CheckExact(key)) {
475 Py_hash_t hash = ((PyASCIIObject *)key)->hash;
476 assert(hash != -1);
477 assert(entry->me_hash == hash);
478 }
479 else {
480 /* test_dict fails if PyObject_Hash() is called again */
481 assert(entry->me_hash != -1);
482 }
483 if (!splitted) {
484 assert(entry->me_value != NULL);
485 }
486 }
487
488 if (splitted) {
489 assert(entry->me_value == NULL);
490 }
491 }
492
493 if (splitted) {
494 /* splitted table */
495 for (i=0; i < mp->ma_used; i++) {
496 assert(mp->ma_values[i] != NULL);
497 }
498 }
499#endif
500
501 return 1;
502}
503#endif
504
505
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400506static PyDictKeysObject *new_keys_object(Py_ssize_t size)
507{
508 PyDictKeysObject *dk;
Victor Stinner742da042016-09-07 17:40:12 -0700509 Py_ssize_t es, usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400510
Victor Stinner742da042016-09-07 17:40:12 -0700511 assert(size >= PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400512 assert(IS_POWER_OF_2(size));
Victor Stinner742da042016-09-07 17:40:12 -0700513
514 usable = USABLE_FRACTION(size);
515 if (size <= 0xff) {
516 es = 1;
517 }
518 else if (size <= 0xffff) {
519 es = 2;
520 }
521#if SIZEOF_VOID_P > 4
522 else if (size <= 0xffffffff) {
523 es = 4;
524 }
525#endif
526 else {
527 es = sizeof(Py_ssize_t);
528 }
529
530 if (size == PyDict_MINSIZE && numfreekeys > 0) {
531 dk = keys_free_list[--numfreekeys];
532 }
533 else {
Victor Stinner98ee9d52016-09-08 09:33:56 -0700534 dk = PyObject_MALLOC(sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -0700535 + es * size
536 + sizeof(PyDictKeyEntry) * usable);
Victor Stinner742da042016-09-07 17:40:12 -0700537 if (dk == NULL) {
538 PyErr_NoMemory();
539 return NULL;
540 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400541 }
Antoine Pitrou2d169b22012-05-12 23:43:44 +0200542 DK_DEBUG_INCREF dk->dk_refcnt = 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400543 dk->dk_size = size;
Victor Stinner742da042016-09-07 17:40:12 -0700544 dk->dk_usable = usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400545 dk->dk_lookup = lookdict_unicode_nodummy;
Victor Stinner742da042016-09-07 17:40:12 -0700546 dk->dk_nentries = 0;
Gregory P. Smith397f1b22018-04-19 22:41:19 -0700547 memset(&dk->dk_indices[0], 0xff, es * size);
Victor Stinner742da042016-09-07 17:40:12 -0700548 memset(DK_ENTRIES(dk), 0, sizeof(PyDictKeyEntry) * usable);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400549 return dk;
550}
551
552static void
553free_keys_object(PyDictKeysObject *keys)
554{
Victor Stinner742da042016-09-07 17:40:12 -0700555 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400556 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -0700557 for (i = 0, n = keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400558 Py_XDECREF(entries[i].me_key);
559 Py_XDECREF(entries[i].me_value);
560 }
Victor Stinner742da042016-09-07 17:40:12 -0700561 if (keys->dk_size == PyDict_MINSIZE && numfreekeys < PyDict_MAXFREELIST) {
562 keys_free_list[numfreekeys++] = keys;
563 return;
564 }
Raymond Hettingerce5179f2016-01-31 08:56:21 -0800565 PyObject_FREE(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400566}
567
568#define new_values(size) PyMem_NEW(PyObject *, size)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400569#define free_values(values) PyMem_FREE(values)
570
571/* Consumes a reference to the keys object */
572static PyObject *
573new_dict(PyDictKeysObject *keys, PyObject **values)
574{
575 PyDictObject *mp;
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200576 assert(keys != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 if (numfree) {
578 mp = free_list[--numfree];
579 assert (mp != NULL);
580 assert (Py_TYPE(mp) == &PyDict_Type);
581 _Py_NewReference((PyObject *)mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400583 else {
584 mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
585 if (mp == NULL) {
586 DK_DECREF(keys);
587 free_values(values);
588 return NULL;
589 }
590 }
591 mp->ma_keys = keys;
592 mp->ma_values = values;
593 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -0700594 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner611b0fa2016-09-14 15:02:01 +0200595 assert(_PyDict_CheckConsistency(mp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000597}
598
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400599/* Consumes a reference to the keys object */
600static PyObject *
601new_dict_with_shared_keys(PyDictKeysObject *keys)
602{
603 PyObject **values;
604 Py_ssize_t i, size;
605
Victor Stinner742da042016-09-07 17:40:12 -0700606 size = USABLE_FRACTION(DK_SIZE(keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400607 values = new_values(size);
608 if (values == NULL) {
609 DK_DECREF(keys);
610 return PyErr_NoMemory();
611 }
612 for (i = 0; i < size; i++) {
613 values[i] = NULL;
614 }
615 return new_dict(keys, values);
616}
617
Yury Selivanovb0a7a032018-01-22 11:54:41 -0500618
619static PyObject *
620clone_combined_dict(PyDictObject *orig)
621{
622 assert(PyDict_CheckExact(orig));
623 assert(orig->ma_values == NULL);
624 assert(orig->ma_keys->dk_refcnt == 1);
625
626 Py_ssize_t keys_size = _PyDict_KeysSize(orig->ma_keys);
627 PyDictKeysObject *keys = PyObject_Malloc(keys_size);
628 if (keys == NULL) {
629 PyErr_NoMemory();
630 return NULL;
631 }
632
633 memcpy(keys, orig->ma_keys, keys_size);
634
635 /* After copying key/value pairs, we need to incref all
636 keys and values and they are about to be co-owned by a
637 new dict object. */
638 PyDictKeyEntry *ep0 = DK_ENTRIES(keys);
639 Py_ssize_t n = keys->dk_nentries;
640 for (Py_ssize_t i = 0; i < n; i++) {
641 PyDictKeyEntry *entry = &ep0[i];
642 PyObject *value = entry->me_value;
643 if (value != NULL) {
644 Py_INCREF(value);
645 Py_INCREF(entry->me_key);
646 }
647 }
648
649 PyDictObject *new = (PyDictObject *)new_dict(keys, NULL);
650 if (new == NULL) {
651 /* In case of an error, `new_dict()` takes care of
652 cleaning up `keys`. */
653 return NULL;
654 }
655 new->ma_used = orig->ma_used;
656 assert(_PyDict_CheckConsistency(new));
657 if (_PyObject_GC_IS_TRACKED(orig)) {
658 /* Maintain tracking. */
659 _PyObject_GC_TRACK(new);
660 }
Yury Selivanov0b752282018-07-06 12:20:07 -0400661
662 /* Since we copied the keys table we now have an extra reference
663 in the system. Manually call _Py_INC_REFTOTAL to signal that
664 we have it now; calling DK_INCREF would be an error as
665 keys->dk_refcnt is already set to 1 (after memcpy). */
666 _Py_INC_REFTOTAL;
667
Yury Selivanovb0a7a032018-01-22 11:54:41 -0500668 return (PyObject *)new;
669}
670
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400671PyObject *
672PyDict_New(void)
673{
Victor Stinner742da042016-09-07 17:40:12 -0700674 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200675 if (keys == NULL)
676 return NULL;
677 return new_dict(keys, NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400678}
679
Victor Stinner742da042016-09-07 17:40:12 -0700680/* Search index of hash table from offset of entry table */
681static Py_ssize_t
682lookdict_index(PyDictKeysObject *k, Py_hash_t hash, Py_ssize_t index)
683{
Victor Stinner742da042016-09-07 17:40:12 -0700684 size_t mask = DK_MASK(k);
INADA Naoki073ae482017-06-23 15:22:50 +0900685 size_t perturb = (size_t)hash;
686 size_t i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700687
INADA Naoki073ae482017-06-23 15:22:50 +0900688 for (;;) {
689 Py_ssize_t ix = dk_get_index(k, i);
Victor Stinner742da042016-09-07 17:40:12 -0700690 if (ix == index) {
691 return i;
692 }
693 if (ix == DKIX_EMPTY) {
694 return DKIX_EMPTY;
695 }
INADA Naoki073ae482017-06-23 15:22:50 +0900696 perturb >>= PERTURB_SHIFT;
697 i = mask & (i*5 + perturb + 1);
Victor Stinner742da042016-09-07 17:40:12 -0700698 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700699 Py_UNREACHABLE();
Victor Stinner742da042016-09-07 17:40:12 -0700700}
701
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000702/*
703The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000704This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000705Open addressing is preferred over chaining since the link overhead for
706chaining would be substantial (100% with typical malloc overhead).
707
Tim Peterseb28ef22001-06-02 05:27:19 +0000708The initial probe index is computed as hash mod the table size. Subsequent
709probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000710
711All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000712
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000713The details in this version are due to Tim Peters, building on many past
Tim Peterseb28ef22001-06-02 05:27:19 +0000714contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000715Christian Tismer.
Fred Drake1bff34a2000-08-31 19:31:38 +0000716
Victor Stinner742da042016-09-07 17:40:12 -0700717lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a
Victor Stinnera4348cc2016-09-08 12:01:25 -0700718comparison raises an exception.
Guido van Rossum89d8c602007-09-18 17:26:56 +0000719lookdict_unicode() below is specialized to string keys, comparison of which can
INADA Naoki1b8df102017-02-20 22:48:10 +0900720never raise an exception; that function can never return DKIX_ERROR when key
721is string. Otherwise, it falls back to lookdict().
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400722lookdict_unicode_nodummy is further specialized for string keys that cannot be
723the <dummy> value.
INADA Naoki778928b2017-08-03 23:45:15 +0900724For both, when the key isn't found a DKIX_EMPTY is returned.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000725*/
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100726static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400727lookdict(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900728 Py_hash_t hash, PyObject **value_addr)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000729{
INADA Naoki778928b2017-08-03 23:45:15 +0900730 size_t i, mask, perturb;
Victor Stinner742da042016-09-07 17:40:12 -0700731 PyDictKeysObject *dk;
INADA Naoki778928b2017-08-03 23:45:15 +0900732 PyDictKeyEntry *ep0;
Tim Peterseb28ef22001-06-02 05:27:19 +0000733
Antoine Pitrou9a234902012-05-13 20:48:01 +0200734top:
Victor Stinner742da042016-09-07 17:40:12 -0700735 dk = mp->ma_keys;
Victor Stinner742da042016-09-07 17:40:12 -0700736 ep0 = DK_ENTRIES(dk);
INADA Naoki778928b2017-08-03 23:45:15 +0900737 mask = DK_MASK(dk);
738 perturb = hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700740
INADA Naoki778928b2017-08-03 23:45:15 +0900741 for (;;) {
742 Py_ssize_t ix = dk_get_index(dk, i);
Victor Stinner742da042016-09-07 17:40:12 -0700743 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700744 *value_addr = NULL;
745 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400746 }
INADA Naoki778928b2017-08-03 23:45:15 +0900747 if (ix >= 0) {
748 PyDictKeyEntry *ep = &ep0[ix];
749 assert(ep->me_key != NULL);
750 if (ep->me_key == key) {
751 *value_addr = ep->me_value;
752 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700753 }
INADA Naoki778928b2017-08-03 23:45:15 +0900754 if (ep->me_hash == hash) {
755 PyObject *startkey = ep->me_key;
756 Py_INCREF(startkey);
757 int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
758 Py_DECREF(startkey);
759 if (cmp < 0) {
760 *value_addr = NULL;
761 return DKIX_ERROR;
762 }
763 if (dk == mp->ma_keys && ep->me_key == startkey) {
764 if (cmp > 0) {
765 *value_addr = ep->me_value;
766 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700767 }
INADA Naoki778928b2017-08-03 23:45:15 +0900768 }
769 else {
770 /* The dict was mutated, restart */
771 goto top;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400772 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 }
INADA Naoki778928b2017-08-03 23:45:15 +0900775 perturb >>= PERTURB_SHIFT;
776 i = (i*5 + perturb + 1) & mask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700778 Py_UNREACHABLE();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000779}
780
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400781/* Specialized version for string-only keys */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100782static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400783lookdict_unicode(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900784 Py_hash_t hash, PyObject **value_addr)
Fred Drake1bff34a2000-08-31 19:31:38 +0000785{
Victor Stinner742da042016-09-07 17:40:12 -0700786 assert(mp->ma_values == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 /* Make sure this function doesn't have to handle non-unicode keys,
788 including subclasses of str; e.g., one reason to subclass
789 unicodes is to override __eq__, and for speed we don't cater to
790 that here. */
791 if (!PyUnicode_CheckExact(key)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400792 mp->ma_keys->dk_lookup = lookdict;
INADA Naoki778928b2017-08-03 23:45:15 +0900793 return lookdict(mp, key, hash, value_addr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 }
Tim Peters15d49292001-05-27 07:39:22 +0000795
INADA Naoki778928b2017-08-03 23:45:15 +0900796 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
797 size_t mask = DK_MASK(mp->ma_keys);
798 size_t perturb = (size_t)hash;
799 size_t i = (size_t)hash & mask;
800
801 for (;;) {
802 Py_ssize_t ix = dk_get_index(mp->ma_keys, i);
Victor Stinner742da042016-09-07 17:40:12 -0700803 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700804 *value_addr = NULL;
805 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400806 }
INADA Naoki778928b2017-08-03 23:45:15 +0900807 if (ix >= 0) {
808 PyDictKeyEntry *ep = &ep0[ix];
809 assert(ep->me_key != NULL);
810 assert(PyUnicode_CheckExact(ep->me_key));
811 if (ep->me_key == key ||
812 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
813 *value_addr = ep->me_value;
814 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700815 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400816 }
INADA Naoki778928b2017-08-03 23:45:15 +0900817 perturb >>= PERTURB_SHIFT;
818 i = mask & (i*5 + perturb + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700820 Py_UNREACHABLE();
Fred Drake1bff34a2000-08-31 19:31:38 +0000821}
822
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400823/* Faster version of lookdict_unicode when it is known that no <dummy> keys
824 * will be present. */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100825static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400826lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900827 Py_hash_t hash, PyObject **value_addr)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400828{
Victor Stinner742da042016-09-07 17:40:12 -0700829 assert(mp->ma_values == NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400830 /* Make sure this function doesn't have to handle non-unicode keys,
831 including subclasses of str; e.g., one reason to subclass
832 unicodes is to override __eq__, and for speed we don't cater to
833 that here. */
834 if (!PyUnicode_CheckExact(key)) {
835 mp->ma_keys->dk_lookup = lookdict;
INADA Naoki778928b2017-08-03 23:45:15 +0900836 return lookdict(mp, key, hash, value_addr);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400837 }
INADA Naoki778928b2017-08-03 23:45:15 +0900838
839 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
840 size_t mask = DK_MASK(mp->ma_keys);
841 size_t perturb = (size_t)hash;
842 size_t i = (size_t)hash & mask;
843
844 for (;;) {
845 Py_ssize_t ix = dk_get_index(mp->ma_keys, i);
Victor Stinner742da042016-09-07 17:40:12 -0700846 assert (ix != DKIX_DUMMY);
847 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700848 *value_addr = NULL;
849 return DKIX_EMPTY;
850 }
INADA Naoki778928b2017-08-03 23:45:15 +0900851 PyDictKeyEntry *ep = &ep0[ix];
852 assert(ep->me_key != NULL);
853 assert(PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700854 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400855 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
INADA Naokiba609772016-12-07 20:41:42 +0900856 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700857 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400858 }
INADA Naoki778928b2017-08-03 23:45:15 +0900859 perturb >>= PERTURB_SHIFT;
860 i = mask & (i*5 + perturb + 1);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400861 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700862 Py_UNREACHABLE();
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400863}
864
865/* Version of lookdict for split tables.
866 * All split tables and only split tables use this lookup function.
867 * Split tables only contain unicode keys and no dummy keys,
868 * so algorithm is the same as lookdict_unicode_nodummy.
869 */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100870static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400871lookdict_split(PyDictObject *mp, PyObject *key,
INADA Naoki778928b2017-08-03 23:45:15 +0900872 Py_hash_t hash, PyObject **value_addr)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400873{
Victor Stinner742da042016-09-07 17:40:12 -0700874 /* mp must split table */
875 assert(mp->ma_values != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400876 if (!PyUnicode_CheckExact(key)) {
INADA Naoki778928b2017-08-03 23:45:15 +0900877 Py_ssize_t ix = lookdict(mp, key, hash, value_addr);
Victor Stinner742da042016-09-07 17:40:12 -0700878 if (ix >= 0) {
INADA Naokiba609772016-12-07 20:41:42 +0900879 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700880 }
881 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400882 }
Victor Stinner742da042016-09-07 17:40:12 -0700883
INADA Naoki778928b2017-08-03 23:45:15 +0900884 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
885 size_t mask = DK_MASK(mp->ma_keys);
886 size_t perturb = (size_t)hash;
887 size_t i = (size_t)hash & mask;
888
889 for (;;) {
890 Py_ssize_t ix = dk_get_index(mp->ma_keys, i);
891 assert (ix != DKIX_DUMMY);
Victor Stinner742da042016-09-07 17:40:12 -0700892 if (ix == DKIX_EMPTY) {
Victor Stinner742da042016-09-07 17:40:12 -0700893 *value_addr = NULL;
894 return DKIX_EMPTY;
895 }
INADA Naoki778928b2017-08-03 23:45:15 +0900896 PyDictKeyEntry *ep = &ep0[ix];
897 assert(ep->me_key != NULL);
898 assert(PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700899 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400900 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
INADA Naokiba609772016-12-07 20:41:42 +0900901 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700902 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400903 }
INADA Naoki778928b2017-08-03 23:45:15 +0900904 perturb >>= PERTURB_SHIFT;
905 i = mask & (i*5 + perturb + 1);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400906 }
Barry Warsawb2e57942017-09-14 18:13:16 -0700907 Py_UNREACHABLE();
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400908}
909
Benjamin Petersonfb886362010-04-24 18:21:17 +0000910int
911_PyDict_HasOnlyStringKeys(PyObject *dict)
912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 Py_ssize_t pos = 0;
914 PyObject *key, *value;
Benjamin Petersonf6096542010-11-17 22:33:12 +0000915 assert(PyDict_Check(dict));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 /* Shortcut */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400917 if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 return 1;
919 while (PyDict_Next(dict, &pos, &key, &value))
920 if (!PyUnicode_Check(key))
921 return 0;
922 return 1;
Benjamin Petersonfb886362010-04-24 18:21:17 +0000923}
924
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000925#define MAINTAIN_TRACKING(mp, key, value) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 do { \
927 if (!_PyObject_GC_IS_TRACKED(mp)) { \
928 if (_PyObject_GC_MAY_BE_TRACKED(key) || \
929 _PyObject_GC_MAY_BE_TRACKED(value)) { \
930 _PyObject_GC_TRACK(mp); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 } \
932 } \
933 } while(0)
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000934
935void
936_PyDict_MaybeUntrack(PyObject *op)
937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 PyDictObject *mp;
939 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -0700940 Py_ssize_t i, numentries;
941 PyDictKeyEntry *ep0;
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
944 return;
945
946 mp = (PyDictObject *) op;
Victor Stinner742da042016-09-07 17:40:12 -0700947 ep0 = DK_ENTRIES(mp->ma_keys);
948 numentries = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400949 if (_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -0700950 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400951 if ((value = mp->ma_values[i]) == NULL)
952 continue;
953 if (_PyObject_GC_MAY_BE_TRACKED(value)) {
Victor Stinner742da042016-09-07 17:40:12 -0700954 assert(!_PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400955 return;
956 }
957 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400959 else {
Victor Stinner742da042016-09-07 17:40:12 -0700960 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400961 if ((value = ep0[i].me_value) == NULL)
962 continue;
963 if (_PyObject_GC_MAY_BE_TRACKED(value) ||
964 _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
965 return;
966 }
967 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 _PyObject_GC_UNTRACK(op);
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000969}
970
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400971/* Internal function to find slot for an item from its hash
Victor Stinner3c336c52016-09-12 14:17:40 +0200972 when it is known that the key is not present in the dict.
973
974 The dict must be combined. */
INADA Naokiba609772016-12-07 20:41:42 +0900975static Py_ssize_t
INADA Naoki778928b2017-08-03 23:45:15 +0900976find_empty_slot(PyDictKeysObject *keys, Py_hash_t hash)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000977{
INADA Naoki778928b2017-08-03 23:45:15 +0900978 assert(keys != NULL);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000979
INADA Naoki778928b2017-08-03 23:45:15 +0900980 const size_t mask = DK_MASK(keys);
981 size_t i = hash & mask;
982 Py_ssize_t ix = dk_get_index(keys, i);
983 for (size_t perturb = hash; ix >= 0;) {
INADA Naoki267941c2016-10-06 15:19:07 +0900984 perturb >>= PERTURB_SHIFT;
INADA Naoki778928b2017-08-03 23:45:15 +0900985 i = (i*5 + perturb + 1) & mask;
986 ix = dk_get_index(keys, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 }
INADA Naoki778928b2017-08-03 23:45:15 +0900988 return i;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000989}
990
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400991static int
992insertion_resize(PyDictObject *mp)
993{
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700994 return dictresize(mp, GROWTH_RATE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400995}
Antoine Pitroue965d972012-02-27 00:45:12 +0100996
997/*
998Internal routine to insert a new item into the table.
999Used both by the internal resize routine and by the public insert routine.
Antoine Pitroue965d972012-02-27 00:45:12 +01001000Returns -1 if an error occurred, or 0 on success.
1001*/
1002static int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001003insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001004{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001005 PyObject *old_value;
INADA Naokiba609772016-12-07 20:41:42 +09001006 PyDictKeyEntry *ep;
Antoine Pitroue965d972012-02-27 00:45:12 +01001007
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001008 Py_INCREF(key);
1009 Py_INCREF(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001010 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
1011 if (insertion_resize(mp) < 0)
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001012 goto Fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001013 }
1014
INADA Naoki778928b2017-08-03 23:45:15 +09001015 Py_ssize_t ix = mp->ma_keys->dk_lookup(mp, key, hash, &old_value);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001016 if (ix == DKIX_ERROR)
1017 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001018
Antoine Pitroud6967322014-10-18 00:35:00 +02001019 assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001020 MAINTAIN_TRACKING(mp, key, value);
Victor Stinner742da042016-09-07 17:40:12 -07001021
1022 /* When insertion order is different from shared key, we can't share
1023 * the key anymore. Convert this instance to combine table.
1024 */
1025 if (_PyDict_HasSplitTable(mp) &&
INADA Naokiba609772016-12-07 20:41:42 +09001026 ((ix >= 0 && old_value == NULL && mp->ma_used != ix) ||
Victor Stinner742da042016-09-07 17:40:12 -07001027 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001028 if (insertion_resize(mp) < 0)
1029 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001030 ix = DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001031 }
Victor Stinner742da042016-09-07 17:40:12 -07001032
1033 if (ix == DKIX_EMPTY) {
1034 /* Insert into new slot. */
INADA Naokiba609772016-12-07 20:41:42 +09001035 assert(old_value == NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001036 if (mp->ma_keys->dk_usable <= 0) {
1037 /* Need to resize. */
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001038 if (insertion_resize(mp) < 0)
1039 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001040 }
INADA Naoki778928b2017-08-03 23:45:15 +09001041 Py_ssize_t hashpos = find_empty_slot(mp->ma_keys, hash);
INADA Naokiba609772016-12-07 20:41:42 +09001042 ep = &DK_ENTRIES(mp->ma_keys)[mp->ma_keys->dk_nentries];
Victor Stinner742da042016-09-07 17:40:12 -07001043 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
Victor Stinner742da042016-09-07 17:40:12 -07001044 ep->me_key = key;
1045 ep->me_hash = hash;
1046 if (mp->ma_values) {
1047 assert (mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
1048 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001049 }
1050 else {
Victor Stinner742da042016-09-07 17:40:12 -07001051 ep->me_value = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001052 }
1053 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001054 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07001055 mp->ma_keys->dk_usable--;
1056 mp->ma_keys->dk_nentries++;
1057 assert(mp->ma_keys->dk_usable >= 0);
Victor Stinner611b0fa2016-09-14 15:02:01 +02001058 assert(_PyDict_CheckConsistency(mp));
Victor Stinner742da042016-09-07 17:40:12 -07001059 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001060 }
Victor Stinner742da042016-09-07 17:40:12 -07001061
INADA Naokiba609772016-12-07 20:41:42 +09001062 if (_PyDict_HasSplitTable(mp)) {
1063 mp->ma_values[ix] = value;
1064 if (old_value == NULL) {
1065 /* pending state */
1066 assert(ix == mp->ma_used);
1067 mp->ma_used++;
1068 }
1069 }
1070 else {
1071 assert(old_value != NULL);
1072 DK_ENTRIES(mp->ma_keys)[ix].me_value = value;
Victor Stinner742da042016-09-07 17:40:12 -07001073 }
1074
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001075 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naokiba609772016-12-07 20:41:42 +09001076 Py_XDECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
Victor Stinner611b0fa2016-09-14 15:02:01 +02001077 assert(_PyDict_CheckConsistency(mp));
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001078 Py_DECREF(key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001079 return 0;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001080
1081Fail:
1082 Py_DECREF(value);
1083 Py_DECREF(key);
1084 return -1;
Antoine Pitroue965d972012-02-27 00:45:12 +01001085}
1086
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001087/*
luzpaza5293b42017-11-05 07:37:50 -06001088Internal routine used by dictresize() to build a hashtable of entries.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001089*/
1090static void
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001091build_indices(PyDictKeysObject *keys, PyDictKeyEntry *ep, Py_ssize_t n)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001092{
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001093 size_t mask = (size_t)DK_SIZE(keys) - 1;
1094 for (Py_ssize_t ix = 0; ix != n; ix++, ep++) {
1095 Py_hash_t hash = ep->me_hash;
1096 size_t i = hash & mask;
1097 for (size_t perturb = hash; dk_get_index(keys, i) != DKIX_EMPTY;) {
1098 perturb >>= PERTURB_SHIFT;
INADA Naoki870c2862017-06-24 09:03:19 +09001099 i = mask & (i*5 + perturb + 1);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001100 }
1101 dk_set_index(keys, i, ix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001103}
1104
1105/*
1106Restructure the table by allocating a new table and reinserting all
1107items again. When entries have been deleted, the new table may
1108actually be smaller than the old one.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001109If a table is split (its keys and hashes are shared, its values are not),
1110then the values are temporarily copied into the table, it is resized as
1111a combined table, then the me_value slots in the old table are NULLed out.
1112After resizing a table is always combined,
1113but can be resplit by make_keys_shared().
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001114*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001115static int
Victor Stinner3d3f2642016-12-15 17:21:23 +01001116dictresize(PyDictObject *mp, Py_ssize_t minsize)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001117{
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001118 Py_ssize_t newsize, numentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001119 PyDictKeysObject *oldkeys;
1120 PyObject **oldvalues;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001121 PyDictKeyEntry *oldentries, *newentries;
Tim Peters91a364d2001-05-19 07:04:38 +00001122
Victor Stinner742da042016-09-07 17:40:12 -07001123 /* Find the smallest table size > minused. */
1124 for (newsize = PyDict_MINSIZE;
Victor Stinner3d3f2642016-12-15 17:21:23 +01001125 newsize < minsize && newsize > 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 newsize <<= 1)
1127 ;
1128 if (newsize <= 0) {
1129 PyErr_NoMemory();
1130 return -1;
1131 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001132
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001133 oldkeys = mp->ma_keys;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001134
1135 /* NOTE: Current odict checks mp->ma_keys to detect resize happen.
1136 * So we can't reuse oldkeys even if oldkeys->dk_size == newsize.
1137 * TODO: Try reusing oldkeys when reimplement odict.
1138 */
1139
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001140 /* Allocate a new table. */
1141 mp->ma_keys = new_keys_object(newsize);
1142 if (mp->ma_keys == NULL) {
1143 mp->ma_keys = oldkeys;
1144 return -1;
1145 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01001146 // New table must be large enough.
1147 assert(mp->ma_keys->dk_usable >= mp->ma_used);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001148 if (oldkeys->dk_lookup == lookdict)
1149 mp->ma_keys->dk_lookup = lookdict;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001150
1151 numentries = mp->ma_used;
1152 oldentries = DK_ENTRIES(oldkeys);
1153 newentries = DK_ENTRIES(mp->ma_keys);
1154 oldvalues = mp->ma_values;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001155 if (oldvalues != NULL) {
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001156 /* Convert split table into new combined table.
1157 * We must incref keys; we can transfer values.
1158 * Note that values of split table is always dense.
1159 */
1160 for (Py_ssize_t i = 0; i < numentries; i++) {
1161 assert(oldvalues[i] != NULL);
1162 PyDictKeyEntry *ep = &oldentries[i];
1163 PyObject *key = ep->me_key;
1164 Py_INCREF(key);
1165 newentries[i].me_key = key;
1166 newentries[i].me_hash = ep->me_hash;
1167 newentries[i].me_value = oldvalues[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001169
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001170 DK_DECREF(oldkeys);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001171 mp->ma_values = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001172 if (oldvalues != empty_values) {
1173 free_values(oldvalues);
1174 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001175 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001176 else { // combined table.
1177 if (oldkeys->dk_nentries == numentries) {
1178 memcpy(newentries, oldentries, numentries * sizeof(PyDictKeyEntry));
1179 }
1180 else {
1181 PyDictKeyEntry *ep = oldentries;
1182 for (Py_ssize_t i = 0; i < numentries; i++) {
1183 while (ep->me_value == NULL)
1184 ep++;
1185 newentries[i] = *ep++;
1186 }
1187 }
1188
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001189 assert(oldkeys->dk_lookup != lookdict_split);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001190 assert(oldkeys->dk_refcnt == 1);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001191 if (oldkeys->dk_size == PyDict_MINSIZE &&
1192 numfreekeys < PyDict_MAXFREELIST) {
1193 DK_DEBUG_DECREF keys_free_list[numfreekeys++] = oldkeys;
1194 }
1195 else {
1196 DK_DEBUG_DECREF PyObject_FREE(oldkeys);
1197 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001198 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001199
1200 build_indices(mp->ma_keys, newentries, numentries);
1201 mp->ma_keys->dk_usable -= numentries;
1202 mp->ma_keys->dk_nentries = numentries;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001204}
1205
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001206/* Returns NULL if unable to split table.
1207 * A NULL return does not necessarily indicate an error */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001208static PyDictKeysObject *
1209make_keys_shared(PyObject *op)
1210{
1211 Py_ssize_t i;
1212 Py_ssize_t size;
1213 PyDictObject *mp = (PyDictObject *)op;
1214
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001215 if (!PyDict_CheckExact(op))
1216 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001217 if (!_PyDict_HasSplitTable(mp)) {
1218 PyDictKeyEntry *ep0;
1219 PyObject **values;
1220 assert(mp->ma_keys->dk_refcnt == 1);
1221 if (mp->ma_keys->dk_lookup == lookdict) {
1222 return NULL;
1223 }
1224 else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
1225 /* Remove dummy keys */
1226 if (dictresize(mp, DK_SIZE(mp->ma_keys)))
1227 return NULL;
1228 }
1229 assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
1230 /* Copy values into a new array */
Victor Stinner742da042016-09-07 17:40:12 -07001231 ep0 = DK_ENTRIES(mp->ma_keys);
1232 size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001233 values = new_values(size);
1234 if (values == NULL) {
1235 PyErr_SetString(PyExc_MemoryError,
1236 "Not enough memory to allocate new values array");
1237 return NULL;
1238 }
1239 for (i = 0; i < size; i++) {
1240 values[i] = ep0[i].me_value;
1241 ep0[i].me_value = NULL;
1242 }
1243 mp->ma_keys->dk_lookup = lookdict_split;
1244 mp->ma_values = values;
1245 }
1246 DK_INCREF(mp->ma_keys);
1247 return mp->ma_keys;
1248}
Christian Heimes99170a52007-12-19 02:07:34 +00001249
1250PyObject *
1251_PyDict_NewPresized(Py_ssize_t minused)
1252{
INADA Naoki92c50ee2016-11-22 00:57:02 +09001253 const Py_ssize_t max_presize = 128 * 1024;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001254 Py_ssize_t newsize;
1255 PyDictKeysObject *new_keys;
INADA Naoki92c50ee2016-11-22 00:57:02 +09001256
1257 /* There are no strict guarantee that returned dict can contain minused
1258 * items without resize. So we create medium size dict instead of very
1259 * large dict or MemoryError.
1260 */
1261 if (minused > USABLE_FRACTION(max_presize)) {
1262 newsize = max_presize;
1263 }
1264 else {
1265 Py_ssize_t minsize = ESTIMATE_SIZE(minused);
1266 newsize = PyDict_MINSIZE;
1267 while (newsize < minsize) {
1268 newsize <<= 1;
1269 }
1270 }
1271 assert(IS_POWER_OF_2(newsize));
1272
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001273 new_keys = new_keys_object(newsize);
1274 if (new_keys == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001276 return new_dict(new_keys, NULL);
Christian Heimes99170a52007-12-19 02:07:34 +00001277}
1278
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001279/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
1280 * that may occur (originally dicts supported only string keys, and exceptions
1281 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001282 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001283 * (suppressed) occurred while computing the key's hash, or that some error
1284 * (suppressed) occurred when comparing keys in the dict's internal probe
1285 * sequence. A nasty example of the latter is when a Python-coded comparison
1286 * function hits a stack-depth error, which can cause this to return NULL
1287 * even if the key is present.
1288 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001289PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001290PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001291{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001292 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001293 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 PyDictObject *mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 PyThreadState *tstate;
INADA Naokiba609772016-12-07 20:41:42 +09001296 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 if (!PyDict_Check(op))
1299 return NULL;
1300 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001301 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 {
1303 hash = PyObject_Hash(key);
1304 if (hash == -1) {
1305 PyErr_Clear();
1306 return NULL;
1307 }
1308 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 /* We can arrive here with a NULL tstate during initialization: try
1311 running "python -Wi" for an example related to string interning.
1312 Let's just hope that no exception occurs then... This must be
1313 _PyThreadState_Current and not PyThreadState_GET() because in debug
1314 mode, the latter complains if tstate is NULL. */
Victor Stinner0cae6092016-11-11 01:43:56 +01001315 tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 if (tstate != NULL && tstate->curexc_type != NULL) {
1317 /* preserve the existing exception */
1318 PyObject *err_type, *err_value, *err_tb;
1319 PyErr_Fetch(&err_type, &err_value, &err_tb);
INADA Naoki778928b2017-08-03 23:45:15 +09001320 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 /* ignore errors */
1322 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001323 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 return NULL;
1325 }
1326 else {
INADA Naoki778928b2017-08-03 23:45:15 +09001327 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001328 if (ix < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 PyErr_Clear();
1330 return NULL;
1331 }
1332 }
INADA Naokiba609772016-12-07 20:41:42 +09001333 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001334}
1335
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001336/* Same as PyDict_GetItemWithError() but with hash supplied by caller.
1337 This returns NULL *with* an exception set if an exception occurred.
1338 It returns NULL *without* an exception set if the key wasn't present.
1339*/
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001340PyObject *
1341_PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1342{
Victor Stinner742da042016-09-07 17:40:12 -07001343 Py_ssize_t ix;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001344 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001345 PyObject *value;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001346
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001347 if (!PyDict_Check(op)) {
1348 PyErr_BadInternalCall();
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001349 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001350 }
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001351
INADA Naoki778928b2017-08-03 23:45:15 +09001352 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001353 if (ix < 0) {
1354 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001355 }
INADA Naokiba609772016-12-07 20:41:42 +09001356 return value;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001357}
1358
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001359/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
1360 This returns NULL *with* an exception set if an exception occurred.
1361 It returns NULL *without* an exception set if the key wasn't present.
1362*/
1363PyObject *
1364PyDict_GetItemWithError(PyObject *op, PyObject *key)
1365{
Victor Stinner742da042016-09-07 17:40:12 -07001366 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001367 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 PyDictObject*mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001369 PyObject *value;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 if (!PyDict_Check(op)) {
1372 PyErr_BadInternalCall();
1373 return NULL;
1374 }
1375 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001376 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 {
1378 hash = PyObject_Hash(key);
1379 if (hash == -1) {
1380 return NULL;
1381 }
1382 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001383
INADA Naoki778928b2017-08-03 23:45:15 +09001384 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001385 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001387 return value;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001388}
1389
Brett Cannonfd074152012-04-14 14:10:13 -04001390PyObject *
1391_PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
1392{
1393 PyObject *kv;
1394 kv = _PyUnicode_FromId(key); /* borrowed */
1395 if (kv == NULL)
1396 return NULL;
1397 return PyDict_GetItemWithError(dp, kv);
1398}
1399
Victor Stinnerb4efc962015-11-20 09:24:02 +01001400/* Fast version of global value lookup (LOAD_GLOBAL).
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001401 * Lookup in globals, then builtins.
Victor Stinnerb4efc962015-11-20 09:24:02 +01001402 *
1403 * Raise an exception and return NULL if an error occurred (ex: computing the
1404 * key hash failed, key comparison failed, ...). Return NULL if the key doesn't
1405 * exist. Return the value if the key exists.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001406 */
1407PyObject *
1408_PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001409{
Victor Stinner742da042016-09-07 17:40:12 -07001410 Py_ssize_t ix;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001411 Py_hash_t hash;
INADA Naokiba609772016-12-07 20:41:42 +09001412 PyObject *value;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001413
1414 if (!PyUnicode_CheckExact(key) ||
1415 (hash = ((PyASCIIObject *) key)->hash) == -1)
1416 {
1417 hash = PyObject_Hash(key);
1418 if (hash == -1)
1419 return NULL;
Antoine Pitroue965d972012-02-27 00:45:12 +01001420 }
Victor Stinnerb4efc962015-11-20 09:24:02 +01001421
1422 /* namespace 1: globals */
INADA Naoki778928b2017-08-03 23:45:15 +09001423 ix = globals->ma_keys->dk_lookup(globals, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001424 if (ix == DKIX_ERROR)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001425 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001426 if (ix != DKIX_EMPTY && value != NULL)
1427 return value;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001428
1429 /* namespace 2: builtins */
INADA Naoki778928b2017-08-03 23:45:15 +09001430 ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07001431 if (ix < 0)
Victor Stinnerb4efc962015-11-20 09:24:02 +01001432 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001433 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001434}
1435
Antoine Pitroue965d972012-02-27 00:45:12 +01001436/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
1437 * dictionary if it's merely replacing the value for an existing key.
1438 * This means that it's safe to loop over a dictionary with PyDict_Next()
1439 * and occasionally replace a value -- but you can't insert new keys or
1440 * remove them.
1441 */
1442int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001443PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001444{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001445 PyDictObject *mp;
1446 Py_hash_t hash;
Antoine Pitroue965d972012-02-27 00:45:12 +01001447 if (!PyDict_Check(op)) {
1448 PyErr_BadInternalCall();
1449 return -1;
1450 }
1451 assert(key);
1452 assert(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001453 mp = (PyDictObject *)op;
1454 if (!PyUnicode_CheckExact(key) ||
1455 (hash = ((PyASCIIObject *) key)->hash) == -1)
1456 {
Antoine Pitroue965d972012-02-27 00:45:12 +01001457 hash = PyObject_Hash(key);
1458 if (hash == -1)
1459 return -1;
1460 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001461
1462 /* insertdict() handles any resizing that might be necessary */
1463 return insertdict(mp, key, hash, value);
Antoine Pitroue965d972012-02-27 00:45:12 +01001464}
1465
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001466int
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001467_PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
1468 Py_hash_t hash)
1469{
1470 PyDictObject *mp;
1471
1472 if (!PyDict_Check(op)) {
1473 PyErr_BadInternalCall();
1474 return -1;
1475 }
1476 assert(key);
1477 assert(value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001478 assert(hash != -1);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001479 mp = (PyDictObject *)op;
1480
1481 /* insertdict() handles any resizing that might be necessary */
1482 return insertdict(mp, key, hash, value);
1483}
1484
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001485static int
INADA Naoki778928b2017-08-03 23:45:15 +09001486delitem_common(PyDictObject *mp, Py_hash_t hash, Py_ssize_t ix,
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001487 PyObject *old_value)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001488{
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001489 PyObject *old_key;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001490 PyDictKeyEntry *ep;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001491
INADA Naoki778928b2017-08-03 23:45:15 +09001492 Py_ssize_t hashpos = lookdict_index(mp->ma_keys, hash, ix);
1493 assert(hashpos >= 0);
1494
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001495 mp->ma_used--;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001496 mp->ma_version_tag = DICT_NEXT_VERSION();
1497 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1498 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1499 ENSURE_ALLOWS_DELETIONS(mp);
1500 old_key = ep->me_key;
1501 ep->me_key = NULL;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001502 ep->me_value = NULL;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001503 Py_DECREF(old_key);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001504 Py_DECREF(old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001505
1506 assert(_PyDict_CheckConsistency(mp));
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001507 return 0;
1508}
1509
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001510int
Tim Peters1f5871e2000-07-04 17:44:48 +00001511PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001512{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001513 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 assert(key);
1515 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001516 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 hash = PyObject_Hash(key);
1518 if (hash == -1)
1519 return -1;
1520 }
Victor Stinner742da042016-09-07 17:40:12 -07001521
1522 return _PyDict_DelItem_KnownHash(op, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001523}
1524
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001525int
1526_PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1527{
INADA Naoki778928b2017-08-03 23:45:15 +09001528 Py_ssize_t ix;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001529 PyDictObject *mp;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001530 PyObject *old_value;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001531
1532 if (!PyDict_Check(op)) {
1533 PyErr_BadInternalCall();
1534 return -1;
1535 }
1536 assert(key);
1537 assert(hash != -1);
1538 mp = (PyDictObject *)op;
INADA Naoki778928b2017-08-03 23:45:15 +09001539 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner742da042016-09-07 17:40:12 -07001540 if (ix == DKIX_ERROR)
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001541 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09001542 if (ix == DKIX_EMPTY || old_value == NULL) {
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001543 _PyErr_SetKeyError(key);
1544 return -1;
1545 }
Victor Stinner78601a32016-09-09 19:28:36 -07001546
1547 // Split table doesn't allow deletion. Combine it.
1548 if (_PyDict_HasSplitTable(mp)) {
1549 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1550 return -1;
1551 }
INADA Naoki778928b2017-08-03 23:45:15 +09001552 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner78601a32016-09-09 19:28:36 -07001553 assert(ix >= 0);
1554 }
1555
INADA Naoki778928b2017-08-03 23:45:15 +09001556 return delitem_common(mp, hash, ix, old_value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001557}
1558
Antoine Pitroud741ed42016-12-27 14:23:43 +01001559/* This function promises that the predicate -> deletion sequence is atomic
1560 * (i.e. protected by the GIL), assuming the predicate itself doesn't
1561 * release the GIL.
1562 */
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001563int
1564_PyDict_DelItemIf(PyObject *op, PyObject *key,
1565 int (*predicate)(PyObject *value))
1566{
Antoine Pitroud741ed42016-12-27 14:23:43 +01001567 Py_ssize_t hashpos, ix;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001568 PyDictObject *mp;
1569 Py_hash_t hash;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001570 PyObject *old_value;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001571 int res;
1572
1573 if (!PyDict_Check(op)) {
1574 PyErr_BadInternalCall();
1575 return -1;
1576 }
1577 assert(key);
1578 hash = PyObject_Hash(key);
1579 if (hash == -1)
1580 return -1;
1581 mp = (PyDictObject *)op;
INADA Naoki778928b2017-08-03 23:45:15 +09001582 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001583 if (ix == DKIX_ERROR)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001584 return -1;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001585 if (ix == DKIX_EMPTY || old_value == NULL) {
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001586 _PyErr_SetKeyError(key);
1587 return -1;
1588 }
Antoine Pitroud741ed42016-12-27 14:23:43 +01001589
1590 // Split table doesn't allow deletion. Combine it.
1591 if (_PyDict_HasSplitTable(mp)) {
1592 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1593 return -1;
1594 }
INADA Naoki778928b2017-08-03 23:45:15 +09001595 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001596 assert(ix >= 0);
1597 }
1598
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001599 res = predicate(old_value);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001600 if (res == -1)
1601 return -1;
INADA Naoki778928b2017-08-03 23:45:15 +09001602
1603 hashpos = lookdict_index(mp->ma_keys, hash, ix);
1604 assert(hashpos >= 0);
1605
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001606 if (res > 0)
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001607 return delitem_common(mp, hashpos, ix, old_value);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001608 else
1609 return 0;
1610}
1611
1612
Guido van Rossum25831651993-05-19 14:50:45 +00001613void
Tim Peters1f5871e2000-07-04 17:44:48 +00001614PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 PyDictObject *mp;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001617 PyDictKeysObject *oldkeys;
1618 PyObject **oldvalues;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 if (!PyDict_Check(op))
1622 return;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001623 mp = ((PyDictObject *)op);
1624 oldkeys = mp->ma_keys;
1625 oldvalues = mp->ma_values;
1626 if (oldvalues == empty_values)
1627 return;
1628 /* Empty the dict... */
1629 DK_INCREF(Py_EMPTY_KEYS);
1630 mp->ma_keys = Py_EMPTY_KEYS;
1631 mp->ma_values = empty_values;
1632 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001633 mp->ma_version_tag = DICT_NEXT_VERSION();
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001634 /* ...then clear the keys and values */
1635 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001636 n = oldkeys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001637 for (i = 0; i < n; i++)
1638 Py_CLEAR(oldvalues[i]);
1639 free_values(oldvalues);
1640 DK_DECREF(oldkeys);
1641 }
1642 else {
1643 assert(oldkeys->dk_refcnt == 1);
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001644 DK_DECREF(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001645 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02001646 assert(_PyDict_CheckConsistency(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001647}
1648
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001649/* Internal version of PyDict_Next that returns a hash value in addition
1650 * to the key and value.
1651 * Return 1 on success, return 0 when the reached the end of the dictionary
1652 * (or if op is not a dictionary)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001653 */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001654int
1655_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
1656 PyObject **pvalue, Py_hash_t *phash)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001657{
INADA Naokica2d8be2016-11-04 16:59:10 +09001658 Py_ssize_t i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001659 PyDictObject *mp;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001660 PyDictKeyEntry *entry_ptr;
1661 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001662
1663 if (!PyDict_Check(op))
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001664 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 mp = (PyDictObject *)op;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001666 i = *ppos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001667 if (mp->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09001668 if (i < 0 || i >= mp->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001669 return 0;
INADA Naokica2d8be2016-11-04 16:59:10 +09001670 /* values of split table is always dense */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001671 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
INADA Naokica2d8be2016-11-04 16:59:10 +09001672 value = mp->ma_values[i];
1673 assert(value != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001675 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09001676 Py_ssize_t n = mp->ma_keys->dk_nentries;
1677 if (i < 0 || i >= n)
1678 return 0;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001679 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
1680 while (i < n && entry_ptr->me_value == NULL) {
1681 entry_ptr++;
1682 i++;
Victor Stinner742da042016-09-07 17:40:12 -07001683 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001684 if (i >= n)
1685 return 0;
1686 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001688 *ppos = i+1;
1689 if (pkey)
1690 *pkey = entry_ptr->me_key;
1691 if (phash)
1692 *phash = entry_ptr->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001693 if (pvalue)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001694 *pvalue = value;
1695 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001696}
1697
Tim Peters080c88b2003-02-15 03:01:11 +00001698/*
1699 * Iterate over a dict. Use like so:
1700 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001701 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +00001702 * PyObject *key, *value;
1703 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +00001704 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001705 * Refer to borrowed references in key and value.
Tim Peters080c88b2003-02-15 03:01:11 +00001706 * }
1707 *
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001708 * Return 1 on success, return 0 when the reached the end of the dictionary
1709 * (or if op is not a dictionary)
1710 *
Tim Peters080c88b2003-02-15 03:01:11 +00001711 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +00001712 * mutates the dict. One exception: it is safe if the loop merely changes
1713 * the values associated with the keys (but doesn't insert new keys or
1714 * delete keys), via PyDict_SetItem().
1715 */
Guido van Rossum25831651993-05-19 14:50:45 +00001716int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001717PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001718{
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001719 return _PyDict_Next(op, ppos, pkey, pvalue, NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00001720}
1721
Eric Snow96c6af92015-05-29 22:21:39 -06001722/* Internal version of dict.pop(). */
1723PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001724_PyDict_Pop_KnownHash(PyObject *dict, PyObject *key, Py_hash_t hash, PyObject *deflt)
Eric Snow96c6af92015-05-29 22:21:39 -06001725{
Victor Stinner742da042016-09-07 17:40:12 -07001726 Py_ssize_t ix, hashpos;
Eric Snow96c6af92015-05-29 22:21:39 -06001727 PyObject *old_value, *old_key;
1728 PyDictKeyEntry *ep;
Yury Selivanov684ef2c2016-10-28 19:01:21 -04001729 PyDictObject *mp;
1730
1731 assert(PyDict_Check(dict));
1732 mp = (PyDictObject *)dict;
Eric Snow96c6af92015-05-29 22:21:39 -06001733
1734 if (mp->ma_used == 0) {
1735 if (deflt) {
1736 Py_INCREF(deflt);
1737 return deflt;
1738 }
1739 _PyErr_SetKeyError(key);
1740 return NULL;
1741 }
INADA Naoki778928b2017-08-03 23:45:15 +09001742 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner742da042016-09-07 17:40:12 -07001743 if (ix == DKIX_ERROR)
Eric Snow96c6af92015-05-29 22:21:39 -06001744 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001745 if (ix == DKIX_EMPTY || old_value == NULL) {
Eric Snow96c6af92015-05-29 22:21:39 -06001746 if (deflt) {
1747 Py_INCREF(deflt);
1748 return deflt;
1749 }
1750 _PyErr_SetKeyError(key);
1751 return NULL;
1752 }
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001753
Victor Stinner78601a32016-09-09 19:28:36 -07001754 // Split table doesn't allow deletion. Combine it.
1755 if (_PyDict_HasSplitTable(mp)) {
1756 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1757 return NULL;
1758 }
INADA Naoki778928b2017-08-03 23:45:15 +09001759 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value);
Victor Stinner78601a32016-09-09 19:28:36 -07001760 assert(ix >= 0);
1761 }
1762
INADA Naoki778928b2017-08-03 23:45:15 +09001763 hashpos = lookdict_index(mp->ma_keys, hash, ix);
1764 assert(hashpos >= 0);
Victor Stinner78601a32016-09-09 19:28:36 -07001765 assert(old_value != NULL);
Eric Snow96c6af92015-05-29 22:21:39 -06001766 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001767 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner78601a32016-09-09 19:28:36 -07001768 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1769 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1770 ENSURE_ALLOWS_DELETIONS(mp);
1771 old_key = ep->me_key;
1772 ep->me_key = NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001773 ep->me_value = NULL;
Victor Stinner78601a32016-09-09 19:28:36 -07001774 Py_DECREF(old_key);
Victor Stinner611b0fa2016-09-14 15:02:01 +02001775
1776 assert(_PyDict_CheckConsistency(mp));
Eric Snow96c6af92015-05-29 22:21:39 -06001777 return old_value;
1778}
1779
Serhiy Storchaka67796522017-01-12 18:34:33 +02001780PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001781_PyDict_Pop(PyObject *dict, PyObject *key, PyObject *deflt)
Serhiy Storchaka67796522017-01-12 18:34:33 +02001782{
1783 Py_hash_t hash;
1784
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001785 if (((PyDictObject *)dict)->ma_used == 0) {
Serhiy Storchaka67796522017-01-12 18:34:33 +02001786 if (deflt) {
1787 Py_INCREF(deflt);
1788 return deflt;
1789 }
1790 _PyErr_SetKeyError(key);
1791 return NULL;
1792 }
1793 if (!PyUnicode_CheckExact(key) ||
1794 (hash = ((PyASCIIObject *) key)->hash) == -1) {
1795 hash = PyObject_Hash(key);
1796 if (hash == -1)
1797 return NULL;
1798 }
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001799 return _PyDict_Pop_KnownHash(dict, key, hash, deflt);
Serhiy Storchaka67796522017-01-12 18:34:33 +02001800}
1801
Eric Snow96c6af92015-05-29 22:21:39 -06001802/* Internal version of dict.from_keys(). It is subclass-friendly. */
1803PyObject *
1804_PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
1805{
1806 PyObject *it; /* iter(iterable) */
1807 PyObject *key;
1808 PyObject *d;
1809 int status;
1810
Victor Stinnera5ed5f02016-12-06 18:45:50 +01001811 d = _PyObject_CallNoArg(cls);
Eric Snow96c6af92015-05-29 22:21:39 -06001812 if (d == NULL)
1813 return NULL;
1814
1815 if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
1816 if (PyDict_CheckExact(iterable)) {
1817 PyDictObject *mp = (PyDictObject *)d;
1818 PyObject *oldvalue;
1819 Py_ssize_t pos = 0;
1820 PyObject *key;
1821 Py_hash_t hash;
1822
Serhiy Storchakac61ac162017-03-21 08:52:38 +02001823 if (dictresize(mp, ESTIMATE_SIZE(PyDict_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001824 Py_DECREF(d);
1825 return NULL;
1826 }
1827
1828 while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
1829 if (insertdict(mp, key, hash, value)) {
1830 Py_DECREF(d);
1831 return NULL;
1832 }
1833 }
1834 return d;
1835 }
1836 if (PyAnySet_CheckExact(iterable)) {
1837 PyDictObject *mp = (PyDictObject *)d;
1838 Py_ssize_t pos = 0;
1839 PyObject *key;
1840 Py_hash_t hash;
1841
Victor Stinner742da042016-09-07 17:40:12 -07001842 if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001843 Py_DECREF(d);
1844 return NULL;
1845 }
1846
1847 while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
1848 if (insertdict(mp, key, hash, value)) {
1849 Py_DECREF(d);
1850 return NULL;
1851 }
1852 }
1853 return d;
1854 }
1855 }
1856
1857 it = PyObject_GetIter(iterable);
1858 if (it == NULL){
1859 Py_DECREF(d);
1860 return NULL;
1861 }
1862
1863 if (PyDict_CheckExact(d)) {
1864 while ((key = PyIter_Next(it)) != NULL) {
1865 status = PyDict_SetItem(d, key, value);
1866 Py_DECREF(key);
1867 if (status < 0)
1868 goto Fail;
1869 }
1870 } else {
1871 while ((key = PyIter_Next(it)) != NULL) {
1872 status = PyObject_SetItem(d, key, value);
1873 Py_DECREF(key);
1874 if (status < 0)
1875 goto Fail;
1876 }
1877 }
1878
1879 if (PyErr_Occurred())
1880 goto Fail;
1881 Py_DECREF(it);
1882 return d;
1883
1884Fail:
1885 Py_DECREF(it);
1886 Py_DECREF(d);
1887 return NULL;
1888}
1889
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001890/* Methods */
1891
1892static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001893dict_dealloc(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001894{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001895 PyObject **values = mp->ma_values;
1896 PyDictKeysObject *keys = mp->ma_keys;
1897 Py_ssize_t i, n;
INADA Naokia6296d32017-08-24 14:55:17 +09001898
1899 /* bpo-31095: UnTrack is needed before calling any callbacks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 PyObject_GC_UnTrack(mp);
1901 Py_TRASHCAN_SAFE_BEGIN(mp)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001902 if (values != NULL) {
1903 if (values != empty_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001904 for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001905 Py_XDECREF(values[i]);
1906 }
1907 free_values(values);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001909 DK_DECREF(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 }
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02001911 else if (keys != NULL) {
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001912 assert(keys->dk_refcnt == 1);
1913 DK_DECREF(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001914 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
1916 free_list[numfree++] = mp;
1917 else
1918 Py_TYPE(mp)->tp_free((PyObject *)mp);
1919 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001920}
1921
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001922
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001923static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001924dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 Py_ssize_t i;
Victor Stinnerf91929b2013-11-19 13:07:38 +01001927 PyObject *key = NULL, *value = NULL;
1928 _PyUnicodeWriter writer;
1929 int first;
Guido van Rossum255443b1998-04-10 22:47:14 +00001930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 i = Py_ReprEnter((PyObject *)mp);
1932 if (i != 0) {
1933 return i > 0 ? PyUnicode_FromString("{...}") : NULL;
1934 }
Guido van Rossum255443b1998-04-10 22:47:14 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 if (mp->ma_used == 0) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01001937 Py_ReprLeave((PyObject *)mp);
1938 return PyUnicode_FromString("{}");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 }
Tim Petersa7259592001-06-16 05:11:17 +00001940
Victor Stinnerf91929b2013-11-19 13:07:38 +01001941 _PyUnicodeWriter_Init(&writer);
1942 writer.overallocate = 1;
1943 /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
1944 writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +00001945
Victor Stinnerf91929b2013-11-19 13:07:38 +01001946 if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
1947 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00001948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 /* Do repr() on each key+value pair, and insert ": " between them.
1950 Note that repr may mutate the dict. */
1951 i = 0;
Victor Stinnerf91929b2013-11-19 13:07:38 +01001952 first = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01001954 PyObject *s;
1955 int res;
1956
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001957 /* Prevent repr from deleting key or value during key format. */
1958 Py_INCREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 Py_INCREF(value);
Victor Stinnerf97dfd72013-07-18 01:00:45 +02001960
Victor Stinnerf91929b2013-11-19 13:07:38 +01001961 if (!first) {
1962 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
1963 goto error;
1964 }
1965 first = 0;
1966
1967 s = PyObject_Repr(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 if (s == NULL)
Victor Stinnerf91929b2013-11-19 13:07:38 +01001969 goto error;
1970 res = _PyUnicodeWriter_WriteStr(&writer, s);
1971 Py_DECREF(s);
1972 if (res < 0)
1973 goto error;
1974
1975 if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
1976 goto error;
1977
1978 s = PyObject_Repr(value);
1979 if (s == NULL)
1980 goto error;
1981 res = _PyUnicodeWriter_WriteStr(&writer, s);
1982 Py_DECREF(s);
1983 if (res < 0)
1984 goto error;
1985
1986 Py_CLEAR(key);
1987 Py_CLEAR(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 }
Tim Petersa7259592001-06-16 05:11:17 +00001989
Victor Stinnerf91929b2013-11-19 13:07:38 +01001990 writer.overallocate = 0;
1991 if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
1992 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 Py_ReprLeave((PyObject *)mp);
Victor Stinnerf91929b2013-11-19 13:07:38 +01001995
1996 return _PyUnicodeWriter_Finish(&writer);
1997
1998error:
1999 Py_ReprLeave((PyObject *)mp);
2000 _PyUnicodeWriter_Dealloc(&writer);
2001 Py_XDECREF(key);
2002 Py_XDECREF(value);
2003 return NULL;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002004}
2005
Martin v. Löwis18e16552006-02-15 17:27:45 +00002006static Py_ssize_t
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002007dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 return mp->ma_used;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002010}
2011
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002012static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002013dict_subscript(PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002014{
Victor Stinner742da042016-09-07 17:40:12 -07002015 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002016 Py_hash_t hash;
INADA Naokiba609772016-12-07 20:41:42 +09002017 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002020 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 hash = PyObject_Hash(key);
2022 if (hash == -1)
2023 return NULL;
2024 }
INADA Naoki778928b2017-08-03 23:45:15 +09002025 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002026 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002028 if (ix == DKIX_EMPTY || value == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 if (!PyDict_CheckExact(mp)) {
2030 /* Look up __missing__ method if we're a subclass. */
2031 PyObject *missing, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05002032 _Py_IDENTIFIER(__missing__);
2033 missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 if (missing != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002035 res = PyObject_CallFunctionObjArgs(missing,
2036 key, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 Py_DECREF(missing);
2038 return res;
2039 }
2040 else if (PyErr_Occurred())
2041 return NULL;
2042 }
Raymond Hettinger69492da2013-09-02 15:59:26 -07002043 _PyErr_SetKeyError(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 return NULL;
2045 }
INADA Naokiba609772016-12-07 20:41:42 +09002046 Py_INCREF(value);
2047 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002048}
2049
2050static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002051dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 if (w == NULL)
2054 return PyDict_DelItem((PyObject *)mp, v);
2055 else
2056 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002057}
2058
Guido van Rossuma9e7a811997-05-13 21:02:11 +00002059static PyMappingMethods dict_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 (lenfunc)dict_length, /*mp_length*/
2061 (binaryfunc)dict_subscript, /*mp_subscript*/
2062 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002063};
2064
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002065static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002066dict_keys(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002067{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002068 PyObject *v;
2069 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002070 PyDictKeyEntry *ep;
2071 Py_ssize_t size, n, offset;
2072 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002073
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002074 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 n = mp->ma_used;
2076 v = PyList_New(n);
2077 if (v == NULL)
2078 return NULL;
2079 if (n != mp->ma_used) {
2080 /* Durnit. The allocations caused the dict to resize.
2081 * Just start over, this shouldn't normally happen.
2082 */
2083 Py_DECREF(v);
2084 goto again;
2085 }
Victor Stinner742da042016-09-07 17:40:12 -07002086 ep = DK_ENTRIES(mp->ma_keys);
2087 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002088 if (mp->ma_values) {
2089 value_ptr = mp->ma_values;
2090 offset = sizeof(PyObject *);
2091 }
2092 else {
2093 value_ptr = &ep[0].me_value;
2094 offset = sizeof(PyDictKeyEntry);
2095 }
2096 for (i = 0, j = 0; i < size; i++) {
2097 if (*value_ptr != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 PyObject *key = ep[i].me_key;
2099 Py_INCREF(key);
2100 PyList_SET_ITEM(v, j, key);
2101 j++;
2102 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002103 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 }
2105 assert(j == n);
2106 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002107}
2108
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002109static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002110dict_values(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002111{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002112 PyObject *v;
2113 Py_ssize_t i, j;
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002114 PyDictKeyEntry *ep;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002115 Py_ssize_t size, n, offset;
2116 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002117
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002118 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 n = mp->ma_used;
2120 v = PyList_New(n);
2121 if (v == NULL)
2122 return NULL;
2123 if (n != mp->ma_used) {
2124 /* Durnit. The allocations caused the dict to resize.
2125 * Just start over, this shouldn't normally happen.
2126 */
2127 Py_DECREF(v);
2128 goto again;
2129 }
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002130 ep = DK_ENTRIES(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002131 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002132 if (mp->ma_values) {
2133 value_ptr = mp->ma_values;
2134 offset = sizeof(PyObject *);
2135 }
2136 else {
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002137 value_ptr = &ep[0].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002138 offset = sizeof(PyDictKeyEntry);
2139 }
2140 for (i = 0, j = 0; i < size; i++) {
2141 PyObject *value = *value_ptr;
2142 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2143 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 Py_INCREF(value);
2145 PyList_SET_ITEM(v, j, value);
2146 j++;
2147 }
2148 }
2149 assert(j == n);
2150 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002151}
2152
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002153static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002154dict_items(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002155{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002156 PyObject *v;
2157 Py_ssize_t i, j, n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002158 Py_ssize_t size, offset;
2159 PyObject *item, *key;
2160 PyDictKeyEntry *ep;
2161 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 /* Preallocate the list of tuples, to avoid allocations during
2164 * the loop over the items, which could trigger GC, which
2165 * could resize the dict. :-(
2166 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002167 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 n = mp->ma_used;
2169 v = PyList_New(n);
2170 if (v == NULL)
2171 return NULL;
2172 for (i = 0; i < n; i++) {
2173 item = PyTuple_New(2);
2174 if (item == NULL) {
2175 Py_DECREF(v);
2176 return NULL;
2177 }
2178 PyList_SET_ITEM(v, i, item);
2179 }
2180 if (n != mp->ma_used) {
2181 /* Durnit. The allocations caused the dict to resize.
2182 * Just start over, this shouldn't normally happen.
2183 */
2184 Py_DECREF(v);
2185 goto again;
2186 }
2187 /* Nothing we do below makes any function calls. */
Victor Stinner742da042016-09-07 17:40:12 -07002188 ep = DK_ENTRIES(mp->ma_keys);
2189 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002190 if (mp->ma_values) {
2191 value_ptr = mp->ma_values;
2192 offset = sizeof(PyObject *);
2193 }
2194 else {
2195 value_ptr = &ep[0].me_value;
2196 offset = sizeof(PyDictKeyEntry);
2197 }
2198 for (i = 0, j = 0; i < size; i++) {
2199 PyObject *value = *value_ptr;
2200 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2201 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 key = ep[i].me_key;
2203 item = PyList_GET_ITEM(v, j);
2204 Py_INCREF(key);
2205 PyTuple_SET_ITEM(item, 0, key);
2206 Py_INCREF(value);
2207 PyTuple_SET_ITEM(item, 1, value);
2208 j++;
2209 }
2210 }
2211 assert(j == n);
2212 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002213}
2214
Larry Hastings5c661892014-01-24 06:17:25 -08002215/*[clinic input]
2216@classmethod
2217dict.fromkeys
Larry Hastings5c661892014-01-24 06:17:25 -08002218 iterable: object
2219 value: object=None
2220 /
2221
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002222Create a new dictionary with keys from iterable and values set to value.
Larry Hastings5c661892014-01-24 06:17:25 -08002223[clinic start generated code]*/
2224
Larry Hastings5c661892014-01-24 06:17:25 -08002225static PyObject *
2226dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002227/*[clinic end generated code: output=8fb98e4b10384999 input=382ba4855d0f74c3]*/
Larry Hastings5c661892014-01-24 06:17:25 -08002228{
Eric Snow96c6af92015-05-29 22:21:39 -06002229 return _PyDict_FromKeys((PyObject *)type, iterable, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002230}
2231
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002232static int
Victor Stinner742da042016-09-07 17:40:12 -07002233dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
2234 const char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 PyObject *arg = NULL;
2237 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002238
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002239 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 result = -1;
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002241 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 else if (arg != NULL) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02002243 _Py_IDENTIFIER(keys);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002244 PyObject *func;
2245 if (_PyObject_LookupAttrId(arg, &PyId_keys, &func) < 0) {
2246 result = -1;
2247 }
2248 else if (func != NULL) {
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002249 Py_DECREF(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 result = PyDict_Merge(self, arg, 1);
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002251 }
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002252 else {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002253 result = PyDict_MergeFromSeq2(self, arg, 1);
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002254 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 }
Serhiy Storchaka60c3d352017-11-11 16:19:56 +02002256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 if (result == 0 && kwds != NULL) {
2258 if (PyArg_ValidateKeywordArguments(kwds))
2259 result = PyDict_Merge(self, kwds, 1);
2260 else
2261 result = -1;
2262 }
2263 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002264}
2265
Victor Stinner91f0d4a2017-01-19 12:45:06 +01002266/* Note: dict.update() uses the METH_VARARGS|METH_KEYWORDS calling convention.
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002267 Using METH_FASTCALL|METH_KEYWORDS would make dict.update(**dict2) calls
2268 slower, see the issue #29312. */
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002269static PyObject *
2270dict_update(PyObject *self, PyObject *args, PyObject *kwds)
2271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 if (dict_update_common(self, args, kwds, "update") != -1)
2273 Py_RETURN_NONE;
2274 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002275}
2276
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002277/* Update unconditionally replaces existing items.
2278 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00002279 otherwise it leaves existing items unchanged.
2280
2281 PyDict_{Update,Merge} update/merge from a mapping object.
2282
Tim Petersf582b822001-12-11 18:51:08 +00002283 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00002284 producing iterable objects of length 2.
2285*/
2286
Tim Petersf582b822001-12-11 18:51:08 +00002287int
Tim Peters1fc240e2001-10-26 05:06:50 +00002288PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
2289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 PyObject *it; /* iter(seq2) */
2291 Py_ssize_t i; /* index into seq2 of current element */
2292 PyObject *item; /* seq2[i] */
2293 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 assert(d != NULL);
2296 assert(PyDict_Check(d));
2297 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 it = PyObject_GetIter(seq2);
2300 if (it == NULL)
2301 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 for (i = 0; ; ++i) {
2304 PyObject *key, *value;
2305 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 fast = NULL;
2308 item = PyIter_Next(it);
2309 if (item == NULL) {
2310 if (PyErr_Occurred())
2311 goto Fail;
2312 break;
2313 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 /* Convert item to sequence, and verify length 2. */
2316 fast = PySequence_Fast(item, "");
2317 if (fast == NULL) {
2318 if (PyErr_ExceptionMatches(PyExc_TypeError))
2319 PyErr_Format(PyExc_TypeError,
2320 "cannot convert dictionary update "
2321 "sequence element #%zd to a sequence",
2322 i);
2323 goto Fail;
2324 }
2325 n = PySequence_Fast_GET_SIZE(fast);
2326 if (n != 2) {
2327 PyErr_Format(PyExc_ValueError,
2328 "dictionary update sequence element #%zd "
2329 "has length %zd; 2 is required",
2330 i, n);
2331 goto Fail;
2332 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 /* Update/merge with this (key, value) pair. */
2335 key = PySequence_Fast_GET_ITEM(fast, 0);
2336 value = PySequence_Fast_GET_ITEM(fast, 1);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002337 Py_INCREF(key);
2338 Py_INCREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 if (override || PyDict_GetItem(d, key) == NULL) {
2340 int status = PyDict_SetItem(d, key, value);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002341 if (status < 0) {
2342 Py_DECREF(key);
2343 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 goto Fail;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002345 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 }
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002347 Py_DECREF(key);
2348 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 Py_DECREF(fast);
2350 Py_DECREF(item);
2351 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 i = 0;
Victor Stinner611b0fa2016-09-14 15:02:01 +02002354 assert(_PyDict_CheckConsistency((PyDictObject *)d));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00002356Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 Py_XDECREF(item);
2358 Py_XDECREF(fast);
2359 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002360Return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 Py_DECREF(it);
2362 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00002363}
2364
doko@ubuntu.comc96df682016-10-11 08:04:02 +02002365static int
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002366dict_merge(PyObject *a, PyObject *b, int override)
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002367{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002368 PyDictObject *mp, *other;
2369 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -07002370 PyDictKeyEntry *entry, *ep0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002371
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002372 assert(0 <= override && override <= 2);
2373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 /* We accept for the argument either a concrete dictionary object,
2375 * or an abstract "mapping" object. For the former, we can do
2376 * things quite efficiently. For the latter, we only require that
2377 * PyMapping_Keys() and PyObject_GetItem() be supported.
2378 */
2379 if (a == NULL || !PyDict_Check(a) || b == NULL) {
2380 PyErr_BadInternalCall();
2381 return -1;
2382 }
2383 mp = (PyDictObject*)a;
INADA Naoki2aaf98c2018-09-26 12:59:00 +09002384 if (PyDict_Check(b) && (Py_TYPE(b)->tp_iter == (getiterfunc)dict_iter)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 other = (PyDictObject*)b;
2386 if (other == mp || other->ma_used == 0)
2387 /* a.update(a) or a.update({}); nothing to do */
2388 return 0;
2389 if (mp->ma_used == 0)
2390 /* Since the target dict is empty, PyDict_GetItem()
2391 * always returns NULL. Setting override to 1
2392 * skips the unnecessary test.
2393 */
2394 override = 1;
2395 /* Do one big resize at the start, rather than
2396 * incrementally resizing as we insert new items. Expect
2397 * that there will be no (or few) overlapping keys.
2398 */
INADA Naokib1152be2016-10-27 19:26:50 +09002399 if (USABLE_FRACTION(mp->ma_keys->dk_size) < other->ma_used) {
2400 if (dictresize(mp, ESTIMATE_SIZE(mp->ma_used + other->ma_used))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 return -1;
INADA Naokib1152be2016-10-27 19:26:50 +09002402 }
2403 }
Victor Stinner742da042016-09-07 17:40:12 -07002404 ep0 = DK_ENTRIES(other->ma_keys);
2405 for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002406 PyObject *key, *value;
2407 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002408 entry = &ep0[i];
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002409 key = entry->me_key;
2410 hash = entry->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002411 if (other->ma_values)
2412 value = other->ma_values[i];
2413 else
2414 value = entry->me_value;
2415
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002416 if (value != NULL) {
2417 int err = 0;
2418 Py_INCREF(key);
2419 Py_INCREF(value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002420 if (override == 1)
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002421 err = insertdict(mp, key, hash, value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002422 else if (_PyDict_GetItem_KnownHash(a, key, hash) == NULL) {
2423 if (PyErr_Occurred()) {
2424 Py_DECREF(value);
2425 Py_DECREF(key);
2426 return -1;
2427 }
2428 err = insertdict(mp, key, hash, value);
2429 }
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002430 else if (override != 0) {
2431 _PyErr_SetKeyError(key);
2432 Py_DECREF(value);
2433 Py_DECREF(key);
2434 return -1;
2435 }
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002436 Py_DECREF(value);
2437 Py_DECREF(key);
2438 if (err != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 return -1;
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002440
Victor Stinner742da042016-09-07 17:40:12 -07002441 if (n != other->ma_keys->dk_nentries) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002442 PyErr_SetString(PyExc_RuntimeError,
2443 "dict mutated during update");
2444 return -1;
2445 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 }
2447 }
2448 }
2449 else {
2450 /* Do it the generic, slower way */
2451 PyObject *keys = PyMapping_Keys(b);
2452 PyObject *iter;
2453 PyObject *key, *value;
2454 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 if (keys == NULL)
2457 /* Docstring says this is equivalent to E.keys() so
2458 * if E doesn't have a .keys() method we want
2459 * AttributeError to percolate up. Might as well
2460 * do the same for any other error.
2461 */
2462 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 iter = PyObject_GetIter(keys);
2465 Py_DECREF(keys);
2466 if (iter == NULL)
2467 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002470 if (override != 1 && PyDict_GetItem(a, key) != NULL) {
2471 if (override != 0) {
2472 _PyErr_SetKeyError(key);
2473 Py_DECREF(key);
2474 Py_DECREF(iter);
2475 return -1;
2476 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 Py_DECREF(key);
2478 continue;
2479 }
2480 value = PyObject_GetItem(b, key);
2481 if (value == NULL) {
2482 Py_DECREF(iter);
2483 Py_DECREF(key);
2484 return -1;
2485 }
2486 status = PyDict_SetItem(a, key, value);
2487 Py_DECREF(key);
2488 Py_DECREF(value);
2489 if (status < 0) {
2490 Py_DECREF(iter);
2491 return -1;
2492 }
2493 }
2494 Py_DECREF(iter);
2495 if (PyErr_Occurred())
2496 /* Iterator completed, via error */
2497 return -1;
2498 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02002499 assert(_PyDict_CheckConsistency((PyDictObject *)a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002501}
2502
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002503int
2504PyDict_Update(PyObject *a, PyObject *b)
2505{
2506 return dict_merge(a, b, 1);
2507}
2508
2509int
2510PyDict_Merge(PyObject *a, PyObject *b, int override)
2511{
2512 /* XXX Deprecate override not in (0, 1). */
2513 return dict_merge(a, b, override != 0);
2514}
2515
2516int
2517_PyDict_MergeEx(PyObject *a, PyObject *b, int override)
2518{
2519 return dict_merge(a, b, override);
2520}
2521
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002522static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302523dict_copy(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002526}
2527
2528PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002529PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 PyObject *copy;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002532 PyDictObject *mp;
2533 Py_ssize_t i, n;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 if (o == NULL || !PyDict_Check(o)) {
2536 PyErr_BadInternalCall();
2537 return NULL;
2538 }
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002539
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002540 mp = (PyDictObject *)o;
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002541 if (mp->ma_used == 0) {
2542 /* The dict is empty; just return a new dict. */
2543 return PyDict_New();
2544 }
2545
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002546 if (_PyDict_HasSplitTable(mp)) {
2547 PyDictObject *split_copy;
Victor Stinner742da042016-09-07 17:40:12 -07002548 Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
2549 PyObject **newvalues;
2550 newvalues = new_values(size);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002551 if (newvalues == NULL)
2552 return PyErr_NoMemory();
2553 split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
2554 if (split_copy == NULL) {
2555 free_values(newvalues);
2556 return NULL;
2557 }
2558 split_copy->ma_values = newvalues;
2559 split_copy->ma_keys = mp->ma_keys;
2560 split_copy->ma_used = mp->ma_used;
INADA Naokid1c82c52018-04-03 11:43:53 +09002561 split_copy->ma_version_tag = DICT_NEXT_VERSION();
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002562 DK_INCREF(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002563 for (i = 0, n = size; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002564 PyObject *value = mp->ma_values[i];
2565 Py_XINCREF(value);
2566 split_copy->ma_values[i] = value;
2567 }
Benjamin Peterson7ce67e42012-04-24 10:32:57 -04002568 if (_PyObject_GC_IS_TRACKED(mp))
2569 _PyObject_GC_TRACK(split_copy);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002570 return (PyObject *)split_copy;
2571 }
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002572
2573 if (PyDict_CheckExact(mp) && mp->ma_values == NULL &&
2574 (mp->ma_used >= (mp->ma_keys->dk_nentries * 2) / 3))
2575 {
2576 /* Use fast-copy if:
2577
2578 (1) 'mp' is an instance of a subclassed dict; and
2579
2580 (2) 'mp' is not a split-dict; and
2581
2582 (3) if 'mp' is non-compact ('del' operation does not resize dicts),
2583 do fast-copy only if it has at most 1/3 non-used keys.
2584
Ville Skyttä61f82e02018-04-20 23:08:45 +03002585 The last condition (3) is important to guard against a pathological
Yury Selivanovb0a7a032018-01-22 11:54:41 -05002586 case when a large dict is almost emptied with multiple del/pop
2587 operations and copied after that. In cases like this, we defer to
2588 PyDict_Merge, which produces a compacted copy.
2589 */
2590 return clone_combined_dict(mp);
2591 }
2592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 copy = PyDict_New();
2594 if (copy == NULL)
2595 return NULL;
2596 if (PyDict_Merge(copy, o, 1) == 0)
2597 return copy;
2598 Py_DECREF(copy);
2599 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002600}
2601
Martin v. Löwis18e16552006-02-15 17:27:45 +00002602Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00002603PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00002604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 if (mp == NULL || !PyDict_Check(mp)) {
2606 PyErr_BadInternalCall();
2607 return -1;
2608 }
2609 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00002610}
2611
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002612PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002613PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 if (mp == NULL || !PyDict_Check(mp)) {
2616 PyErr_BadInternalCall();
2617 return NULL;
2618 }
2619 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002620}
2621
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002622PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002623PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 if (mp == NULL || !PyDict_Check(mp)) {
2626 PyErr_BadInternalCall();
2627 return NULL;
2628 }
2629 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002630}
2631
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002632PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002633PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 if (mp == NULL || !PyDict_Check(mp)) {
2636 PyErr_BadInternalCall();
2637 return NULL;
2638 }
2639 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002640}
2641
Tim Peterse63415e2001-05-08 04:38:29 +00002642/* Return 1 if dicts equal, 0 if not, -1 if error.
2643 * Gets out as soon as any difference is detected.
2644 * Uses only Py_EQ comparison.
2645 */
2646static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002647dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00002648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00002650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 if (a->ma_used != b->ma_used)
2652 /* can't be equal if # of entries differ */
2653 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Victor Stinner742da042016-09-07 17:40:12 -07002655 for (i = 0; i < a->ma_keys->dk_nentries; i++) {
2656 PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002657 PyObject *aval;
2658 if (a->ma_values)
2659 aval = a->ma_values[i];
2660 else
2661 aval = ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 if (aval != NULL) {
2663 int cmp;
2664 PyObject *bval;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002665 PyObject *key = ep->me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 /* temporarily bump aval's refcount to ensure it stays
2667 alive until we're done with it */
2668 Py_INCREF(aval);
2669 /* ditto for key */
2670 Py_INCREF(key);
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002671 /* reuse the known hash value */
INADA Naoki778928b2017-08-03 23:45:15 +09002672 b->ma_keys->dk_lookup(b, key, ep->me_hash, &bval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 if (bval == NULL) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002674 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 Py_DECREF(aval);
2676 if (PyErr_Occurred())
2677 return -1;
2678 return 0;
2679 }
2680 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002681 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 Py_DECREF(aval);
2683 if (cmp <= 0) /* error or not equal */
2684 return cmp;
2685 }
2686 }
2687 return 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002688}
Tim Peterse63415e2001-05-08 04:38:29 +00002689
2690static PyObject *
2691dict_richcompare(PyObject *v, PyObject *w, int op)
2692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 int cmp;
2694 PyObject *res;
Tim Peterse63415e2001-05-08 04:38:29 +00002695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 if (!PyDict_Check(v) || !PyDict_Check(w)) {
2697 res = Py_NotImplemented;
2698 }
2699 else if (op == Py_EQ || op == Py_NE) {
2700 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
2701 if (cmp < 0)
2702 return NULL;
2703 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
2704 }
2705 else
2706 res = Py_NotImplemented;
2707 Py_INCREF(res);
2708 return res;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002709}
Tim Peterse63415e2001-05-08 04:38:29 +00002710
Larry Hastings61272b72014-01-07 12:41:53 -08002711/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002712
2713@coexist
2714dict.__contains__
2715
2716 key: object
2717 /
2718
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002719True if the dictionary has the specified key, else False.
Larry Hastings61272b72014-01-07 12:41:53 -08002720[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002721
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002722static PyObject *
Larry Hastingsc2047262014-01-25 20:43:29 -08002723dict___contains__(PyDictObject *self, PyObject *key)
Serhiy Storchaka19d25972017-02-04 08:05:07 +02002724/*[clinic end generated code: output=a3d03db709ed6e6b input=fe1cb42ad831e820]*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002725{
Larry Hastingsc2047262014-01-25 20:43:29 -08002726 register PyDictObject *mp = self;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002727 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002728 Py_ssize_t ix;
INADA Naokiba609772016-12-07 20:41:42 +09002729 PyObject *value;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002732 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 hash = PyObject_Hash(key);
2734 if (hash == -1)
2735 return NULL;
2736 }
INADA Naoki778928b2017-08-03 23:45:15 +09002737 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002738 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002740 if (ix == DKIX_EMPTY || value == NULL)
Victor Stinner742da042016-09-07 17:40:12 -07002741 Py_RETURN_FALSE;
2742 Py_RETURN_TRUE;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002743}
2744
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002745/*[clinic input]
2746dict.get
2747
2748 key: object
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002749 default: object = None
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002750 /
2751
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002752Return the value for key if key is in the dictionary, else default.
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002753[clinic start generated code]*/
2754
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002755static PyObject *
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002756dict_get_impl(PyDictObject *self, PyObject *key, PyObject *default_value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002757/*[clinic end generated code: output=bba707729dee05bf input=279ddb5790b6b107]*/
Barry Warsawc38c5da1997-10-06 17:49:20 +00002758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002760 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002761 Py_ssize_t ix;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002764 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 hash = PyObject_Hash(key);
2766 if (hash == -1)
2767 return NULL;
2768 }
INADA Naoki778928b2017-08-03 23:45:15 +09002769 ix = (self->ma_keys->dk_lookup) (self, key, hash, &val);
Victor Stinner742da042016-09-07 17:40:12 -07002770 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002772 if (ix == DKIX_EMPTY || val == NULL) {
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002773 val = default_value;
INADA Naokiba609772016-12-07 20:41:42 +09002774 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 Py_INCREF(val);
2776 return val;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002777}
2778
Benjamin Peterson00e98862013-03-07 22:16:29 -05002779PyObject *
2780PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
Guido van Rossum164452c2000-08-08 16:12:54 +00002781{
Benjamin Peterson00e98862013-03-07 22:16:29 -05002782 PyDictObject *mp = (PyDictObject *)d;
INADA Naoki93f26f72016-11-02 18:45:16 +09002783 PyObject *value;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002784 Py_hash_t hash;
Guido van Rossum164452c2000-08-08 16:12:54 +00002785
Benjamin Peterson00e98862013-03-07 22:16:29 -05002786 if (!PyDict_Check(d)) {
2787 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 return NULL;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002789 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002792 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 hash = PyObject_Hash(key);
2794 if (hash == -1)
2795 return NULL;
2796 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002797
2798 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
2799 if (insertion_resize(mp) < 0)
2800 return NULL;
2801 }
2802
INADA Naoki778928b2017-08-03 23:45:15 +09002803 Py_ssize_t ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07002804 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 return NULL;
INADA Naoki93f26f72016-11-02 18:45:16 +09002806
2807 if (_PyDict_HasSplitTable(mp) &&
INADA Naokiba609772016-12-07 20:41:42 +09002808 ((ix >= 0 && value == NULL && mp->ma_used != ix) ||
INADA Naoki93f26f72016-11-02 18:45:16 +09002809 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
2810 if (insertion_resize(mp) < 0) {
2811 return NULL;
2812 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002813 ix = DKIX_EMPTY;
2814 }
2815
2816 if (ix == DKIX_EMPTY) {
2817 PyDictKeyEntry *ep, *ep0;
2818 value = defaultobj;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002819 if (mp->ma_keys->dk_usable <= 0) {
Victor Stinner3c336c52016-09-12 14:17:40 +02002820 if (insertion_resize(mp) < 0) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002821 return NULL;
Victor Stinner3c336c52016-09-12 14:17:40 +02002822 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002823 }
INADA Naoki778928b2017-08-03 23:45:15 +09002824 Py_ssize_t hashpos = find_empty_slot(mp->ma_keys, hash);
INADA Naoki93f26f72016-11-02 18:45:16 +09002825 ep0 = DK_ENTRIES(mp->ma_keys);
2826 ep = &ep0[mp->ma_keys->dk_nentries];
2827 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
Benjamin Petersonb1efa532013-03-04 09:47:50 -05002828 Py_INCREF(key);
INADA Naoki93f26f72016-11-02 18:45:16 +09002829 Py_INCREF(value);
2830 MAINTAIN_TRACKING(mp, key, value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002831 ep->me_key = key;
2832 ep->me_hash = hash;
INADA Naokiba609772016-12-07 20:41:42 +09002833 if (_PyDict_HasSplitTable(mp)) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002834 assert(mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
2835 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Victor Stinner742da042016-09-07 17:40:12 -07002836 }
2837 else {
INADA Naoki93f26f72016-11-02 18:45:16 +09002838 ep->me_value = value;
Victor Stinner742da042016-09-07 17:40:12 -07002839 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002840 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07002841 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naoki93f26f72016-11-02 18:45:16 +09002842 mp->ma_keys->dk_usable--;
2843 mp->ma_keys->dk_nentries++;
2844 assert(mp->ma_keys->dk_usable >= 0);
2845 }
INADA Naokiba609772016-12-07 20:41:42 +09002846 else if (value == NULL) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002847 value = defaultobj;
2848 assert(_PyDict_HasSplitTable(mp));
2849 assert(ix == mp->ma_used);
2850 Py_INCREF(value);
2851 MAINTAIN_TRACKING(mp, key, value);
INADA Naokiba609772016-12-07 20:41:42 +09002852 mp->ma_values[ix] = value;
INADA Naoki93f26f72016-11-02 18:45:16 +09002853 mp->ma_used++;
2854 mp->ma_version_tag = DICT_NEXT_VERSION();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002856
2857 assert(_PyDict_CheckConsistency(mp));
2858 return value;
Guido van Rossum164452c2000-08-08 16:12:54 +00002859}
2860
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002861/*[clinic input]
2862dict.setdefault
2863
2864 key: object
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002865 default: object = None
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002866 /
2867
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002868Insert key with a value of default if key is not in the dictionary.
2869
2870Return the value for key if key is in the dictionary, else default.
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002871[clinic start generated code]*/
2872
Benjamin Peterson00e98862013-03-07 22:16:29 -05002873static PyObject *
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002874dict_setdefault_impl(PyDictObject *self, PyObject *key,
2875 PyObject *default_value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002876/*[clinic end generated code: output=f8c1101ebf69e220 input=0f063756e815fd9d]*/
Benjamin Peterson00e98862013-03-07 22:16:29 -05002877{
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002878 PyObject *val;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002879
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002880 val = PyDict_SetDefault((PyObject *)self, key, default_value);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002881 Py_XINCREF(val);
2882 return val;
2883}
Guido van Rossum164452c2000-08-08 16:12:54 +00002884
2885static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302886dict_clear(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 PyDict_Clear((PyObject *)mp);
2889 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002890}
2891
Guido van Rossumba6ab842000-12-12 22:02:18 +00002892static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002893dict_pop(PyDictObject *mp, PyObject *args)
Guido van Rossume027d982002-04-12 15:11:59 +00002894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 PyObject *key, *deflt = NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00002896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
2898 return NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06002899
Yury Selivanov684ef2c2016-10-28 19:01:21 -04002900 return _PyDict_Pop((PyObject*)mp, key, deflt);
Guido van Rossume027d982002-04-12 15:11:59 +00002901}
2902
2903static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302904dict_popitem(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Guido van Rossumba6ab842000-12-12 22:02:18 +00002905{
Victor Stinner742da042016-09-07 17:40:12 -07002906 Py_ssize_t i, j;
2907 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 PyObject *res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 /* Allocate the result tuple before checking the size. Believe it
2911 * or not, this allocation could trigger a garbage collection which
2912 * could empty the dict, so if we checked the size first and that
2913 * happened, the result would be an infinite loop (searching for an
2914 * entry that no longer exists). Note that the usual popitem()
2915 * idiom is "while d: k, v = d.popitem()". so needing to throw the
2916 * tuple away if the dict *is* empty isn't a significant
2917 * inefficiency -- possible, but unlikely in practice.
2918 */
2919 res = PyTuple_New(2);
2920 if (res == NULL)
2921 return NULL;
2922 if (mp->ma_used == 0) {
2923 Py_DECREF(res);
2924 PyErr_SetString(PyExc_KeyError,
2925 "popitem(): dictionary is empty");
2926 return NULL;
2927 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002928 /* Convert split table to combined table */
2929 if (mp->ma_keys->dk_lookup == lookdict_split) {
2930 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
2931 Py_DECREF(res);
2932 return NULL;
2933 }
2934 }
2935 ENSURE_ALLOWS_DELETIONS(mp);
Victor Stinner742da042016-09-07 17:40:12 -07002936
2937 /* Pop last item */
2938 ep0 = DK_ENTRIES(mp->ma_keys);
2939 i = mp->ma_keys->dk_nentries - 1;
2940 while (i >= 0 && ep0[i].me_value == NULL) {
2941 i--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 }
Victor Stinner742da042016-09-07 17:40:12 -07002943 assert(i >= 0);
2944
2945 ep = &ep0[i];
2946 j = lookdict_index(mp->ma_keys, ep->me_hash, i);
2947 assert(j >= 0);
2948 assert(dk_get_index(mp->ma_keys, j) == i);
2949 dk_set_index(mp->ma_keys, j, DKIX_DUMMY);
2950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 PyTuple_SET_ITEM(res, 0, ep->me_key);
2952 PyTuple_SET_ITEM(res, 1, ep->me_value);
Victor Stinner742da042016-09-07 17:40:12 -07002953 ep->me_key = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 ep->me_value = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002955 /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
2956 mp->ma_keys->dk_nentries = i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07002958 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner611b0fa2016-09-14 15:02:01 +02002959 assert(_PyDict_CheckConsistency(mp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 return res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002961}
2962
Jeremy Hylton8caad492000-06-23 14:18:11 +00002963static int
2964dict_traverse(PyObject *op, visitproc visit, void *arg)
2965{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002966 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson55f44522016-09-05 12:12:59 -07002967 PyDictKeysObject *keys = mp->ma_keys;
Serhiy Storchaka46825d22016-09-26 21:29:34 +03002968 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Victor Stinner742da042016-09-07 17:40:12 -07002969 Py_ssize_t i, n = keys->dk_nentries;
2970
Benjamin Peterson55f44522016-09-05 12:12:59 -07002971 if (keys->dk_lookup == lookdict) {
2972 for (i = 0; i < n; i++) {
2973 if (entries[i].me_value != NULL) {
2974 Py_VISIT(entries[i].me_value);
2975 Py_VISIT(entries[i].me_key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002976 }
2977 }
Victor Stinner742da042016-09-07 17:40:12 -07002978 }
2979 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002980 if (mp->ma_values != NULL) {
Benjamin Peterson55f44522016-09-05 12:12:59 -07002981 for (i = 0; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002982 Py_VISIT(mp->ma_values[i]);
2983 }
2984 }
2985 else {
Benjamin Peterson55f44522016-09-05 12:12:59 -07002986 for (i = 0; i < n; i++) {
2987 Py_VISIT(entries[i].me_value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002988 }
2989 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 }
2991 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002992}
2993
2994static int
2995dict_tp_clear(PyObject *op)
2996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 PyDict_Clear(op);
2998 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002999}
3000
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003001static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003002
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003003Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003004_PyDict_SizeOf(PyDictObject *mp)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003005{
Victor Stinner742da042016-09-07 17:40:12 -07003006 Py_ssize_t size, usable, res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003007
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003008 size = DK_SIZE(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07003009 usable = USABLE_FRACTION(size);
3010
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02003011 res = _PyObject_SIZE(Py_TYPE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003012 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07003013 res += usable * sizeof(PyObject*);
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003014 /* If the dictionary is split, the keys portion is accounted-for
3015 in the type object. */
3016 if (mp->ma_keys->dk_refcnt == 1)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003017 res += (sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003018 + DK_IXSIZE(mp->ma_keys) * size
3019 + sizeof(PyDictKeyEntry) * usable);
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003020 return res;
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003021}
3022
3023Py_ssize_t
3024_PyDict_KeysSize(PyDictKeysObject *keys)
3025{
Victor Stinner98ee9d52016-09-08 09:33:56 -07003026 return (sizeof(PyDictKeysObject)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003027 + DK_IXSIZE(keys) * DK_SIZE(keys)
3028 + USABLE_FRACTION(DK_SIZE(keys)) * sizeof(PyDictKeyEntry));
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003029}
3030
doko@ubuntu.com17210f52016-01-14 14:04:59 +01003031static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303032dict_sizeof(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003033{
3034 return PyLong_FromSsize_t(_PyDict_SizeOf(mp));
3035}
3036
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003037PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
3038
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003039PyDoc_STRVAR(sizeof__doc__,
3040"D.__sizeof__() -> size of D in memory, in bytes");
3041
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003042PyDoc_STRVAR(pop__doc__,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00003043"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00003044If key is not found, d is returned if given, otherwise KeyError is raised");
Guido van Rossume027d982002-04-12 15:11:59 +00003045
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003046PyDoc_STRVAR(popitem__doc__,
Tim Petersf7f88b12000-12-13 23:18:45 +00003047"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000030482-tuple; but raise KeyError if D is empty.");
Tim Petersf7f88b12000-12-13 23:18:45 +00003049
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003050PyDoc_STRVAR(update__doc__,
Brett Cannonf2754162013-05-11 14:46:48 -04003051"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n\
3052If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]\n\
3053If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n\
3054In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00003055
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003056PyDoc_STRVAR(clear__doc__,
3057"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00003058
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003059PyDoc_STRVAR(copy__doc__,
3060"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00003061
Guido van Rossumb90c8482007-02-10 01:11:45 +00003062/* Forward */
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303063static PyObject *dictkeys_new(PyObject *, PyObject *);
3064static PyObject *dictitems_new(PyObject *, PyObject *);
3065static PyObject *dictvalues_new(PyObject *, PyObject *);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003066
Guido van Rossum45c85d12007-07-27 16:31:40 +00003067PyDoc_STRVAR(keys__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 "D.keys() -> a set-like object providing a view on D's keys");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003069PyDoc_STRVAR(items__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 "D.items() -> a set-like object providing a view on D's items");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003071PyDoc_STRVAR(values__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 "D.values() -> an object providing a view on D's values");
Guido van Rossumb90c8482007-02-10 01:11:45 +00003073
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003074static PyMethodDef mapp_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -07003075 DICT___CONTAINS___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
3077 getitem__doc__},
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003078 {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 sizeof__doc__},
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01003080 DICT_GET_METHODDEF
3081 DICT_SETDEFAULT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 {"pop", (PyCFunction)dict_pop, METH_VARARGS,
3083 pop__doc__},
3084 {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
3085 popitem__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303086 {"keys", dictkeys_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 keys__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303088 {"items", dictitems_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 items__doc__},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303090 {"values", dictvalues_new, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 values__doc__},
3092 {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
3093 update__doc__},
Larry Hastings5c661892014-01-24 06:17:25 -08003094 DICT_FROMKEYS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
3096 clear__doc__},
3097 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
3098 copy__doc__},
3099 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003100};
3101
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00003102/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00003103int
3104PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003105{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003106 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07003107 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09003109 PyObject *value;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003112 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 hash = PyObject_Hash(key);
3114 if (hash == -1)
3115 return -1;
3116 }
INADA Naoki778928b2017-08-03 23:45:15 +09003117 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07003118 if (ix == DKIX_ERROR)
3119 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09003120 return (ix != DKIX_EMPTY && value != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003121}
3122
Thomas Wouterscf297e42007-02-23 15:07:44 +00003123/* Internal version of PyDict_Contains used when the hash value is already known */
3124int
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003125_PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00003126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09003128 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -07003129 Py_ssize_t ix;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003130
INADA Naoki778928b2017-08-03 23:45:15 +09003131 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value);
Victor Stinner742da042016-09-07 17:40:12 -07003132 if (ix == DKIX_ERROR)
3133 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09003134 return (ix != DKIX_EMPTY && value != NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00003135}
3136
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003137/* Hack to implement "key in dict" */
3138static PySequenceMethods dict_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 0, /* sq_length */
3140 0, /* sq_concat */
3141 0, /* sq_repeat */
3142 0, /* sq_item */
3143 0, /* sq_slice */
3144 0, /* sq_ass_item */
3145 0, /* sq_ass_slice */
3146 PyDict_Contains, /* sq_contains */
3147 0, /* sq_inplace_concat */
3148 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003149};
3150
Guido van Rossum09e563a2001-05-01 12:10:21 +00003151static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003152dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 PyObject *self;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003155 PyDictObject *d;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 assert(type != NULL && type->tp_alloc != NULL);
3158 self = type->tp_alloc(type, 0);
Victor Stinnera9f61a52013-07-16 22:17:26 +02003159 if (self == NULL)
3160 return NULL;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003161 d = (PyDictObject *)self;
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003162
Victor Stinnera9f61a52013-07-16 22:17:26 +02003163 /* The object has been implicitly tracked by tp_alloc */
3164 if (type == &PyDict_Type)
3165 _PyObject_GC_UNTRACK(d);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003166
3167 d->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07003168 d->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07003169 d->ma_keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003170 if (d->ma_keys == NULL) {
3171 Py_DECREF(self);
3172 return NULL;
3173 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02003174 assert(_PyDict_CheckConsistency(d));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 return self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003176}
3177
Tim Peters25786c02001-09-02 08:22:48 +00003178static int
3179dict_init(PyObject *self, PyObject *args, PyObject *kwds)
3180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00003182}
3183
Tim Peters6d6c1a32001-08-02 04:15:00 +00003184static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003185dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00003186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003188}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003189
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003190PyDoc_STRVAR(dictionary_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00003191"dict() -> new empty dictionary\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00003192"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003193" (key, value) pairs\n"
3194"dict(iterable) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00003195" d = {}\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003196" for k, v in iterable:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00003197" d[k] = v\n"
3198"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
3199" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00003200
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003201PyTypeObject PyDict_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3203 "dict",
3204 sizeof(PyDictObject),
3205 0,
3206 (destructor)dict_dealloc, /* tp_dealloc */
3207 0, /* tp_print */
3208 0, /* tp_getattr */
3209 0, /* tp_setattr */
3210 0, /* tp_reserved */
3211 (reprfunc)dict_repr, /* tp_repr */
3212 0, /* tp_as_number */
3213 &dict_as_sequence, /* tp_as_sequence */
3214 &dict_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003215 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 0, /* tp_call */
3217 0, /* tp_str */
3218 PyObject_GenericGetAttr, /* tp_getattro */
3219 0, /* tp_setattro */
3220 0, /* tp_as_buffer */
3221 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3222 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
3223 dictionary_doc, /* tp_doc */
3224 dict_traverse, /* tp_traverse */
3225 dict_tp_clear, /* tp_clear */
3226 dict_richcompare, /* tp_richcompare */
3227 0, /* tp_weaklistoffset */
3228 (getiterfunc)dict_iter, /* tp_iter */
3229 0, /* tp_iternext */
3230 mapp_methods, /* tp_methods */
3231 0, /* tp_members */
3232 0, /* tp_getset */
3233 0, /* tp_base */
3234 0, /* tp_dict */
3235 0, /* tp_descr_get */
3236 0, /* tp_descr_set */
3237 0, /* tp_dictoffset */
3238 dict_init, /* tp_init */
3239 PyType_GenericAlloc, /* tp_alloc */
3240 dict_new, /* tp_new */
3241 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003242};
3243
Victor Stinner3c1e4812012-03-26 22:10:51 +02003244PyObject *
3245_PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
3246{
3247 PyObject *kv;
3248 kv = _PyUnicode_FromId(key); /* borrowed */
Victor Stinner5b3b1002013-07-22 23:50:57 +02003249 if (kv == NULL) {
3250 PyErr_Clear();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003251 return NULL;
Victor Stinner5b3b1002013-07-22 23:50:57 +02003252 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003253 return PyDict_GetItem(dp, kv);
3254}
3255
Guido van Rossum3cca2451997-05-16 14:23:33 +00003256/* For backward compatibility with old dictionary interface */
3257
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003258PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003259PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 PyObject *kv, *rv;
3262 kv = PyUnicode_FromString(key);
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003263 if (kv == NULL) {
3264 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 return NULL;
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003266 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 rv = PyDict_GetItem(v, kv);
3268 Py_DECREF(kv);
3269 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003270}
3271
3272int
Victor Stinner3c1e4812012-03-26 22:10:51 +02003273_PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
3274{
3275 PyObject *kv;
3276 kv = _PyUnicode_FromId(key); /* borrowed */
3277 if (kv == NULL)
3278 return -1;
3279 return PyDict_SetItem(v, kv, item);
3280}
3281
3282int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003283PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 PyObject *kv;
3286 int err;
3287 kv = PyUnicode_FromString(key);
3288 if (kv == NULL)
3289 return -1;
3290 PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
3291 err = PyDict_SetItem(v, kv, item);
3292 Py_DECREF(kv);
3293 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003294}
3295
3296int
Victor Stinner5fd2e5a2013-11-06 18:58:22 +01003297_PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
3298{
3299 PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
3300 if (kv == NULL)
3301 return -1;
3302 return PyDict_DelItem(v, kv);
3303}
3304
3305int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003306PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 PyObject *kv;
3309 int err;
3310 kv = PyUnicode_FromString(key);
3311 if (kv == NULL)
3312 return -1;
3313 err = PyDict_DelItem(v, kv);
3314 Py_DECREF(kv);
3315 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003316}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003317
Raymond Hettinger019a1482004-03-18 02:41:19 +00003318/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003319
3320typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 PyObject_HEAD
3322 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
3323 Py_ssize_t di_used;
3324 Py_ssize_t di_pos;
3325 PyObject* di_result; /* reusable result tuple for iteritems */
3326 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003327} dictiterobject;
3328
3329static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003330dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 dictiterobject *di;
3333 di = PyObject_GC_New(dictiterobject, itertype);
3334 if (di == NULL)
3335 return NULL;
3336 Py_INCREF(dict);
3337 di->di_dict = dict;
3338 di->di_used = dict->ma_used;
3339 di->di_pos = 0;
3340 di->len = dict->ma_used;
3341 if (itertype == &PyDictIterItem_Type) {
3342 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
3343 if (di->di_result == NULL) {
3344 Py_DECREF(di);
3345 return NULL;
3346 }
3347 }
3348 else
3349 di->di_result = NULL;
3350 _PyObject_GC_TRACK(di);
3351 return (PyObject *)di;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003352}
3353
3354static void
3355dictiter_dealloc(dictiterobject *di)
3356{
INADA Naokia6296d32017-08-24 14:55:17 +09003357 /* bpo-31095: UnTrack is needed before calling any callbacks */
3358 _PyObject_GC_UNTRACK(di);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 Py_XDECREF(di->di_dict);
3360 Py_XDECREF(di->di_result);
3361 PyObject_GC_Del(di);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003362}
3363
3364static int
3365dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
3366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 Py_VISIT(di->di_dict);
3368 Py_VISIT(di->di_result);
3369 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003370}
3371
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003372static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303373dictiter_len(dictiterobject *di, PyObject *Py_UNUSED(ignored))
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 Py_ssize_t len = 0;
3376 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
3377 len = di->len;
3378 return PyLong_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003379}
3380
Guido van Rossumb90c8482007-02-10 01:11:45 +00003381PyDoc_STRVAR(length_hint_doc,
3382 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003383
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003384static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303385dictiter_reduce(dictiterobject *di, PyObject *Py_UNUSED(ignored));
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003386
3387PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3388
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003389static PyMethodDef dictiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS,
3391 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003392 {"__reduce__", (PyCFunction)dictiter_reduce, METH_NOARGS,
3393 reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003395};
3396
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003397static PyObject*
3398dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00003399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003400 PyObject *key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003401 Py_ssize_t i;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003402 PyDictKeysObject *k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 PyDictObject *d = di->di_dict;
Guido van Rossum213c7a62001-04-23 14:08:49 +00003404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 if (d == NULL)
3406 return NULL;
3407 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00003408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 if (di->di_used != d->ma_used) {
3410 PyErr_SetString(PyExc_RuntimeError,
3411 "dictionary changed size during iteration");
3412 di->di_used = -1; /* Make this state sticky */
3413 return NULL;
3414 }
Guido van Rossum2147df72002-07-16 20:30:22 +00003415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 i = di->di_pos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003417 k = d->ma_keys;
INADA Naokica2d8be2016-11-04 16:59:10 +09003418 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003419 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003420 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003421 goto fail;
3422 key = DK_ENTRIES(k)[i].me_key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003423 assert(d->ma_values[i] != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003424 }
3425 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003426 Py_ssize_t n = k->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003427 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
3428 while (i < n && entry_ptr->me_value == NULL) {
3429 entry_ptr++;
3430 i++;
3431 }
3432 if (i >= n)
3433 goto fail;
3434 key = entry_ptr->me_key;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003435 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 di->di_pos = i+1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 di->len--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 Py_INCREF(key);
3439 return key;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003440
3441fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003443 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003445}
3446
Raymond Hettinger019a1482004-03-18 02:41:19 +00003447PyTypeObject PyDictIterKey_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3449 "dict_keyiterator", /* tp_name */
3450 sizeof(dictiterobject), /* tp_basicsize */
3451 0, /* tp_itemsize */
3452 /* methods */
3453 (destructor)dictiter_dealloc, /* tp_dealloc */
3454 0, /* tp_print */
3455 0, /* tp_getattr */
3456 0, /* tp_setattr */
3457 0, /* tp_reserved */
3458 0, /* tp_repr */
3459 0, /* tp_as_number */
3460 0, /* tp_as_sequence */
3461 0, /* tp_as_mapping */
3462 0, /* tp_hash */
3463 0, /* tp_call */
3464 0, /* tp_str */
3465 PyObject_GenericGetAttr, /* tp_getattro */
3466 0, /* tp_setattro */
3467 0, /* tp_as_buffer */
3468 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3469 0, /* tp_doc */
3470 (traverseproc)dictiter_traverse, /* tp_traverse */
3471 0, /* tp_clear */
3472 0, /* tp_richcompare */
3473 0, /* tp_weaklistoffset */
3474 PyObject_SelfIter, /* tp_iter */
3475 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
3476 dictiter_methods, /* tp_methods */
3477 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003478};
3479
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003480static PyObject *
3481dictiter_iternextvalue(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 PyObject *value;
INADA Naokica2d8be2016-11-04 16:59:10 +09003484 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003485 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 if (d == NULL)
3488 return NULL;
3489 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 if (di->di_used != d->ma_used) {
3492 PyErr_SetString(PyExc_RuntimeError,
3493 "dictionary changed size during iteration");
3494 di->di_used = -1; /* Make this state sticky */
3495 return NULL;
3496 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 i = di->di_pos;
INADA Naokica2d8be2016-11-04 16:59:10 +09003499 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003500 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003501 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003502 goto fail;
INADA Naokica2d8be2016-11-04 16:59:10 +09003503 value = d->ma_values[i];
3504 assert(value != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003505 }
3506 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003507 Py_ssize_t n = d->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003508 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3509 while (i < n && entry_ptr->me_value == NULL) {
3510 entry_ptr++;
3511 i++;
3512 }
3513 if (i >= n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 goto fail;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003515 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 }
3517 di->di_pos = i+1;
3518 di->len--;
3519 Py_INCREF(value);
3520 return value;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003521
3522fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003524 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003526}
3527
3528PyTypeObject PyDictIterValue_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3530 "dict_valueiterator", /* tp_name */
3531 sizeof(dictiterobject), /* tp_basicsize */
3532 0, /* tp_itemsize */
3533 /* methods */
3534 (destructor)dictiter_dealloc, /* tp_dealloc */
3535 0, /* tp_print */
3536 0, /* tp_getattr */
3537 0, /* tp_setattr */
3538 0, /* tp_reserved */
3539 0, /* tp_repr */
3540 0, /* tp_as_number */
3541 0, /* tp_as_sequence */
3542 0, /* tp_as_mapping */
3543 0, /* tp_hash */
3544 0, /* tp_call */
3545 0, /* tp_str */
3546 PyObject_GenericGetAttr, /* tp_getattro */
3547 0, /* tp_setattro */
3548 0, /* tp_as_buffer */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003549 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 0, /* tp_doc */
3551 (traverseproc)dictiter_traverse, /* tp_traverse */
3552 0, /* tp_clear */
3553 0, /* tp_richcompare */
3554 0, /* tp_weaklistoffset */
3555 PyObject_SelfIter, /* tp_iter */
3556 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
3557 dictiter_methods, /* tp_methods */
3558 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003559};
3560
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003561static PyObject *
3562dictiter_iternextitem(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003563{
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003564 PyObject *key, *value, *result;
INADA Naokica2d8be2016-11-04 16:59:10 +09003565 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 if (d == NULL)
3569 return NULL;
3570 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 if (di->di_used != d->ma_used) {
3573 PyErr_SetString(PyExc_RuntimeError,
3574 "dictionary changed size during iteration");
3575 di->di_used = -1; /* Make this state sticky */
3576 return NULL;
3577 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 i = di->di_pos;
INADA Naokica2d8be2016-11-04 16:59:10 +09003580 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003581 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003582 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003583 goto fail;
3584 key = DK_ENTRIES(d->ma_keys)[i].me_key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003585 value = d->ma_values[i];
3586 assert(value != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003587 }
3588 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003589 Py_ssize_t n = d->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003590 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3591 while (i < n && entry_ptr->me_value == NULL) {
3592 entry_ptr++;
3593 i++;
3594 }
3595 if (i >= n)
3596 goto fail;
3597 key = entry_ptr->me_key;
3598 value = entry_ptr->me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003599 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 di->di_pos = i+1;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003601 di->len--;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003602 Py_INCREF(key);
3603 Py_INCREF(value);
3604 result = di->di_result;
3605 if (Py_REFCNT(result) == 1) {
3606 PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
3607 PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
3608 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3609 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 Py_INCREF(result);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003611 Py_DECREF(oldkey);
3612 Py_DECREF(oldvalue);
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003613 }
3614 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 result = PyTuple_New(2);
3616 if (result == NULL)
3617 return NULL;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003618 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3619 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003622
3623fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003625 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003627}
3628
3629PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3631 "dict_itemiterator", /* tp_name */
3632 sizeof(dictiterobject), /* tp_basicsize */
3633 0, /* tp_itemsize */
3634 /* methods */
3635 (destructor)dictiter_dealloc, /* tp_dealloc */
3636 0, /* tp_print */
3637 0, /* tp_getattr */
3638 0, /* tp_setattr */
3639 0, /* tp_reserved */
3640 0, /* tp_repr */
3641 0, /* tp_as_number */
3642 0, /* tp_as_sequence */
3643 0, /* tp_as_mapping */
3644 0, /* tp_hash */
3645 0, /* tp_call */
3646 0, /* tp_str */
3647 PyObject_GenericGetAttr, /* tp_getattro */
3648 0, /* tp_setattro */
3649 0, /* tp_as_buffer */
3650 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3651 0, /* tp_doc */
3652 (traverseproc)dictiter_traverse, /* tp_traverse */
3653 0, /* tp_clear */
3654 0, /* tp_richcompare */
3655 0, /* tp_weaklistoffset */
3656 PyObject_SelfIter, /* tp_iter */
3657 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
3658 dictiter_methods, /* tp_methods */
3659 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003660};
Guido van Rossumb90c8482007-02-10 01:11:45 +00003661
3662
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003663static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303664dictiter_reduce(dictiterobject *di, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003665{
Sergey Fedoseev63958442018-10-20 05:43:33 +05003666 /* copy the iterator state */
3667 dictiterobject tmp = *di;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003668 Py_XINCREF(tmp.di_dict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003669
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003670 /* iterate the temporary into a list */
Sergey Fedoseev63958442018-10-20 05:43:33 +05003671 PyObject *list = PySequence_List((PyObject*)&tmp);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003672 Py_XDECREF(tmp.di_dict);
Sergey Fedoseev63958442018-10-20 05:43:33 +05003673 if (list == NULL) {
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003674 return NULL;
3675 }
Antoine Pitroua7013882012-04-05 00:04:20 +02003676 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003677}
3678
Guido van Rossum3ac67412007-02-10 18:55:06 +00003679/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003680/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00003681/***********************************************/
3682
Guido van Rossumb90c8482007-02-10 01:11:45 +00003683/* The instance lay-out is the same for all three; but the type differs. */
3684
Guido van Rossumb90c8482007-02-10 01:11:45 +00003685static void
Eric Snow96c6af92015-05-29 22:21:39 -06003686dictview_dealloc(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003687{
INADA Naokia6296d32017-08-24 14:55:17 +09003688 /* bpo-31095: UnTrack is needed before calling any callbacks */
3689 _PyObject_GC_UNTRACK(dv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 Py_XDECREF(dv->dv_dict);
3691 PyObject_GC_Del(dv);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003692}
3693
3694static int
Eric Snow96c6af92015-05-29 22:21:39 -06003695dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 Py_VISIT(dv->dv_dict);
3698 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003699}
3700
Guido van Rossum83825ac2007-02-10 04:54:19 +00003701static Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003702dictview_len(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003704 Py_ssize_t len = 0;
3705 if (dv->dv_dict != NULL)
3706 len = dv->dv_dict->ma_used;
3707 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003708}
3709
Eric Snow96c6af92015-05-29 22:21:39 -06003710PyObject *
3711_PyDictView_New(PyObject *dict, PyTypeObject *type)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003712{
Eric Snow96c6af92015-05-29 22:21:39 -06003713 _PyDictViewObject *dv;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714 if (dict == NULL) {
3715 PyErr_BadInternalCall();
3716 return NULL;
3717 }
3718 if (!PyDict_Check(dict)) {
3719 /* XXX Get rid of this restriction later */
3720 PyErr_Format(PyExc_TypeError,
3721 "%s() requires a dict argument, not '%s'",
3722 type->tp_name, dict->ob_type->tp_name);
3723 return NULL;
3724 }
Eric Snow96c6af92015-05-29 22:21:39 -06003725 dv = PyObject_GC_New(_PyDictViewObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003726 if (dv == NULL)
3727 return NULL;
3728 Py_INCREF(dict);
3729 dv->dv_dict = (PyDictObject *)dict;
3730 _PyObject_GC_TRACK(dv);
3731 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003732}
3733
Neal Norwitze36f2ba2007-02-26 23:12:28 +00003734/* TODO(guido): The views objects are not complete:
3735
3736 * support more set operations
3737 * support arbitrary mappings?
3738 - either these should be static or exported in dictobject.h
3739 - if public then they should probably be in builtins
3740*/
3741
Guido van Rossumaac530c2007-08-24 22:33:45 +00003742/* Return 1 if self is a subset of other, iterating over self;
3743 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00003744static int
3745all_contained_in(PyObject *self, PyObject *other)
3746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003747 PyObject *iter = PyObject_GetIter(self);
3748 int ok = 1;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 if (iter == NULL)
3751 return -1;
3752 for (;;) {
3753 PyObject *next = PyIter_Next(iter);
3754 if (next == NULL) {
3755 if (PyErr_Occurred())
3756 ok = -1;
3757 break;
3758 }
3759 ok = PySequence_Contains(other, next);
3760 Py_DECREF(next);
3761 if (ok <= 0)
3762 break;
3763 }
3764 Py_DECREF(iter);
3765 return ok;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003766}
3767
3768static PyObject *
3769dictview_richcompare(PyObject *self, PyObject *other, int op)
3770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 Py_ssize_t len_self, len_other;
3772 int ok;
3773 PyObject *result;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 assert(self != NULL);
3776 assert(PyDictViewSet_Check(self));
3777 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00003778
Brian Curtindfc80e32011-08-10 20:28:54 -05003779 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
3780 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 len_self = PyObject_Size(self);
3783 if (len_self < 0)
3784 return NULL;
3785 len_other = PyObject_Size(other);
3786 if (len_other < 0)
3787 return NULL;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003789 ok = 0;
3790 switch(op) {
Guido van Rossumaac530c2007-08-24 22:33:45 +00003791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 case Py_NE:
3793 case Py_EQ:
3794 if (len_self == len_other)
3795 ok = all_contained_in(self, other);
3796 if (op == Py_NE && ok >= 0)
3797 ok = !ok;
3798 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 case Py_LT:
3801 if (len_self < len_other)
3802 ok = all_contained_in(self, other);
3803 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003805 case Py_LE:
3806 if (len_self <= len_other)
3807 ok = all_contained_in(self, other);
3808 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003810 case Py_GT:
3811 if (len_self > len_other)
3812 ok = all_contained_in(other, self);
3813 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 case Py_GE:
3816 if (len_self >= len_other)
3817 ok = all_contained_in(other, self);
3818 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 }
3821 if (ok < 0)
3822 return NULL;
3823 result = ok ? Py_True : Py_False;
3824 Py_INCREF(result);
3825 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003826}
3827
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003828static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003829dictview_repr(_PyDictViewObject *dv)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 PyObject *seq;
bennorthd7773d92018-01-26 15:46:01 +00003832 PyObject *result = NULL;
3833 Py_ssize_t rc;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003834
bennorthd7773d92018-01-26 15:46:01 +00003835 rc = Py_ReprEnter((PyObject *)dv);
3836 if (rc != 0) {
3837 return rc > 0 ? PyUnicode_FromString("...") : NULL;
3838 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 seq = PySequence_List((PyObject *)dv);
bennorthd7773d92018-01-26 15:46:01 +00003840 if (seq == NULL) {
3841 goto Done;
3842 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
3844 Py_DECREF(seq);
bennorthd7773d92018-01-26 15:46:01 +00003845
3846Done:
3847 Py_ReprLeave((PyObject *)dv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 return result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003849}
3850
Guido van Rossum3ac67412007-02-10 18:55:06 +00003851/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003852
3853static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003854dictkeys_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003856 if (dv->dv_dict == NULL) {
3857 Py_RETURN_NONE;
3858 }
3859 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003860}
3861
3862static int
Eric Snow96c6af92015-05-29 22:21:39 -06003863dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00003864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 if (dv->dv_dict == NULL)
3866 return 0;
3867 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003868}
3869
Guido van Rossum83825ac2007-02-10 04:54:19 +00003870static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 (lenfunc)dictview_len, /* sq_length */
3872 0, /* sq_concat */
3873 0, /* sq_repeat */
3874 0, /* sq_item */
3875 0, /* sq_slice */
3876 0, /* sq_ass_item */
3877 0, /* sq_ass_slice */
3878 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003879};
3880
Guido van Rossum523259b2007-08-24 23:41:22 +00003881static PyObject*
3882dictviews_sub(PyObject* self, PyObject *other)
3883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 PyObject *result = PySet_New(self);
3885 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003886 _Py_IDENTIFIER(difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 if (result == NULL)
3889 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003890
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003891 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 if (tmp == NULL) {
3893 Py_DECREF(result);
3894 return NULL;
3895 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 Py_DECREF(tmp);
3898 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003899}
3900
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003901PyObject*
3902_PyDictView_Intersect(PyObject* self, PyObject *other)
Guido van Rossum523259b2007-08-24 23:41:22 +00003903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 PyObject *result = PySet_New(self);
3905 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003906 _Py_IDENTIFIER(intersection_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 if (result == NULL)
3909 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003910
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003911 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_intersection_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 if (tmp == NULL) {
3913 Py_DECREF(result);
3914 return NULL;
3915 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003917 Py_DECREF(tmp);
3918 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003919}
3920
3921static PyObject*
3922dictviews_or(PyObject* self, PyObject *other)
3923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 PyObject *result = PySet_New(self);
3925 PyObject *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02003926 _Py_IDENTIFIER(update);
Victor Stinnerd1a9cc22011-10-13 22:51:17 +02003927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 if (result == NULL)
3929 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003930
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003931 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 if (tmp == NULL) {
3933 Py_DECREF(result);
3934 return NULL;
3935 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 Py_DECREF(tmp);
3938 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003939}
3940
3941static PyObject*
3942dictviews_xor(PyObject* self, PyObject *other)
3943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 PyObject *result = PySet_New(self);
3945 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003946 _Py_IDENTIFIER(symmetric_difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 if (result == NULL)
3949 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003950
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003951 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_symmetric_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 if (tmp == NULL) {
3953 Py_DECREF(result);
3954 return NULL;
3955 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003957 Py_DECREF(tmp);
3958 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003959}
3960
3961static PyNumberMethods dictviews_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 0, /*nb_add*/
3963 (binaryfunc)dictviews_sub, /*nb_subtract*/
3964 0, /*nb_multiply*/
3965 0, /*nb_remainder*/
3966 0, /*nb_divmod*/
3967 0, /*nb_power*/
3968 0, /*nb_negative*/
3969 0, /*nb_positive*/
3970 0, /*nb_absolute*/
3971 0, /*nb_bool*/
3972 0, /*nb_invert*/
3973 0, /*nb_lshift*/
3974 0, /*nb_rshift*/
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003975 (binaryfunc)_PyDictView_Intersect, /*nb_and*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 (binaryfunc)dictviews_xor, /*nb_xor*/
3977 (binaryfunc)dictviews_or, /*nb_or*/
Guido van Rossum523259b2007-08-24 23:41:22 +00003978};
3979
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003980static PyObject*
3981dictviews_isdisjoint(PyObject *self, PyObject *other)
3982{
3983 PyObject *it;
3984 PyObject *item = NULL;
3985
3986 if (self == other) {
Eric Snow96c6af92015-05-29 22:21:39 -06003987 if (dictview_len((_PyDictViewObject *)self) == 0)
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003988 Py_RETURN_TRUE;
3989 else
3990 Py_RETURN_FALSE;
3991 }
3992
3993 /* Iterate over the shorter object (only if other is a set,
3994 * because PySequence_Contains may be expensive otherwise): */
3995 if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
Eric Snow96c6af92015-05-29 22:21:39 -06003996 Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003997 Py_ssize_t len_other = PyObject_Size(other);
3998 if (len_other == -1)
3999 return NULL;
4000
4001 if ((len_other > len_self)) {
4002 PyObject *tmp = other;
4003 other = self;
4004 self = tmp;
4005 }
4006 }
4007
4008 it = PyObject_GetIter(other);
4009 if (it == NULL)
4010 return NULL;
4011
4012 while ((item = PyIter_Next(it)) != NULL) {
4013 int contains = PySequence_Contains(self, item);
4014 Py_DECREF(item);
4015 if (contains == -1) {
4016 Py_DECREF(it);
4017 return NULL;
4018 }
4019
4020 if (contains) {
4021 Py_DECREF(it);
4022 Py_RETURN_FALSE;
4023 }
4024 }
4025 Py_DECREF(it);
4026 if (PyErr_Occurred())
4027 return NULL; /* PyIter_Next raised an exception. */
4028 Py_RETURN_TRUE;
4029}
4030
4031PyDoc_STRVAR(isdisjoint_doc,
4032"Return True if the view and the given iterable have a null intersection.");
4033
Guido van Rossumb90c8482007-02-10 01:11:45 +00004034static PyMethodDef dictkeys_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004035 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4036 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004037 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004038};
4039
4040PyTypeObject PyDictKeys_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4042 "dict_keys", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004043 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 0, /* tp_itemsize */
4045 /* methods */
4046 (destructor)dictview_dealloc, /* tp_dealloc */
4047 0, /* tp_print */
4048 0, /* tp_getattr */
4049 0, /* tp_setattr */
4050 0, /* tp_reserved */
4051 (reprfunc)dictview_repr, /* tp_repr */
4052 &dictviews_as_number, /* tp_as_number */
4053 &dictkeys_as_sequence, /* tp_as_sequence */
4054 0, /* tp_as_mapping */
4055 0, /* tp_hash */
4056 0, /* tp_call */
4057 0, /* tp_str */
4058 PyObject_GenericGetAttr, /* tp_getattro */
4059 0, /* tp_setattro */
4060 0, /* tp_as_buffer */
4061 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4062 0, /* tp_doc */
4063 (traverseproc)dictview_traverse, /* tp_traverse */
4064 0, /* tp_clear */
4065 dictview_richcompare, /* tp_richcompare */
4066 0, /* tp_weaklistoffset */
4067 (getiterfunc)dictkeys_iter, /* tp_iter */
4068 0, /* tp_iternext */
4069 dictkeys_methods, /* tp_methods */
4070 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004071};
4072
4073static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304074dictkeys_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004075{
Eric Snow96c6af92015-05-29 22:21:39 -06004076 return _PyDictView_New(dict, &PyDictKeys_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004077}
4078
Guido van Rossum3ac67412007-02-10 18:55:06 +00004079/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004080
4081static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004082dictitems_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004083{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004084 if (dv->dv_dict == NULL) {
4085 Py_RETURN_NONE;
4086 }
4087 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00004088}
4089
4090static int
Eric Snow96c6af92015-05-29 22:21:39 -06004091dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00004092{
Serhiy Storchaka753bca32017-05-20 12:30:02 +03004093 int result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 PyObject *key, *value, *found;
4095 if (dv->dv_dict == NULL)
4096 return 0;
4097 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
4098 return 0;
4099 key = PyTuple_GET_ITEM(obj, 0);
4100 value = PyTuple_GET_ITEM(obj, 1);
Raymond Hettinger6692f012016-09-18 21:46:08 -07004101 found = PyDict_GetItemWithError((PyObject *)dv->dv_dict, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 if (found == NULL) {
4103 if (PyErr_Occurred())
4104 return -1;
4105 return 0;
4106 }
Serhiy Storchaka753bca32017-05-20 12:30:02 +03004107 Py_INCREF(found);
4108 result = PyObject_RichCompareBool(value, found, Py_EQ);
4109 Py_DECREF(found);
4110 return result;
Guido van Rossumb90c8482007-02-10 01:11:45 +00004111}
4112
Guido van Rossum83825ac2007-02-10 04:54:19 +00004113static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004114 (lenfunc)dictview_len, /* sq_length */
4115 0, /* sq_concat */
4116 0, /* sq_repeat */
4117 0, /* sq_item */
4118 0, /* sq_slice */
4119 0, /* sq_ass_item */
4120 0, /* sq_ass_slice */
4121 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004122};
4123
Guido van Rossumb90c8482007-02-10 01:11:45 +00004124static PyMethodDef dictitems_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004125 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4126 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004128};
4129
4130PyTypeObject PyDictItems_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004131 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4132 "dict_items", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004133 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 0, /* tp_itemsize */
4135 /* methods */
4136 (destructor)dictview_dealloc, /* tp_dealloc */
4137 0, /* tp_print */
4138 0, /* tp_getattr */
4139 0, /* tp_setattr */
4140 0, /* tp_reserved */
4141 (reprfunc)dictview_repr, /* tp_repr */
4142 &dictviews_as_number, /* tp_as_number */
4143 &dictitems_as_sequence, /* tp_as_sequence */
4144 0, /* tp_as_mapping */
4145 0, /* tp_hash */
4146 0, /* tp_call */
4147 0, /* tp_str */
4148 PyObject_GenericGetAttr, /* tp_getattro */
4149 0, /* tp_setattro */
4150 0, /* tp_as_buffer */
4151 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4152 0, /* tp_doc */
4153 (traverseproc)dictview_traverse, /* tp_traverse */
4154 0, /* tp_clear */
4155 dictview_richcompare, /* tp_richcompare */
4156 0, /* tp_weaklistoffset */
4157 (getiterfunc)dictitems_iter, /* tp_iter */
4158 0, /* tp_iternext */
4159 dictitems_methods, /* tp_methods */
4160 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004161};
4162
4163static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304164dictitems_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004165{
Eric Snow96c6af92015-05-29 22:21:39 -06004166 return _PyDictView_New(dict, &PyDictItems_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004167}
4168
Guido van Rossum3ac67412007-02-10 18:55:06 +00004169/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004170
4171static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004172dictvalues_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004174 if (dv->dv_dict == NULL) {
4175 Py_RETURN_NONE;
4176 }
4177 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004178}
4179
Guido van Rossum83825ac2007-02-10 04:54:19 +00004180static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004181 (lenfunc)dictview_len, /* sq_length */
4182 0, /* sq_concat */
4183 0, /* sq_repeat */
4184 0, /* sq_item */
4185 0, /* sq_slice */
4186 0, /* sq_ass_item */
4187 0, /* sq_ass_slice */
4188 (objobjproc)0, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004189};
4190
Guido van Rossumb90c8482007-02-10 01:11:45 +00004191static PyMethodDef dictvalues_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004192 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004193};
4194
4195PyTypeObject PyDictValues_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004196 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4197 "dict_values", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004198 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004199 0, /* tp_itemsize */
4200 /* methods */
4201 (destructor)dictview_dealloc, /* tp_dealloc */
4202 0, /* tp_print */
4203 0, /* tp_getattr */
4204 0, /* tp_setattr */
4205 0, /* tp_reserved */
4206 (reprfunc)dictview_repr, /* tp_repr */
4207 0, /* tp_as_number */
4208 &dictvalues_as_sequence, /* tp_as_sequence */
4209 0, /* tp_as_mapping */
4210 0, /* tp_hash */
4211 0, /* tp_call */
4212 0, /* tp_str */
4213 PyObject_GenericGetAttr, /* tp_getattro */
4214 0, /* tp_setattro */
4215 0, /* tp_as_buffer */
4216 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4217 0, /* tp_doc */
4218 (traverseproc)dictview_traverse, /* tp_traverse */
4219 0, /* tp_clear */
4220 0, /* tp_richcompare */
4221 0, /* tp_weaklistoffset */
4222 (getiterfunc)dictvalues_iter, /* tp_iter */
4223 0, /* tp_iternext */
4224 dictvalues_methods, /* tp_methods */
4225 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004226};
4227
4228static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05304229dictvalues_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
Guido van Rossumb90c8482007-02-10 01:11:45 +00004230{
Eric Snow96c6af92015-05-29 22:21:39 -06004231 return _PyDictView_New(dict, &PyDictValues_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004232}
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004233
4234/* Returns NULL if cannot allocate a new PyDictKeysObject,
4235 but does not set an error */
4236PyDictKeysObject *
4237_PyDict_NewKeysForClass(void)
4238{
Victor Stinner742da042016-09-07 17:40:12 -07004239 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004240 if (keys == NULL)
4241 PyErr_Clear();
4242 else
4243 keys->dk_lookup = lookdict_split;
4244 return keys;
4245}
4246
4247#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
4248
4249PyObject *
4250PyObject_GenericGetDict(PyObject *obj, void *context)
4251{
4252 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
4253 if (dictptr == NULL) {
4254 PyErr_SetString(PyExc_AttributeError,
4255 "This object has no __dict__");
4256 return NULL;
4257 }
4258 dict = *dictptr;
4259 if (dict == NULL) {
4260 PyTypeObject *tp = Py_TYPE(obj);
4261 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
4262 DK_INCREF(CACHED_KEYS(tp));
4263 *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
4264 }
4265 else {
4266 *dictptr = dict = PyDict_New();
4267 }
4268 }
4269 Py_XINCREF(dict);
4270 return dict;
4271}
4272
4273int
4274_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
Victor Stinner742da042016-09-07 17:40:12 -07004275 PyObject *key, PyObject *value)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004276{
4277 PyObject *dict;
4278 int res;
4279 PyDictKeysObject *cached;
4280
4281 assert(dictptr != NULL);
4282 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
4283 assert(dictptr != NULL);
4284 dict = *dictptr;
4285 if (dict == NULL) {
4286 DK_INCREF(cached);
4287 dict = new_dict_with_shared_keys(cached);
4288 if (dict == NULL)
4289 return -1;
4290 *dictptr = dict;
4291 }
4292 if (value == NULL) {
4293 res = PyDict_DelItem(dict, key);
INADA Naoki2294f3a2017-02-12 13:51:30 +09004294 // Since key sharing dict doesn't allow deletion, PyDict_DelItem()
4295 // always converts dict to combined form.
4296 if ((cached = CACHED_KEYS(tp)) != NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004297 CACHED_KEYS(tp) = NULL;
4298 DK_DECREF(cached);
4299 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01004300 }
4301 else {
INADA Naoki2294f3a2017-02-12 13:51:30 +09004302 int was_shared = (cached == ((PyDictObject *)dict)->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004303 res = PyDict_SetItem(dict, key, value);
INADA Naoki2294f3a2017-02-12 13:51:30 +09004304 if (was_shared &&
4305 (cached = CACHED_KEYS(tp)) != NULL &&
4306 cached != ((PyDictObject *)dict)->ma_keys) {
Victor Stinner3d3f2642016-12-15 17:21:23 +01004307 /* PyDict_SetItem() may call dictresize and convert split table
4308 * into combined table. In such case, convert it to split
4309 * table again and update type's shared key only when this is
4310 * the only dict sharing key with the type.
4311 *
4312 * This is to allow using shared key in class like this:
4313 *
4314 * class C:
4315 * def __init__(self):
4316 * # one dict resize happens
4317 * self.a, self.b, self.c = 1, 2, 3
4318 * self.d, self.e, self.f = 4, 5, 6
4319 * a = C()
4320 */
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004321 if (cached->dk_refcnt == 1) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004322 CACHED_KEYS(tp) = make_keys_shared(dict);
Victor Stinner742da042016-09-07 17:40:12 -07004323 }
4324 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004325 CACHED_KEYS(tp) = NULL;
4326 }
4327 DK_DECREF(cached);
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004328 if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
4329 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004330 }
4331 }
4332 } else {
4333 dict = *dictptr;
4334 if (dict == NULL) {
4335 dict = PyDict_New();
4336 if (dict == NULL)
4337 return -1;
4338 *dictptr = dict;
4339 }
4340 if (value == NULL) {
4341 res = PyDict_DelItem(dict, key);
4342 } else {
4343 res = PyDict_SetItem(dict, key, value);
4344 }
4345 }
4346 return res;
4347}
4348
4349void
4350_PyDictKeys_DecRef(PyDictKeysObject *keys)
4351{
4352 DK_DECREF(keys);
4353}