blob: b0f583a067b4e196da36afcb9b1014e33fabd63f [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
Berker Peksag71c01d42016-09-09 03:57:23 +030013As of Python 3.6, this is compact and ordered. Basic idea is described here.
Benjamin Peterson003f0592016-09-08 10:14:31 -070014https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html
Victor Stinner742da042016-09-07 17:40:12 -070015
16layout:
17
18+---------------+
19| dk_refcnt |
20| dk_size |
21| dk_lookup |
22| dk_usable |
23| dk_nentries |
24+---------------+
25| dk_indices |
26| |
27+---------------+
28| dk_entries |
29| |
30+---------------+
31
32dk_indices is actual hashtable. It holds index in entries, or DKIX_EMPTY(-1)
33or DKIX_DUMMY(-2).
34Size of indices is dk_size. Type of each index in indices is vary on dk_size:
35
36* int8 for dk_size <= 128
37* int16 for 256 <= dk_size <= 2**15
38* int32 for 2**16 <= dk_size <= 2**31
39* int64 for 2**32 <= dk_size
40
41dk_entries is array of PyDictKeyEntry. It's size is USABLE_FRACTION(dk_size).
42DK_ENTRIES(dk) can be used to get pointer to entries.
43
44NOTE: Since negative value is used for DKIX_EMPTY and DKIX_DUMMY, type of
45dk_indices entry is signed integer and int16 is used for table which
46dk_size == 256.
47*/
48
Benjamin Peterson7d95e402012-04-23 11:24:50 -040049
50/*
Benjamin Peterson7d95e402012-04-23 11:24:50 -040051The DictObject can be in one of two forms.
Victor Stinner742da042016-09-07 17:40:12 -070052
Benjamin Peterson7d95e402012-04-23 11:24:50 -040053Either:
54 A combined table:
55 ma_values == NULL, dk_refcnt == 1.
56 Values are stored in the me_value field of the PyDictKeysObject.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040057Or:
58 A split table:
59 ma_values != NULL, dk_refcnt >= 1
60 Values are stored in the ma_values array.
Victor Stinner742da042016-09-07 17:40:12 -070061 Only string (unicode) keys are allowed.
62 All dicts sharing same key must have same insertion order.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040063
Victor Stinner742da042016-09-07 17:40:12 -070064There are four kinds of slots in the table (slot is index, and
65DK_ENTRIES(keys)[index] if index >= 0):
66
671. Unused. index == DKIX_EMPTY
68 Does not hold an active (key, value) pair now and never did. Unused can
69 transition to Active upon key insertion. This is each slot's initial state.
70
712. Active. index >= 0, me_key != NULL and me_value != NULL
72 Holds an active (key, value) pair. Active can transition to Dummy or
73 Pending upon key deletion (for combined and split tables respectively).
74 This is the only case in which me_value != NULL.
75
763. Dummy. index == DKIX_DUMMY (combined only)
77 Previously held an active (key, value) pair, but that was deleted and an
78 active pair has not yet overwritten the slot. Dummy can transition to
79 Active upon key insertion. Dummy slots cannot be made Unused again
80 else the probe sequence in case of collision would have no way to know
81 they were once active.
82
834. Pending. index >= 0, key != NULL, and value == NULL (split only)
84 Not yet inserted in split-table.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040085*/
86
Victor Stinner742da042016-09-07 17:40:12 -070087/*
88Preserving insertion order
Benjamin Peterson7d95e402012-04-23 11:24:50 -040089
Victor Stinner742da042016-09-07 17:40:12 -070090It's simple for combined table. Since dk_entries is mostly append only, we can
91get insertion order by just iterating dk_entries.
92
93One exception is .popitem(). It removes last item in dk_entries and decrement
94dk_nentries to achieve amortized O(1). Since there are DKIX_DUMMY remains in
95dk_indices, we can't increment dk_usable even though dk_nentries is
96decremented.
97
98In split table, inserting into pending entry is allowed only for dk_entries[ix]
99where ix == mp->ma_used. Inserting into other index and deleting item cause
100converting the dict to the combined table.
101*/
102
103/* PyDict_MINSIZE is the starting size for any new dict.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400104 * 8 allows dicts with no more than 5 active entries; experiments suggested
105 * this suffices for the majority of dicts (consisting mostly of usually-small
106 * dicts created to pass keyword arguments).
107 * Making this 8, rather than 4 reduces the number of resizes for most
108 * dictionaries, without any significant extra memory use.
109 */
Victor Stinner742da042016-09-07 17:40:12 -0700110#define PyDict_MINSIZE 8
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400111
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112#include "Python.h"
Eric Snow96c6af92015-05-29 22:21:39 -0600113#include "dict-common.h"
Victor Stinner990397e2016-09-09 20:22:59 -0700114#include "stringlib/eq.h" /* to get unicode_eq() */
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000115
Larry Hastings61272b72014-01-07 12:41:53 -0800116/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -0800117class dict "PyDictObject *" "&PyDict_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800118[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -0800119/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f157a5a0ce9589d6]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800120
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400121
122/*
123To ensure the lookup algorithm terminates, there must be at least one Unused
124slot (NULL key) in the table.
125To avoid slowing down lookups on a near-full table, we resize the table when
126it's USABLE_FRACTION (currently two-thirds) full.
127*/
Guido van Rossum16e93a81997-01-28 00:00:11 +0000128
Tim Peterseb28ef22001-06-02 05:27:19 +0000129#define PERTURB_SHIFT 5
130
Guido van Rossum16e93a81997-01-28 00:00:11 +0000131/*
Tim Peterseb28ef22001-06-02 05:27:19 +0000132Major subtleties ahead: Most hash schemes depend on having a "good" hash
133function, in the sense of simulating randomness. Python doesn't: its most
R David Murray537ad7a2016-07-10 12:33:18 -0400134important hash functions (for ints) are very regular in common
Tim Peterseb28ef22001-06-02 05:27:19 +0000135cases:
Tim Peters15d49292001-05-27 07:39:22 +0000136
R David Murray537ad7a2016-07-10 12:33:18 -0400137 >>>[hash(i) for i in range(4)]
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000138 [0, 1, 2, 3]
Tim Peters15d49292001-05-27 07:39:22 +0000139
Tim Peterseb28ef22001-06-02 05:27:19 +0000140This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
141the low-order i bits as the initial table index is extremely fast, and there
R David Murray537ad7a2016-07-10 12:33:18 -0400142are no collisions at all for dicts indexed by a contiguous range of ints. So
143this gives better-than-random behavior in common cases, and that's very
144desirable.
Tim Peters15d49292001-05-27 07:39:22 +0000145
Tim Peterseb28ef22001-06-02 05:27:19 +0000146OTOH, when collisions occur, the tendency to fill contiguous slices of the
147hash table makes a good collision resolution strategy crucial. Taking only
148the last i bits of the hash code is also vulnerable: for example, consider
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149the list [i << 16 for i in range(20000)] as a set of keys. Since ints are
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000150their own hash codes, and this fits in a dict of size 2**15, the last 15 bits
151 of every hash code are all 0: they *all* map to the same table index.
Tim Peters15d49292001-05-27 07:39:22 +0000152
Tim Peterseb28ef22001-06-02 05:27:19 +0000153But catering to unusual cases should not slow the usual ones, so we just take
154the last i bits anyway. It's up to collision resolution to do the rest. If
155we *usually* find the key we're looking for on the first try (and, it turns
156out, we usually do -- the table load factor is kept under 2/3, so the odds
157are solidly in our favor), then it makes best sense to keep the initial index
158computation dirt cheap.
Tim Peters15d49292001-05-27 07:39:22 +0000159
Tim Peterseb28ef22001-06-02 05:27:19 +0000160The first half of collision resolution is to visit table indices via this
161recurrence:
Tim Peters15d49292001-05-27 07:39:22 +0000162
Tim Peterseb28ef22001-06-02 05:27:19 +0000163 j = ((5*j) + 1) mod 2**i
Tim Peters15d49292001-05-27 07:39:22 +0000164
Tim Peterseb28ef22001-06-02 05:27:19 +0000165For any initial j in range(2**i), repeating that 2**i times generates each
166int in range(2**i) exactly once (see any text on random-number generation for
167proof). By itself, this doesn't help much: like linear probing (setting
168j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
169order. This would be bad, except that's not the only thing we do, and it's
170actually *good* in the common cases where hash keys are consecutive. In an
171example that's really too small to make this entirely clear, for a table of
172size 2**3 the order of indices is:
Tim Peters15d49292001-05-27 07:39:22 +0000173
Tim Peterseb28ef22001-06-02 05:27:19 +0000174 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
175
176If two things come in at index 5, the first place we look after is index 2,
177not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
178Linear probing is deadly in this case because there the fixed probe order
179is the *same* as the order consecutive keys are likely to arrive. But it's
180extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
181and certain that consecutive hash codes do not.
182
183The other half of the strategy is to get the other bits of the hash code
184into play. This is done by initializing a (unsigned) vrbl "perturb" to the
185full hash code, and changing the recurrence to:
186
Tim Peterseb28ef22001-06-02 05:27:19 +0000187 perturb >>= PERTURB_SHIFT;
INADA Naoki267941c2016-10-06 15:19:07 +0900188 j = (5*j) + 1 + perturb;
Tim Peterseb28ef22001-06-02 05:27:19 +0000189 use j % 2**i as the next table index;
190
191Now the probe sequence depends (eventually) on every bit in the hash code,
192and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
193because it quickly magnifies small differences in the bits that didn't affect
194the initial index. Note that because perturb is unsigned, if the recurrence
195is executed often enough perturb eventually becomes and remains 0. At that
196point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
197that's certain to find an empty slot eventually (since it generates every int
198in range(2**i), and we make sure there's always at least one empty slot).
199
200Selecting a good value for PERTURB_SHIFT is a balancing act. You want it
201small so that the high bits of the hash code continue to affect the probe
202sequence across iterations; but you want it large so that in really bad cases
203the high-order hash bits have an effect on early iterations. 5 was "the
204best" in minimizing total collisions across experiments Tim Peters ran (on
205both normal and pathological cases), but 4 and 6 weren't significantly worse.
206
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000207Historical: Reimer Behrends contributed the idea of using a polynomial-based
Tim Peterseb28ef22001-06-02 05:27:19 +0000208approach, using repeated multiplication by x in GF(2**n) where an irreducible
209polynomial for each table size was chosen such that x was a primitive root.
210Christian Tismer later extended that to use division by x instead, as an
211efficient way to get the high bits of the hash code into play. This scheme
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000212also gave excellent collision statistics, but was more expensive: two
213if-tests were required inside the loop; computing "the next" index took about
214the same number of operations but without as much potential parallelism
215(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
216above, and then shifting perturb can be done while the table index is being
217masked); and the PyDictObject struct required a member to hold the table's
218polynomial. In Tim's experiments the current scheme ran faster, produced
219equally good collision statistics, needed less code & used less memory.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000220
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000221*/
Tim Petersdea48ec2001-05-22 20:40:22 +0000222
Fred Drake1bff34a2000-08-31 19:31:38 +0000223/* forward declarations */
Victor Stinner742da042016-09-07 17:40:12 -0700224static Py_ssize_t lookdict(PyDictObject *mp, PyObject *key,
225 Py_hash_t hash, PyObject ***value_addr,
226 Py_ssize_t *hashpos);
227static Py_ssize_t lookdict_unicode(PyDictObject *mp, PyObject *key,
228 Py_hash_t hash, PyObject ***value_addr,
229 Py_ssize_t *hashpos);
230static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400231lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700232 Py_hash_t hash, PyObject ***value_addr,
233 Py_ssize_t *hashpos);
234static Py_ssize_t lookdict_split(PyDictObject *mp, PyObject *key,
235 Py_hash_t hash, PyObject ***value_addr,
236 Py_ssize_t *hashpos);
Fred Drake1bff34a2000-08-31 19:31:38 +0000237
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400238static int dictresize(PyDictObject *mp, Py_ssize_t minused);
Tim Petersdea48ec2001-05-22 20:40:22 +0000239
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) \
Benjamin Peterson186122e2016-09-08 12:20:12 -0700303 ((PyDictKeyEntry*)(&(dk)->dk_indices.as_1[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) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700321 int8_t *indices = keys->dk_indices.as_1;
Victor Stinner208857e2016-09-08 11:35:46 -0700322 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700323 }
324 else if (s <= 0xffff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700325 int16_t *indices = keys->dk_indices.as_2;
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) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700330 int64_t *indices = keys->dk_indices.as_8;
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 {
335 int32_t *indices = keys->dk_indices.as_4;
336 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) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700351 int8_t *indices = keys->dk_indices.as_1;
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) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700356 int16_t *indices = keys->dk_indices.as_2;
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) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700362 int64_t *indices = keys->dk_indices.as_8;
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 {
367 int32_t *indices = keys->dk_indices.as_4;
368 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 Naoki2c5a8302016-12-07 18:34:44 +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.
401 * Currently set to used*2 + capacity/2.
402 * 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
404 * number of insertions.
405 * Raising this to used*4 doubles memory consumption depending on the size of
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200406 * the dictionary, but results in half the number of resizes, less effort to
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700407 * resize.
408 * GROWTH_RATE was set to used*4 up to version 3.2.
409 * GROWTH_RATE was set to used*2 in version 3.3.0
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200410 */
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700411#define GROWTH_RATE(d) (((d)->ma_used*2)+((d)->ma_keys->dk_size>>1))
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400412
413#define ENSURE_ALLOWS_DELETIONS(d) \
414 if ((d)->ma_keys->dk_lookup == lookdict_unicode_nodummy) { \
415 (d)->ma_keys->dk_lookup = lookdict_unicode; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400417
418/* This immutable, empty PyDictKeysObject is used for PyDict_Clear()
419 * (which cannot fail and thus can do no allocation).
420 */
421static PyDictKeysObject empty_keys_struct = {
Serhiy Storchaka97932e42016-09-26 23:01:23 +0300422 1, /* dk_refcnt */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400423 1, /* dk_size */
424 lookdict_split, /* dk_lookup */
425 0, /* dk_usable (immutable) */
Victor Stinner742da042016-09-07 17:40:12 -0700426 0, /* dk_nentries */
Benjamin Peterson186122e2016-09-08 12:20:12 -0700427 .dk_indices = { .as_1 = {DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY,
428 DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY}},
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400429};
430
431static PyObject *empty_values[1] = { NULL };
432
433#define Py_EMPTY_KEYS &empty_keys_struct
434
Victor Stinner611b0fa2016-09-14 15:02:01 +0200435/* Uncomment to check the dict content in _PyDict_CheckConsistency() */
436/* #define DEBUG_PYDICT */
437
438
T. Wouters90e35182017-04-01 20:20:05 -0700439#ifndef NDEBUG
Victor Stinner611b0fa2016-09-14 15:02:01 +0200440static int
441_PyDict_CheckConsistency(PyDictObject *mp)
442{
443 PyDictKeysObject *keys = mp->ma_keys;
444 int splitted = _PyDict_HasSplitTable(mp);
445 Py_ssize_t usable = USABLE_FRACTION(keys->dk_size);
446#ifdef DEBUG_PYDICT
447 PyDictKeyEntry *entries = DK_ENTRIES(keys);
448 Py_ssize_t i;
449#endif
450
451 assert(0 <= mp->ma_used && mp->ma_used <= usable);
452 assert(IS_POWER_OF_2(keys->dk_size));
453 assert(0 <= keys->dk_usable
454 && keys->dk_usable <= usable);
455 assert(0 <= keys->dk_nentries
456 && keys->dk_nentries <= usable);
457 assert(keys->dk_usable + keys->dk_nentries <= usable);
458
459 if (!splitted) {
460 /* combined table */
461 assert(keys->dk_refcnt == 1);
462 }
463
464#ifdef DEBUG_PYDICT
465 for (i=0; i < keys->dk_size; i++) {
466 Py_ssize_t ix = dk_get_index(keys, i);
467 assert(DKIX_DUMMY <= ix && ix <= usable);
468 }
469
470 for (i=0; i < usable; i++) {
471 PyDictKeyEntry *entry = &entries[i];
472 PyObject *key = entry->me_key;
473
474 if (key != NULL) {
475 if (PyUnicode_CheckExact(key)) {
476 Py_hash_t hash = ((PyASCIIObject *)key)->hash;
477 assert(hash != -1);
478 assert(entry->me_hash == hash);
479 }
480 else {
481 /* test_dict fails if PyObject_Hash() is called again */
482 assert(entry->me_hash != -1);
483 }
484 if (!splitted) {
485 assert(entry->me_value != NULL);
486 }
487 }
488
489 if (splitted) {
490 assert(entry->me_value == NULL);
491 }
492 }
493
494 if (splitted) {
495 /* splitted table */
496 for (i=0; i < mp->ma_used; i++) {
497 assert(mp->ma_values[i] != NULL);
498 }
499 }
500#endif
501
502 return 1;
503}
504#endif
505
506
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400507static PyDictKeysObject *new_keys_object(Py_ssize_t size)
508{
509 PyDictKeysObject *dk;
Victor Stinner742da042016-09-07 17:40:12 -0700510 Py_ssize_t es, usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400511
Victor Stinner742da042016-09-07 17:40:12 -0700512 assert(size >= PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400513 assert(IS_POWER_OF_2(size));
Victor Stinner742da042016-09-07 17:40:12 -0700514
515 usable = USABLE_FRACTION(size);
516 if (size <= 0xff) {
517 es = 1;
518 }
519 else if (size <= 0xffff) {
520 es = 2;
521 }
522#if SIZEOF_VOID_P > 4
523 else if (size <= 0xffffffff) {
524 es = 4;
525 }
526#endif
527 else {
528 es = sizeof(Py_ssize_t);
529 }
530
531 if (size == PyDict_MINSIZE && numfreekeys > 0) {
532 dk = keys_free_list[--numfreekeys];
533 }
534 else {
Victor Stinner98ee9d52016-09-08 09:33:56 -0700535 dk = PyObject_MALLOC(sizeof(PyDictKeysObject)
536 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
537 + es * size
538 + sizeof(PyDictKeyEntry) * usable);
Victor Stinner742da042016-09-07 17:40:12 -0700539 if (dk == NULL) {
540 PyErr_NoMemory();
541 return NULL;
542 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400543 }
Antoine Pitrou2d169b22012-05-12 23:43:44 +0200544 DK_DEBUG_INCREF dk->dk_refcnt = 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400545 dk->dk_size = size;
Victor Stinner742da042016-09-07 17:40:12 -0700546 dk->dk_usable = usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400547 dk->dk_lookup = lookdict_unicode_nodummy;
Victor Stinner742da042016-09-07 17:40:12 -0700548 dk->dk_nentries = 0;
Benjamin Peterson186122e2016-09-08 12:20:12 -0700549 memset(&dk->dk_indices.as_1[0], 0xff, es * size);
Victor Stinner742da042016-09-07 17:40:12 -0700550 memset(DK_ENTRIES(dk), 0, sizeof(PyDictKeyEntry) * usable);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400551 return dk;
552}
553
554static void
555free_keys_object(PyDictKeysObject *keys)
556{
Victor Stinner742da042016-09-07 17:40:12 -0700557 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400558 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -0700559 for (i = 0, n = keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400560 Py_XDECREF(entries[i].me_key);
561 Py_XDECREF(entries[i].me_value);
562 }
Victor Stinner742da042016-09-07 17:40:12 -0700563 if (keys->dk_size == PyDict_MINSIZE && numfreekeys < PyDict_MAXFREELIST) {
564 keys_free_list[numfreekeys++] = keys;
565 return;
566 }
Raymond Hettingerce5179f2016-01-31 08:56:21 -0800567 PyObject_FREE(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400568}
569
570#define new_values(size) PyMem_NEW(PyObject *, size)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400571#define free_values(values) PyMem_FREE(values)
572
573/* Consumes a reference to the keys object */
574static PyObject *
575new_dict(PyDictKeysObject *keys, PyObject **values)
576{
577 PyDictObject *mp;
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200578 assert(keys != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (numfree) {
580 mp = free_list[--numfree];
581 assert (mp != NULL);
582 assert (Py_TYPE(mp) == &PyDict_Type);
583 _Py_NewReference((PyObject *)mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400585 else {
586 mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
587 if (mp == NULL) {
588 DK_DECREF(keys);
589 free_values(values);
590 return NULL;
591 }
592 }
593 mp->ma_keys = keys;
594 mp->ma_values = values;
595 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -0700596 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner611b0fa2016-09-14 15:02:01 +0200597 assert(_PyDict_CheckConsistency(mp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000599}
600
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400601/* Consumes a reference to the keys object */
602static PyObject *
603new_dict_with_shared_keys(PyDictKeysObject *keys)
604{
605 PyObject **values;
606 Py_ssize_t i, size;
607
Victor Stinner742da042016-09-07 17:40:12 -0700608 size = USABLE_FRACTION(DK_SIZE(keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400609 values = new_values(size);
610 if (values == NULL) {
611 DK_DECREF(keys);
612 return PyErr_NoMemory();
613 }
614 for (i = 0; i < size; i++) {
615 values[i] = NULL;
616 }
617 return new_dict(keys, values);
618}
619
620PyObject *
621PyDict_New(void)
622{
Victor Stinner742da042016-09-07 17:40:12 -0700623 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200624 if (keys == NULL)
625 return NULL;
626 return new_dict(keys, NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400627}
628
Victor Stinner742da042016-09-07 17:40:12 -0700629/* Search index of hash table from offset of entry table */
630static Py_ssize_t
631lookdict_index(PyDictKeysObject *k, Py_hash_t hash, Py_ssize_t index)
632{
INADA Naoki267941c2016-10-06 15:19:07 +0900633 size_t i;
Victor Stinner742da042016-09-07 17:40:12 -0700634 size_t mask = DK_MASK(k);
635 Py_ssize_t ix;
636
637 i = (size_t)hash & mask;
638 ix = dk_get_index(k, i);
639 if (ix == index) {
640 return i;
641 }
642 if (ix == DKIX_EMPTY) {
643 return DKIX_EMPTY;
644 }
645
INADA Naoki267941c2016-10-06 15:19:07 +0900646 for (size_t perturb = hash;;) {
647 perturb >>= PERTURB_SHIFT;
Victor Stinner742da042016-09-07 17:40:12 -0700648 i = mask & ((i << 2) + i + perturb + 1);
649 ix = dk_get_index(k, i);
650 if (ix == index) {
651 return i;
652 }
653 if (ix == DKIX_EMPTY) {
654 return DKIX_EMPTY;
655 }
656 }
657 assert(0); /* NOT REACHED */
658 return DKIX_ERROR;
659}
660
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000661/*
662The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000663This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000664Open addressing is preferred over chaining since the link overhead for
665chaining would be substantial (100% with typical malloc overhead).
666
Tim Peterseb28ef22001-06-02 05:27:19 +0000667The initial probe index is computed as hash mod the table size. Subsequent
668probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000669
670All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000671
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000672The details in this version are due to Tim Peters, building on many past
Tim Peterseb28ef22001-06-02 05:27:19 +0000673contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000674Christian Tismer.
Fred Drake1bff34a2000-08-31 19:31:38 +0000675
Victor Stinner742da042016-09-07 17:40:12 -0700676lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a
Victor Stinnera4348cc2016-09-08 12:01:25 -0700677comparison raises an exception.
Guido van Rossum89d8c602007-09-18 17:26:56 +0000678lookdict_unicode() below is specialized to string keys, comparison of which can
INADA Naokice552e22017-02-20 22:58:11 +0900679never raise an exception; that function can never return DKIX_ERROR when key
680is string. Otherwise, it falls back to lookdict().
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400681lookdict_unicode_nodummy is further specialized for string keys that cannot be
682the <dummy> value.
Victor Stinner742da042016-09-07 17:40:12 -0700683For both, when the key isn't found a DKIX_EMPTY is returned. hashpos returns
684where the key index should be inserted.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000685*/
Victor Stinner742da042016-09-07 17:40:12 -0700686static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400687lookdict(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700688 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000689{
INADA Naoki267941c2016-10-06 15:19:07 +0900690 size_t i, mask;
Victor Stinner742da042016-09-07 17:40:12 -0700691 Py_ssize_t ix, freeslot;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200692 int cmp;
Victor Stinner742da042016-09-07 17:40:12 -0700693 PyDictKeysObject *dk;
694 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 PyObject *startkey;
Tim Peterseb28ef22001-06-02 05:27:19 +0000696
Antoine Pitrou9a234902012-05-13 20:48:01 +0200697top:
Victor Stinner742da042016-09-07 17:40:12 -0700698 dk = mp->ma_keys;
699 mask = DK_MASK(dk);
700 ep0 = DK_ENTRIES(dk);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700702
703 ix = dk_get_index(dk, i);
704 if (ix == DKIX_EMPTY) {
705 if (hashpos != NULL)
706 *hashpos = i;
707 *value_addr = NULL;
708 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400709 }
Victor Stinner742da042016-09-07 17:40:12 -0700710 if (ix == DKIX_DUMMY) {
711 freeslot = i;
712 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 else {
Victor Stinner742da042016-09-07 17:40:12 -0700714 ep = &ep0[ix];
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300715 assert(ep->me_key != NULL);
Victor Stinner742da042016-09-07 17:40:12 -0700716 if (ep->me_key == key) {
717 *value_addr = &ep->me_value;
718 if (hashpos != NULL)
719 *hashpos = i;
720 return ix;
721 }
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300722 if (ep->me_hash == hash) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 startkey = ep->me_key;
724 Py_INCREF(startkey);
725 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
726 Py_DECREF(startkey);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +0200727 if (cmp < 0) {
728 *value_addr = NULL;
Victor Stinner742da042016-09-07 17:40:12 -0700729 return DKIX_ERROR;
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +0200730 }
Victor Stinner742da042016-09-07 17:40:12 -0700731 if (dk == mp->ma_keys && ep->me_key == startkey) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400732 if (cmp > 0) {
733 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700734 if (hashpos != NULL)
735 *hashpos = i;
736 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400737 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 }
739 else {
Antoine Pitrou9a234902012-05-13 20:48:01 +0200740 /* The dict was mutated, restart */
741 goto top;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 }
743 }
Victor Stinner742da042016-09-07 17:40:12 -0700744 freeslot = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 }
Tim Peters15d49292001-05-27 07:39:22 +0000746
INADA Naoki267941c2016-10-06 15:19:07 +0900747 for (size_t perturb = hash;;) {
748 perturb >>= PERTURB_SHIFT;
Victor Stinner742da042016-09-07 17:40:12 -0700749 i = ((i << 2) + i + perturb + 1) & mask;
750 ix = dk_get_index(dk, i);
751 if (ix == DKIX_EMPTY) {
752 if (hashpos != NULL) {
753 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400754 }
Victor Stinner742da042016-09-07 17:40:12 -0700755 *value_addr = NULL;
756 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400757 }
Victor Stinner742da042016-09-07 17:40:12 -0700758 if (ix == DKIX_DUMMY) {
759 if (freeslot == -1)
760 freeslot = i;
761 continue;
762 }
763 ep = &ep0[ix];
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300764 assert(ep->me_key != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400765 if (ep->me_key == key) {
Victor Stinner742da042016-09-07 17:40:12 -0700766 if (hashpos != NULL) {
767 *hashpos = i;
768 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400769 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700770 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400771 }
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300772 if (ep->me_hash == hash) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 startkey = ep->me_key;
774 Py_INCREF(startkey);
775 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
776 Py_DECREF(startkey);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400777 if (cmp < 0) {
778 *value_addr = NULL;
Victor Stinner742da042016-09-07 17:40:12 -0700779 return DKIX_ERROR;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400780 }
Victor Stinner742da042016-09-07 17:40:12 -0700781 if (dk == mp->ma_keys && ep->me_key == startkey) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400782 if (cmp > 0) {
Victor Stinner742da042016-09-07 17:40:12 -0700783 if (hashpos != NULL) {
784 *hashpos = i;
785 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400786 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700787 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400788 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 }
790 else {
Antoine Pitrou9a234902012-05-13 20:48:01 +0200791 /* The dict was mutated, restart */
792 goto top;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 }
794 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 }
796 assert(0); /* NOT REACHED */
797 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000798}
799
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400800/* Specialized version for string-only keys */
Victor Stinner742da042016-09-07 17:40:12 -0700801static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400802lookdict_unicode(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700803 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Fred Drake1bff34a2000-08-31 19:31:38 +0000804{
INADA Naoki267941c2016-10-06 15:19:07 +0900805 size_t i;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200806 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700807 Py_ssize_t ix, freeslot;
808 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Fred Drake1bff34a2000-08-31 19:31:38 +0000809
Victor Stinner742da042016-09-07 17:40:12 -0700810 assert(mp->ma_values == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 /* Make sure this function doesn't have to handle non-unicode keys,
812 including subclasses of str; e.g., one reason to subclass
813 unicodes is to override __eq__, and for speed we don't cater to
814 that here. */
815 if (!PyUnicode_CheckExact(key)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400816 mp->ma_keys->dk_lookup = lookdict;
Victor Stinner742da042016-09-07 17:40:12 -0700817 return lookdict(mp, key, hash, value_addr, hashpos);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 }
Mark Dickinson57e683e2011-09-24 18:18:40 +0100819 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700820 ix = dk_get_index(mp->ma_keys, i);
821 if (ix == DKIX_EMPTY) {
822 if (hashpos != NULL)
823 *hashpos = i;
824 *value_addr = NULL;
825 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400826 }
Victor Stinner742da042016-09-07 17:40:12 -0700827 if (ix == DKIX_DUMMY) {
828 freeslot = i;
829 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 else {
Victor Stinner742da042016-09-07 17:40:12 -0700831 ep = &ep0[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700832 assert(ep->me_key != NULL);
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300833 if (ep->me_key == key
834 || (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700835 if (hashpos != NULL)
836 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400837 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700838 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400839 }
Victor Stinner742da042016-09-07 17:40:12 -0700840 freeslot = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 }
Tim Peters15d49292001-05-27 07:39:22 +0000842
INADA Naoki267941c2016-10-06 15:19:07 +0900843 for (size_t perturb = hash;;) {
844 perturb >>= PERTURB_SHIFT;
Victor Stinner742da042016-09-07 17:40:12 -0700845 i = mask & ((i << 2) + i + perturb + 1);
846 ix = dk_get_index(mp->ma_keys, i);
847 if (ix == DKIX_EMPTY) {
848 if (hashpos != NULL) {
849 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400850 }
Victor Stinner742da042016-09-07 17:40:12 -0700851 *value_addr = NULL;
852 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400853 }
Victor Stinner742da042016-09-07 17:40:12 -0700854 if (ix == DKIX_DUMMY) {
855 if (freeslot == -1)
856 freeslot = i;
857 continue;
858 }
859 ep = &ep0[ix];
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300860 assert(ep->me_key != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 if (ep->me_key == key
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300862 || (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400863 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700864 if (hashpos != NULL) {
865 *hashpos = i;
866 }
867 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400868 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 }
870 assert(0); /* NOT REACHED */
871 return 0;
Fred Drake1bff34a2000-08-31 19:31:38 +0000872}
873
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400874/* Faster version of lookdict_unicode when it is known that no <dummy> keys
875 * will be present. */
Victor Stinner742da042016-09-07 17:40:12 -0700876static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400877lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700878 Py_hash_t hash, PyObject ***value_addr,
879 Py_ssize_t *hashpos)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400880{
INADA Naoki267941c2016-10-06 15:19:07 +0900881 size_t i;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200882 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700883 Py_ssize_t ix;
884 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400885
Victor Stinner742da042016-09-07 17:40:12 -0700886 assert(mp->ma_values == NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400887 /* Make sure this function doesn't have to handle non-unicode keys,
888 including subclasses of str; e.g., one reason to subclass
889 unicodes is to override __eq__, and for speed we don't cater to
890 that here. */
891 if (!PyUnicode_CheckExact(key)) {
892 mp->ma_keys->dk_lookup = lookdict;
Victor Stinner742da042016-09-07 17:40:12 -0700893 return lookdict(mp, key, hash, value_addr, hashpos);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400894 }
895 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700896 ix = dk_get_index(mp->ma_keys, i);
897 assert (ix != DKIX_DUMMY);
898 if (ix == DKIX_EMPTY) {
899 if (hashpos != NULL)
900 *hashpos = i;
901 *value_addr = NULL;
902 return DKIX_EMPTY;
903 }
904 ep = &ep0[ix];
Victor Stinnerdee6e252016-09-08 11:16:07 -0700905 assert(ep->me_key != NULL);
906 assert(PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700907 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400908 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700909 if (hashpos != NULL)
910 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400911 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700912 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400913 }
INADA Naoki267941c2016-10-06 15:19:07 +0900914 for (size_t perturb = hash;;) {
915 perturb >>= PERTURB_SHIFT;
Victor Stinner742da042016-09-07 17:40:12 -0700916 i = mask & ((i << 2) + i + perturb + 1);
917 ix = dk_get_index(mp->ma_keys, i);
918 assert (ix != DKIX_DUMMY);
919 if (ix == DKIX_EMPTY) {
920 if (hashpos != NULL)
921 *hashpos = i;
922 *value_addr = NULL;
923 return DKIX_EMPTY;
924 }
925 ep = &ep0[ix];
926 assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
927 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400928 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700929 if (hashpos != NULL)
930 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400931 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700932 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400933 }
934 }
935 assert(0); /* NOT REACHED */
936 return 0;
937}
938
939/* Version of lookdict for split tables.
940 * All split tables and only split tables use this lookup function.
941 * Split tables only contain unicode keys and no dummy keys,
942 * so algorithm is the same as lookdict_unicode_nodummy.
943 */
Victor Stinner742da042016-09-07 17:40:12 -0700944static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400945lookdict_split(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700946 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400947{
INADA Naoki267941c2016-10-06 15:19:07 +0900948 size_t i;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200949 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700950 Py_ssize_t ix;
951 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400952
Victor Stinner742da042016-09-07 17:40:12 -0700953 /* mp must split table */
954 assert(mp->ma_values != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400955 if (!PyUnicode_CheckExact(key)) {
Victor Stinner742da042016-09-07 17:40:12 -0700956 ix = lookdict(mp, key, hash, value_addr, hashpos);
957 if (ix >= 0) {
958 *value_addr = &mp->ma_values[ix];
959 }
960 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400961 }
Victor Stinner742da042016-09-07 17:40:12 -0700962
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400963 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700964 ix = dk_get_index(mp->ma_keys, i);
965 if (ix == DKIX_EMPTY) {
966 if (hashpos != NULL)
967 *hashpos = i;
968 *value_addr = NULL;
969 return DKIX_EMPTY;
970 }
971 assert(ix >= 0);
972 ep = &ep0[ix];
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300973 assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700974 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400975 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700976 if (hashpos != NULL)
977 *hashpos = i;
978 *value_addr = &mp->ma_values[ix];
979 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400980 }
INADA Naoki267941c2016-10-06 15:19:07 +0900981 for (size_t perturb = hash;;) {
982 perturb >>= PERTURB_SHIFT;
Victor Stinner742da042016-09-07 17:40:12 -0700983 i = mask & ((i << 2) + i + perturb + 1);
984 ix = dk_get_index(mp->ma_keys, i);
985 if (ix == DKIX_EMPTY) {
986 if (hashpos != NULL)
987 *hashpos = i;
988 *value_addr = NULL;
989 return DKIX_EMPTY;
990 }
991 assert(ix >= 0);
992 ep = &ep0[ix];
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300993 assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700994 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400995 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700996 if (hashpos != NULL)
997 *hashpos = i;
998 *value_addr = &mp->ma_values[ix];
999 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001000 }
1001 }
1002 assert(0); /* NOT REACHED */
1003 return 0;
1004}
1005
Benjamin Petersonfb886362010-04-24 18:21:17 +00001006int
1007_PyDict_HasOnlyStringKeys(PyObject *dict)
1008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 Py_ssize_t pos = 0;
1010 PyObject *key, *value;
Benjamin Petersonf6096542010-11-17 22:33:12 +00001011 assert(PyDict_Check(dict));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 /* Shortcut */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001013 if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 return 1;
1015 while (PyDict_Next(dict, &pos, &key, &value))
1016 if (!PyUnicode_Check(key))
1017 return 0;
1018 return 1;
Benjamin Petersonfb886362010-04-24 18:21:17 +00001019}
1020
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001021#define MAINTAIN_TRACKING(mp, key, value) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 do { \
1023 if (!_PyObject_GC_IS_TRACKED(mp)) { \
1024 if (_PyObject_GC_MAY_BE_TRACKED(key) || \
1025 _PyObject_GC_MAY_BE_TRACKED(value)) { \
1026 _PyObject_GC_TRACK(mp); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 } \
1028 } \
1029 } while(0)
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001030
1031void
1032_PyDict_MaybeUntrack(PyObject *op)
1033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 PyDictObject *mp;
1035 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -07001036 Py_ssize_t i, numentries;
1037 PyDictKeyEntry *ep0;
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
1040 return;
1041
1042 mp = (PyDictObject *) op;
Victor Stinner742da042016-09-07 17:40:12 -07001043 ep0 = DK_ENTRIES(mp->ma_keys);
1044 numentries = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001045 if (_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -07001046 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001047 if ((value = mp->ma_values[i]) == NULL)
1048 continue;
1049 if (_PyObject_GC_MAY_BE_TRACKED(value)) {
Victor Stinner742da042016-09-07 17:40:12 -07001050 assert(!_PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001051 return;
1052 }
1053 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001055 else {
Victor Stinner742da042016-09-07 17:40:12 -07001056 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001057 if ((value = ep0[i].me_value) == NULL)
1058 continue;
1059 if (_PyObject_GC_MAY_BE_TRACKED(value) ||
1060 _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
1061 return;
1062 }
1063 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 _PyObject_GC_UNTRACK(op);
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001065}
1066
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001067/* Internal function to find slot for an item from its hash
Victor Stinner3c336c52016-09-12 14:17:40 +02001068 when it is known that the key is not present in the dict.
1069
1070 The dict must be combined. */
Victor Stinner99264802016-09-13 09:38:29 +02001071static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001072find_empty_slot(PyDictObject *mp, PyObject *key, Py_hash_t hash,
Victor Stinner742da042016-09-07 17:40:12 -07001073 PyObject ***value_addr, Py_ssize_t *hashpos)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001074{
INADA Naoki267941c2016-10-06 15:19:07 +09001075 size_t i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001076 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07001077 Py_ssize_t ix;
1078 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001079
Victor Stinner3c336c52016-09-12 14:17:40 +02001080 assert(!_PyDict_HasSplitTable(mp));
Victor Stinner742da042016-09-07 17:40:12 -07001081 assert(hashpos != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001082 assert(key != NULL);
Victor Stinner3c336c52016-09-12 14:17:40 +02001083
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001084 if (!PyUnicode_CheckExact(key))
1085 mp->ma_keys->dk_lookup = lookdict;
1086 i = hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -07001087 ix = dk_get_index(mp->ma_keys, i);
INADA Naoki267941c2016-10-06 15:19:07 +09001088 for (size_t perturb = hash; ix != DKIX_EMPTY;) {
1089 perturb >>= PERTURB_SHIFT;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001090 i = (i << 2) + i + perturb + 1;
Victor Stinner742da042016-09-07 17:40:12 -07001091 ix = dk_get_index(mp->ma_keys, i & mask);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 }
Victor Stinner742da042016-09-07 17:40:12 -07001093 ep = &ep0[mp->ma_keys->dk_nentries];
1094 *hashpos = i & mask;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001095 assert(ep->me_value == NULL);
Victor Stinner99264802016-09-13 09:38:29 +02001096 *value_addr = &ep->me_value;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001097}
1098
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001099static int
1100insertion_resize(PyDictObject *mp)
1101{
Raymond Hettinger36f74aa2013-05-17 03:01:13 -07001102 return dictresize(mp, GROWTH_RATE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001103}
Antoine Pitroue965d972012-02-27 00:45:12 +01001104
1105/*
1106Internal routine to insert a new item into the table.
1107Used both by the internal resize routine and by the public insert routine.
Antoine Pitroue965d972012-02-27 00:45:12 +01001108Returns -1 if an error occurred, or 0 on success.
1109*/
1110static int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001111insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001112{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001113 PyObject *old_value;
1114 PyObject **value_addr;
Victor Stinner742da042016-09-07 17:40:12 -07001115 PyDictKeyEntry *ep, *ep0;
1116 Py_ssize_t hashpos, ix;
Antoine Pitroue965d972012-02-27 00:45:12 +01001117
Serhiy Storchaka564398a2017-05-20 13:06:26 +03001118 Py_INCREF(key);
1119 Py_INCREF(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001120 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
1121 if (insertion_resize(mp) < 0)
Serhiy Storchaka564398a2017-05-20 13:06:26 +03001122 goto Fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001123 }
1124
Victor Stinner742da042016-09-07 17:40:12 -07001125 ix = mp->ma_keys->dk_lookup(mp, key, hash, &value_addr, &hashpos);
Serhiy Storchaka564398a2017-05-20 13:06:26 +03001126 if (ix == DKIX_ERROR)
1127 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001128
Antoine Pitroud6967322014-10-18 00:35:00 +02001129 assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001130 MAINTAIN_TRACKING(mp, key, value);
Victor Stinner742da042016-09-07 17:40:12 -07001131
1132 /* When insertion order is different from shared key, we can't share
1133 * the key anymore. Convert this instance to combine table.
1134 */
1135 if (_PyDict_HasSplitTable(mp) &&
1136 ((ix >= 0 && *value_addr == NULL && mp->ma_used != ix) ||
1137 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
Serhiy Storchaka564398a2017-05-20 13:06:26 +03001138 if (insertion_resize(mp) < 0)
1139 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001140 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
1141 ix = DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001142 }
Victor Stinner742da042016-09-07 17:40:12 -07001143
1144 if (ix == DKIX_EMPTY) {
1145 /* Insert into new slot. */
1146 if (mp->ma_keys->dk_usable <= 0) {
1147 /* Need to resize. */
Serhiy Storchaka564398a2017-05-20 13:06:26 +03001148 if (insertion_resize(mp) < 0)
1149 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001150 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
1151 }
1152 ep0 = DK_ENTRIES(mp->ma_keys);
1153 ep = &ep0[mp->ma_keys->dk_nentries];
1154 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
Victor Stinner742da042016-09-07 17:40:12 -07001155 ep->me_key = key;
1156 ep->me_hash = hash;
1157 if (mp->ma_values) {
1158 assert (mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
1159 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001160 }
1161 else {
Victor Stinner742da042016-09-07 17:40:12 -07001162 ep->me_value = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001163 }
1164 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001165 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07001166 mp->ma_keys->dk_usable--;
1167 mp->ma_keys->dk_nentries++;
1168 assert(mp->ma_keys->dk_usable >= 0);
Victor Stinner611b0fa2016-09-14 15:02:01 +02001169 assert(_PyDict_CheckConsistency(mp));
Victor Stinner742da042016-09-07 17:40:12 -07001170 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001171 }
Victor Stinner742da042016-09-07 17:40:12 -07001172
1173 assert(value_addr != NULL);
1174
1175 old_value = *value_addr;
1176 if (old_value != NULL) {
1177 *value_addr = value;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001178 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner611b0fa2016-09-14 15:02:01 +02001179 assert(_PyDict_CheckConsistency(mp));
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001180
Victor Stinner742da042016-09-07 17:40:12 -07001181 Py_DECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
Serhiy Storchaka564398a2017-05-20 13:06:26 +03001182 Py_DECREF(key);
Victor Stinner742da042016-09-07 17:40:12 -07001183 return 0;
1184 }
1185
1186 /* pending state */
1187 assert(_PyDict_HasSplitTable(mp));
1188 assert(ix == mp->ma_used);
1189 *value_addr = value;
1190 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001191 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner611b0fa2016-09-14 15:02:01 +02001192 assert(_PyDict_CheckConsistency(mp));
Serhiy Storchaka564398a2017-05-20 13:06:26 +03001193 Py_DECREF(key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001194 return 0;
Serhiy Storchaka564398a2017-05-20 13:06:26 +03001195
1196Fail:
1197 Py_DECREF(value);
1198 Py_DECREF(key);
1199 return -1;
Antoine Pitroue965d972012-02-27 00:45:12 +01001200}
1201
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001202/*
Serhiy Storchaka7f0514a2016-10-31 20:14:05 +02001203Internal routine used by dictresize() to insert an item which is
1204known to be absent from the dict. This routine also assumes that
1205the dict contains no deleted entries. Besides the performance benefit,
1206using insertdict() in dictresize() is dangerous (SF bug #1456209).
1207Note that no refcounts are changed by this routine; if needed, the caller
1208is responsible for incref'ing `key` and `value`.
1209Neither mp->ma_used nor k->dk_usable are modified by this routine; the caller
1210must set them correctly
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001211*/
1212static void
Serhiy Storchaka7f0514a2016-10-31 20:14:05 +02001213insertdict_clean(PyDictObject *mp, PyObject *key, Py_hash_t hash,
1214 PyObject *value)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001215{
Serhiy Storchaka7f0514a2016-10-31 20:14:05 +02001216 size_t i;
1217 PyDictKeysObject *k = mp->ma_keys;
1218 size_t mask = (size_t)DK_SIZE(k)-1;
1219 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
1220 PyDictKeyEntry *ep;
1221
1222 assert(k->dk_lookup != NULL);
1223 assert(value != NULL);
1224 assert(key != NULL);
1225 assert(PyUnicode_CheckExact(key) || k->dk_lookup == lookdict);
1226 i = hash & mask;
1227 for (size_t perturb = hash; dk_get_index(k, i) != DKIX_EMPTY;) {
1228 perturb >>= PERTURB_SHIFT;
1229 i = mask & ((i << 2) + i + perturb + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 }
Serhiy Storchaka7f0514a2016-10-31 20:14:05 +02001231 ep = &ep0[k->dk_nentries];
1232 assert(ep->me_value == NULL);
1233 dk_set_index(k, i, k->dk_nentries);
1234 k->dk_nentries++;
1235 ep->me_key = key;
1236 ep->me_hash = hash;
1237 ep->me_value = value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001238}
1239
1240/*
1241Restructure the table by allocating a new table and reinserting all
1242items again. When entries have been deleted, the new table may
1243actually be smaller than the old one.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001244If a table is split (its keys and hashes are shared, its values are not),
1245then the values are temporarily copied into the table, it is resized as
1246a combined table, then the me_value slots in the old table are NULLed out.
1247After resizing a table is always combined,
1248but can be resplit by make_keys_shared().
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001249*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001250static int
Victor Stinner3d3f2642016-12-15 17:21:23 +01001251dictresize(PyDictObject *mp, Py_ssize_t minsize)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001252{
Serhiy Storchaka7f0514a2016-10-31 20:14:05 +02001253 Py_ssize_t i, newsize;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001254 PyDictKeysObject *oldkeys;
1255 PyObject **oldvalues;
Serhiy Storchaka7f0514a2016-10-31 20:14:05 +02001256 PyDictKeyEntry *ep0;
Tim Peters91a364d2001-05-19 07:04:38 +00001257
Victor Stinner742da042016-09-07 17:40:12 -07001258 /* Find the smallest table size > minused. */
1259 for (newsize = PyDict_MINSIZE;
Victor Stinner3d3f2642016-12-15 17:21:23 +01001260 newsize < minsize && newsize > 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 newsize <<= 1)
1262 ;
1263 if (newsize <= 0) {
1264 PyErr_NoMemory();
1265 return -1;
1266 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001267 oldkeys = mp->ma_keys;
Serhiy Storchaka7f0514a2016-10-31 20:14:05 +02001268 oldvalues = mp->ma_values;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001269 /* Allocate a new table. */
1270 mp->ma_keys = new_keys_object(newsize);
1271 if (mp->ma_keys == NULL) {
1272 mp->ma_keys = oldkeys;
1273 return -1;
1274 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01001275 // New table must be large enough.
1276 assert(mp->ma_keys->dk_usable >= mp->ma_used);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001277 if (oldkeys->dk_lookup == lookdict)
1278 mp->ma_keys->dk_lookup = lookdict;
Serhiy Storchaka7f0514a2016-10-31 20:14:05 +02001279 mp->ma_values = NULL;
1280 ep0 = DK_ENTRIES(oldkeys);
1281 /* Main loop below assumes we can transfer refcount to new keys
1282 * and that value is stored in me_value.
1283 * Increment ref-counts and copy values here to compensate
1284 * This (resizing a split table) should be relatively rare */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001285 if (oldvalues != NULL) {
Serhiy Storchaka7f0514a2016-10-31 20:14:05 +02001286 for (i = 0; i < oldkeys->dk_nentries; i++) {
1287 if (oldvalues[i] != NULL) {
1288 Py_INCREF(ep0[i].me_key);
1289 ep0[i].me_value = oldvalues[i];
1290 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 }
Serhiy Storchaka7f0514a2016-10-31 20:14:05 +02001292 }
1293 /* Main loop */
1294 for (i = 0; i < oldkeys->dk_nentries; i++) {
1295 PyDictKeyEntry *ep = &ep0[i];
1296 if (ep->me_value != NULL) {
1297 insertdict_clean(mp, ep->me_key, ep->me_hash, ep->me_value);
1298 }
1299 }
1300 mp->ma_keys->dk_usable -= mp->ma_used;
1301 if (oldvalues != NULL) {
1302 /* NULL out me_value slot in oldkeys, in case it was shared */
1303 for (i = 0; i < oldkeys->dk_nentries; i++)
1304 ep0[i].me_value = NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001305 DK_DECREF(oldkeys);
Victor Stinner742da042016-09-07 17:40:12 -07001306 if (oldvalues != empty_values) {
1307 free_values(oldvalues);
1308 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001309 }
Serhiy Storchaka7f0514a2016-10-31 20:14:05 +02001310 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001311 assert(oldkeys->dk_lookup != lookdict_split);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001312 assert(oldkeys->dk_refcnt == 1);
Serhiy Storchaka7f0514a2016-10-31 20:14:05 +02001313 DK_DEBUG_DECREF PyObject_FREE(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001314 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001316}
1317
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001318/* Returns NULL if unable to split table.
1319 * A NULL return does not necessarily indicate an error */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001320static PyDictKeysObject *
1321make_keys_shared(PyObject *op)
1322{
1323 Py_ssize_t i;
1324 Py_ssize_t size;
1325 PyDictObject *mp = (PyDictObject *)op;
1326
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001327 if (!PyDict_CheckExact(op))
1328 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001329 if (!_PyDict_HasSplitTable(mp)) {
1330 PyDictKeyEntry *ep0;
1331 PyObject **values;
1332 assert(mp->ma_keys->dk_refcnt == 1);
1333 if (mp->ma_keys->dk_lookup == lookdict) {
1334 return NULL;
1335 }
1336 else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
1337 /* Remove dummy keys */
1338 if (dictresize(mp, DK_SIZE(mp->ma_keys)))
1339 return NULL;
1340 }
1341 assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
1342 /* Copy values into a new array */
Victor Stinner742da042016-09-07 17:40:12 -07001343 ep0 = DK_ENTRIES(mp->ma_keys);
1344 size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001345 values = new_values(size);
1346 if (values == NULL) {
1347 PyErr_SetString(PyExc_MemoryError,
1348 "Not enough memory to allocate new values array");
1349 return NULL;
1350 }
1351 for (i = 0; i < size; i++) {
1352 values[i] = ep0[i].me_value;
1353 ep0[i].me_value = NULL;
1354 }
1355 mp->ma_keys->dk_lookup = lookdict_split;
1356 mp->ma_values = values;
1357 }
1358 DK_INCREF(mp->ma_keys);
1359 return mp->ma_keys;
1360}
Christian Heimes99170a52007-12-19 02:07:34 +00001361
1362PyObject *
1363_PyDict_NewPresized(Py_ssize_t minused)
1364{
INADA Naoki2c5a8302016-12-07 18:34:44 +09001365 const Py_ssize_t max_presize = 128 * 1024;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001366 Py_ssize_t newsize;
1367 PyDictKeysObject *new_keys;
INADA Naoki2c5a8302016-12-07 18:34:44 +09001368
1369 /* There are no strict guarantee that returned dict can contain minused
1370 * items without resize. So we create medium size dict instead of very
1371 * large dict or MemoryError.
1372 */
1373 if (minused > USABLE_FRACTION(max_presize)) {
1374 newsize = max_presize;
1375 }
1376 else {
1377 Py_ssize_t minsize = ESTIMATE_SIZE(minused);
1378 newsize = PyDict_MINSIZE;
1379 while (newsize < minsize) {
1380 newsize <<= 1;
1381 }
1382 }
1383 assert(IS_POWER_OF_2(newsize));
1384
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001385 new_keys = new_keys_object(newsize);
1386 if (new_keys == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001388 return new_dict(new_keys, NULL);
Christian Heimes99170a52007-12-19 02:07:34 +00001389}
1390
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001391/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
1392 * that may occur (originally dicts supported only string keys, and exceptions
1393 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001394 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001395 * (suppressed) occurred while computing the key's hash, or that some error
1396 * (suppressed) occurred when comparing keys in the dict's internal probe
1397 * sequence. A nasty example of the latter is when a Python-coded comparison
1398 * function hits a stack-depth error, which can cause this to return NULL
1399 * even if the key is present.
1400 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001401PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001402PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001403{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001404 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001405 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 PyDictObject *mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 PyThreadState *tstate;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001408 PyObject **value_addr;
1409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 if (!PyDict_Check(op))
1411 return NULL;
1412 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001413 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 {
1415 hash = PyObject_Hash(key);
1416 if (hash == -1) {
1417 PyErr_Clear();
1418 return NULL;
1419 }
1420 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 /* We can arrive here with a NULL tstate during initialization: try
1423 running "python -Wi" for an example related to string interning.
1424 Let's just hope that no exception occurs then... This must be
1425 _PyThreadState_Current and not PyThreadState_GET() because in debug
1426 mode, the latter complains if tstate is NULL. */
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001427 tstate = _PyThreadState_UncheckedGet();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 if (tstate != NULL && tstate->curexc_type != NULL) {
1429 /* preserve the existing exception */
1430 PyObject *err_type, *err_value, *err_tb;
1431 PyErr_Fetch(&err_type, &err_value, &err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001432 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 /* ignore errors */
1434 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001435 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 return NULL;
1437 }
1438 else {
Victor Stinner742da042016-09-07 17:40:12 -07001439 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1440 if (ix < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 PyErr_Clear();
1442 return NULL;
1443 }
1444 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001445 return *value_addr;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001446}
1447
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001448/* Same as PyDict_GetItemWithError() but with hash supplied by caller.
1449 This returns NULL *with* an exception set if an exception occurred.
1450 It returns NULL *without* an exception set if the key wasn't present.
1451*/
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001452PyObject *
1453_PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1454{
Victor Stinner742da042016-09-07 17:40:12 -07001455 Py_ssize_t ix;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001456 PyDictObject *mp = (PyDictObject *)op;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001457 PyObject **value_addr;
1458
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001459 if (!PyDict_Check(op)) {
1460 PyErr_BadInternalCall();
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001461 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001462 }
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001463
1464 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1465 if (ix < 0) {
1466 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001467 }
1468 return *value_addr;
1469}
1470
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001471/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
1472 This returns NULL *with* an exception set if an exception occurred.
1473 It returns NULL *without* an exception set if the key wasn't present.
1474*/
1475PyObject *
1476PyDict_GetItemWithError(PyObject *op, PyObject *key)
1477{
Victor Stinner742da042016-09-07 17:40:12 -07001478 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001479 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 PyDictObject*mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001481 PyObject **value_addr;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 if (!PyDict_Check(op)) {
1484 PyErr_BadInternalCall();
1485 return NULL;
1486 }
1487 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001488 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 {
1490 hash = PyObject_Hash(key);
1491 if (hash == -1) {
1492 return NULL;
1493 }
1494 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001495
Victor Stinner742da042016-09-07 17:40:12 -07001496 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1497 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001499 return *value_addr;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001500}
1501
Brett Cannonfd074152012-04-14 14:10:13 -04001502PyObject *
1503_PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
1504{
1505 PyObject *kv;
1506 kv = _PyUnicode_FromId(key); /* borrowed */
1507 if (kv == NULL)
1508 return NULL;
1509 return PyDict_GetItemWithError(dp, kv);
1510}
1511
Victor Stinnerb4efc962015-11-20 09:24:02 +01001512/* Fast version of global value lookup (LOAD_GLOBAL).
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001513 * Lookup in globals, then builtins.
Victor Stinnerb4efc962015-11-20 09:24:02 +01001514 *
1515 * Raise an exception and return NULL if an error occurred (ex: computing the
1516 * key hash failed, key comparison failed, ...). Return NULL if the key doesn't
1517 * exist. Return the value if the key exists.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001518 */
1519PyObject *
1520_PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001521{
Victor Stinner742da042016-09-07 17:40:12 -07001522 Py_ssize_t ix;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001523 Py_hash_t hash;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001524 PyObject **value_addr;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001525
1526 if (!PyUnicode_CheckExact(key) ||
1527 (hash = ((PyASCIIObject *) key)->hash) == -1)
1528 {
1529 hash = PyObject_Hash(key);
1530 if (hash == -1)
1531 return NULL;
Antoine Pitroue965d972012-02-27 00:45:12 +01001532 }
Victor Stinnerb4efc962015-11-20 09:24:02 +01001533
1534 /* namespace 1: globals */
Victor Stinner742da042016-09-07 17:40:12 -07001535 ix = globals->ma_keys->dk_lookup(globals, key, hash, &value_addr, NULL);
1536 if (ix == DKIX_ERROR)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001537 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001538 if (ix != DKIX_EMPTY && *value_addr != NULL)
1539 return *value_addr;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001540
1541 /* namespace 2: builtins */
Victor Stinner742da042016-09-07 17:40:12 -07001542 ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value_addr, NULL);
1543 if (ix < 0)
Victor Stinnerb4efc962015-11-20 09:24:02 +01001544 return NULL;
1545 return *value_addr;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001546}
1547
Antoine Pitroue965d972012-02-27 00:45:12 +01001548/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
1549 * dictionary if it's merely replacing the value for an existing key.
1550 * This means that it's safe to loop over a dictionary with PyDict_Next()
1551 * and occasionally replace a value -- but you can't insert new keys or
1552 * remove them.
1553 */
1554int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001555PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001556{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001557 PyDictObject *mp;
1558 Py_hash_t hash;
Antoine Pitroue965d972012-02-27 00:45:12 +01001559 if (!PyDict_Check(op)) {
1560 PyErr_BadInternalCall();
1561 return -1;
1562 }
1563 assert(key);
1564 assert(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001565 mp = (PyDictObject *)op;
1566 if (!PyUnicode_CheckExact(key) ||
1567 (hash = ((PyASCIIObject *) key)->hash) == -1)
1568 {
Antoine Pitroue965d972012-02-27 00:45:12 +01001569 hash = PyObject_Hash(key);
1570 if (hash == -1)
1571 return -1;
1572 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001573
1574 /* insertdict() handles any resizing that might be necessary */
1575 return insertdict(mp, key, hash, value);
Antoine Pitroue965d972012-02-27 00:45:12 +01001576}
1577
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001578int
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001579_PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
1580 Py_hash_t hash)
1581{
1582 PyDictObject *mp;
1583
1584 if (!PyDict_Check(op)) {
1585 PyErr_BadInternalCall();
1586 return -1;
1587 }
1588 assert(key);
1589 assert(value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001590 assert(hash != -1);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001591 mp = (PyDictObject *)op;
1592
1593 /* insertdict() handles any resizing that might be necessary */
1594 return insertdict(mp, key, hash, value);
1595}
1596
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001597static int
Antoine Pitroud741ed42016-12-27 14:23:43 +01001598delitem_common(PyDictObject *mp, Py_ssize_t hashpos, Py_ssize_t ix,
1599 PyObject **value_addr)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001600{
1601 PyObject *old_key, *old_value;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001602 PyDictKeyEntry *ep;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001603
1604 old_value = *value_addr;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001605 assert(old_value != NULL);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001606 *value_addr = NULL;
1607 mp->ma_used--;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001608 mp->ma_version_tag = DICT_NEXT_VERSION();
1609 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1610 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1611 ENSURE_ALLOWS_DELETIONS(mp);
1612 old_key = ep->me_key;
1613 ep->me_key = NULL;
1614 Py_DECREF(old_key);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001615 Py_DECREF(old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001616
1617 assert(_PyDict_CheckConsistency(mp));
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001618 return 0;
1619}
1620
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001621int
Tim Peters1f5871e2000-07-04 17:44:48 +00001622PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001623{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001624 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 assert(key);
1626 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001627 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 hash = PyObject_Hash(key);
1629 if (hash == -1)
1630 return -1;
1631 }
Victor Stinner742da042016-09-07 17:40:12 -07001632
1633 return _PyDict_DelItem_KnownHash(op, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001634}
1635
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001636int
1637_PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1638{
Victor Stinner742da042016-09-07 17:40:12 -07001639 Py_ssize_t hashpos, ix;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001640 PyDictObject *mp;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001641 PyObject **value_addr;
1642
1643 if (!PyDict_Check(op)) {
1644 PyErr_BadInternalCall();
1645 return -1;
1646 }
1647 assert(key);
1648 assert(hash != -1);
1649 mp = (PyDictObject *)op;
Victor Stinner742da042016-09-07 17:40:12 -07001650 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1651 if (ix == DKIX_ERROR)
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001652 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07001653 if (ix == DKIX_EMPTY || *value_addr == NULL) {
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001654 _PyErr_SetKeyError(key);
1655 return -1;
1656 }
Victor Stinner742da042016-09-07 17:40:12 -07001657 assert(dk_get_index(mp->ma_keys, hashpos) == ix);
Victor Stinner78601a32016-09-09 19:28:36 -07001658
1659 // Split table doesn't allow deletion. Combine it.
1660 if (_PyDict_HasSplitTable(mp)) {
1661 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1662 return -1;
1663 }
1664 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1665 assert(ix >= 0);
1666 }
Antoine Pitroud741ed42016-12-27 14:23:43 +01001667 return delitem_common(mp, hashpos, ix, value_addr);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001668}
1669
Antoine Pitroud741ed42016-12-27 14:23:43 +01001670/* This function promises that the predicate -> deletion sequence is atomic
1671 * (i.e. protected by the GIL), assuming the predicate itself doesn't
1672 * release the GIL.
1673 */
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001674int
1675_PyDict_DelItemIf(PyObject *op, PyObject *key,
1676 int (*predicate)(PyObject *value))
1677{
Antoine Pitroud741ed42016-12-27 14:23:43 +01001678 Py_ssize_t hashpos, ix;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001679 PyDictObject *mp;
1680 Py_hash_t hash;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001681 PyObject **value_addr;
1682 int res;
1683
1684 if (!PyDict_Check(op)) {
1685 PyErr_BadInternalCall();
1686 return -1;
1687 }
1688 assert(key);
1689 hash = PyObject_Hash(key);
1690 if (hash == -1)
1691 return -1;
1692 mp = (PyDictObject *)op;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001693 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1694 if (ix == DKIX_ERROR)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001695 return -1;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001696 if (ix == DKIX_EMPTY || *value_addr == NULL) {
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001697 _PyErr_SetKeyError(key);
1698 return -1;
1699 }
Antoine Pitroud741ed42016-12-27 14:23:43 +01001700 assert(dk_get_index(mp->ma_keys, hashpos) == ix);
1701
1702 // Split table doesn't allow deletion. Combine it.
1703 if (_PyDict_HasSplitTable(mp)) {
1704 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1705 return -1;
1706 }
1707 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1708 assert(ix >= 0);
1709 }
1710
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001711 res = predicate(*value_addr);
1712 if (res == -1)
1713 return -1;
1714 if (res > 0)
Antoine Pitroud741ed42016-12-27 14:23:43 +01001715 return delitem_common(mp, hashpos, ix, value_addr);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001716 else
1717 return 0;
1718}
1719
1720
Guido van Rossum25831651993-05-19 14:50:45 +00001721void
Tim Peters1f5871e2000-07-04 17:44:48 +00001722PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 PyDictObject *mp;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001725 PyDictKeysObject *oldkeys;
1726 PyObject **oldvalues;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 if (!PyDict_Check(op))
1730 return;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001731 mp = ((PyDictObject *)op);
1732 oldkeys = mp->ma_keys;
1733 oldvalues = mp->ma_values;
1734 if (oldvalues == empty_values)
1735 return;
1736 /* Empty the dict... */
1737 DK_INCREF(Py_EMPTY_KEYS);
1738 mp->ma_keys = Py_EMPTY_KEYS;
1739 mp->ma_values = empty_values;
1740 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001741 mp->ma_version_tag = DICT_NEXT_VERSION();
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001742 /* ...then clear the keys and values */
1743 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001744 n = oldkeys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001745 for (i = 0; i < n; i++)
1746 Py_CLEAR(oldvalues[i]);
1747 free_values(oldvalues);
1748 DK_DECREF(oldkeys);
1749 }
1750 else {
1751 assert(oldkeys->dk_refcnt == 1);
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001752 DK_DECREF(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001753 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02001754 assert(_PyDict_CheckConsistency(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001755}
1756
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001757/* Internal version of PyDict_Next that returns a hash value in addition
1758 * to the key and value.
1759 * Return 1 on success, return 0 when the reached the end of the dictionary
1760 * (or if op is not a dictionary)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001761 */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001762int
1763_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
1764 PyObject **pvalue, Py_hash_t *phash)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001765{
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001766 Py_ssize_t i, n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001767 PyDictObject *mp;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001768 PyDictKeyEntry *entry_ptr;
1769 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001770
1771 if (!PyDict_Check(op))
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001772 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 mp = (PyDictObject *)op;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001774 i = *ppos;
Victor Stinner742da042016-09-07 17:40:12 -07001775 n = mp->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001776 if ((size_t)i >= (size_t)n)
1777 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001778 if (mp->ma_values) {
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001779 PyObject **value_ptr = &mp->ma_values[i];
1780 while (i < n && *value_ptr == NULL) {
1781 value_ptr++;
1782 i++;
Victor Stinner742da042016-09-07 17:40:12 -07001783 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001784 if (i >= n)
1785 return 0;
1786 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
1787 value = *value_ptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001789 else {
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001790 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
1791 while (i < n && entry_ptr->me_value == NULL) {
1792 entry_ptr++;
1793 i++;
Victor Stinner742da042016-09-07 17:40:12 -07001794 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001795 if (i >= n)
1796 return 0;
1797 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001799 *ppos = i+1;
1800 if (pkey)
1801 *pkey = entry_ptr->me_key;
1802 if (phash)
1803 *phash = entry_ptr->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001804 if (pvalue)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001805 *pvalue = value;
1806 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001807}
1808
Tim Peters080c88b2003-02-15 03:01:11 +00001809/*
1810 * Iterate over a dict. Use like so:
1811 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001812 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +00001813 * PyObject *key, *value;
1814 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +00001815 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001816 * Refer to borrowed references in key and value.
Tim Peters080c88b2003-02-15 03:01:11 +00001817 * }
1818 *
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001819 * Return 1 on success, return 0 when the reached the end of the dictionary
1820 * (or if op is not a dictionary)
1821 *
Tim Peters080c88b2003-02-15 03:01:11 +00001822 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +00001823 * mutates the dict. One exception: it is safe if the loop merely changes
1824 * the values associated with the keys (but doesn't insert new keys or
1825 * delete keys), via PyDict_SetItem().
1826 */
Guido van Rossum25831651993-05-19 14:50:45 +00001827int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001828PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001829{
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001830 return _PyDict_Next(op, ppos, pkey, pvalue, NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00001831}
1832
Eric Snow96c6af92015-05-29 22:21:39 -06001833/* Internal version of dict.pop(). */
1834PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001835_PyDict_Pop_KnownHash(PyObject *dict, PyObject *key, Py_hash_t hash, PyObject *deflt)
Eric Snow96c6af92015-05-29 22:21:39 -06001836{
Victor Stinner742da042016-09-07 17:40:12 -07001837 Py_ssize_t ix, hashpos;
Eric Snow96c6af92015-05-29 22:21:39 -06001838 PyObject *old_value, *old_key;
1839 PyDictKeyEntry *ep;
1840 PyObject **value_addr;
Yury Selivanov684ef2c2016-10-28 19:01:21 -04001841 PyDictObject *mp;
1842
1843 assert(PyDict_Check(dict));
1844 mp = (PyDictObject *)dict;
Eric Snow96c6af92015-05-29 22:21:39 -06001845
1846 if (mp->ma_used == 0) {
1847 if (deflt) {
1848 Py_INCREF(deflt);
1849 return deflt;
1850 }
1851 _PyErr_SetKeyError(key);
1852 return NULL;
1853 }
Victor Stinner742da042016-09-07 17:40:12 -07001854 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1855 if (ix == DKIX_ERROR)
Eric Snow96c6af92015-05-29 22:21:39 -06001856 return NULL;
Victor Stinnerd0ad11f2016-09-13 16:56:38 +02001857 if (ix == DKIX_EMPTY || *value_addr == NULL) {
Eric Snow96c6af92015-05-29 22:21:39 -06001858 if (deflt) {
1859 Py_INCREF(deflt);
1860 return deflt;
1861 }
1862 _PyErr_SetKeyError(key);
1863 return NULL;
1864 }
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001865
Victor Stinner78601a32016-09-09 19:28:36 -07001866 // Split table doesn't allow deletion. Combine it.
1867 if (_PyDict_HasSplitTable(mp)) {
1868 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1869 return NULL;
1870 }
1871 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1872 assert(ix >= 0);
1873 }
1874
Victor Stinner742da042016-09-07 17:40:12 -07001875 old_value = *value_addr;
Victor Stinner78601a32016-09-09 19:28:36 -07001876 assert(old_value != NULL);
Eric Snow96c6af92015-05-29 22:21:39 -06001877 *value_addr = NULL;
1878 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001879 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner78601a32016-09-09 19:28:36 -07001880 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1881 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1882 ENSURE_ALLOWS_DELETIONS(mp);
1883 old_key = ep->me_key;
1884 ep->me_key = NULL;
1885 Py_DECREF(old_key);
Victor Stinner611b0fa2016-09-14 15:02:01 +02001886
1887 assert(_PyDict_CheckConsistency(mp));
Eric Snow96c6af92015-05-29 22:21:39 -06001888 return old_value;
1889}
1890
Serhiy Storchaka67796522017-01-12 18:34:33 +02001891PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001892_PyDict_Pop(PyObject *dict, PyObject *key, PyObject *deflt)
Serhiy Storchaka67796522017-01-12 18:34:33 +02001893{
1894 Py_hash_t hash;
1895
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001896 if (((PyDictObject *)dict)->ma_used == 0) {
Serhiy Storchaka67796522017-01-12 18:34:33 +02001897 if (deflt) {
1898 Py_INCREF(deflt);
1899 return deflt;
1900 }
1901 _PyErr_SetKeyError(key);
1902 return NULL;
1903 }
1904 if (!PyUnicode_CheckExact(key) ||
1905 (hash = ((PyASCIIObject *) key)->hash) == -1) {
1906 hash = PyObject_Hash(key);
1907 if (hash == -1)
1908 return NULL;
1909 }
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001910 return _PyDict_Pop_KnownHash(dict, key, hash, deflt);
Serhiy Storchaka67796522017-01-12 18:34:33 +02001911}
1912
Eric Snow96c6af92015-05-29 22:21:39 -06001913/* Internal version of dict.from_keys(). It is subclass-friendly. */
1914PyObject *
1915_PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
1916{
1917 PyObject *it; /* iter(iterable) */
1918 PyObject *key;
1919 PyObject *d;
1920 int status;
1921
1922 d = PyObject_CallObject(cls, NULL);
1923 if (d == NULL)
1924 return NULL;
1925
1926 if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
1927 if (PyDict_CheckExact(iterable)) {
1928 PyDictObject *mp = (PyDictObject *)d;
1929 PyObject *oldvalue;
1930 Py_ssize_t pos = 0;
1931 PyObject *key;
1932 Py_hash_t hash;
1933
Serhiy Storchakaaf839fe2017-03-22 07:45:23 +02001934 if (dictresize(mp, ESTIMATE_SIZE(((PyDictObject *)iterable)->ma_used))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001935 Py_DECREF(d);
1936 return NULL;
1937 }
1938
1939 while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
1940 if (insertdict(mp, key, hash, value)) {
1941 Py_DECREF(d);
1942 return NULL;
1943 }
1944 }
1945 return d;
1946 }
1947 if (PyAnySet_CheckExact(iterable)) {
1948 PyDictObject *mp = (PyDictObject *)d;
1949 Py_ssize_t pos = 0;
1950 PyObject *key;
1951 Py_hash_t hash;
1952
Victor Stinner742da042016-09-07 17:40:12 -07001953 if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001954 Py_DECREF(d);
1955 return NULL;
1956 }
1957
1958 while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
1959 if (insertdict(mp, key, hash, value)) {
1960 Py_DECREF(d);
1961 return NULL;
1962 }
1963 }
1964 return d;
1965 }
1966 }
1967
1968 it = PyObject_GetIter(iterable);
1969 if (it == NULL){
1970 Py_DECREF(d);
1971 return NULL;
1972 }
1973
1974 if (PyDict_CheckExact(d)) {
1975 while ((key = PyIter_Next(it)) != NULL) {
1976 status = PyDict_SetItem(d, key, value);
1977 Py_DECREF(key);
1978 if (status < 0)
1979 goto Fail;
1980 }
1981 } else {
1982 while ((key = PyIter_Next(it)) != NULL) {
1983 status = PyObject_SetItem(d, key, value);
1984 Py_DECREF(key);
1985 if (status < 0)
1986 goto Fail;
1987 }
1988 }
1989
1990 if (PyErr_Occurred())
1991 goto Fail;
1992 Py_DECREF(it);
1993 return d;
1994
1995Fail:
1996 Py_DECREF(it);
1997 Py_DECREF(d);
1998 return NULL;
1999}
2000
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002001/* Methods */
2002
2003static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002004dict_dealloc(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002005{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002006 PyObject **values = mp->ma_values;
2007 PyDictKeysObject *keys = mp->ma_keys;
2008 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 PyObject_GC_UnTrack(mp);
2010 Py_TRASHCAN_SAFE_BEGIN(mp)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002011 if (values != NULL) {
2012 if (values != empty_values) {
Victor Stinner742da042016-09-07 17:40:12 -07002013 for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002014 Py_XDECREF(values[i]);
2015 }
2016 free_values(values);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002018 DK_DECREF(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 }
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02002020 else if (keys != NULL) {
Antoine Pitrou2d169b22012-05-12 23:43:44 +02002021 assert(keys->dk_refcnt == 1);
2022 DK_DECREF(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002023 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
2025 free_list[numfree++] = mp;
2026 else
2027 Py_TYPE(mp)->tp_free((PyObject *)mp);
2028 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002029}
2030
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002031
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002032static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002033dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 Py_ssize_t i;
Victor Stinnerf91929b2013-11-19 13:07:38 +01002036 PyObject *key = NULL, *value = NULL;
2037 _PyUnicodeWriter writer;
2038 int first;
Guido van Rossum255443b1998-04-10 22:47:14 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 i = Py_ReprEnter((PyObject *)mp);
2041 if (i != 0) {
2042 return i > 0 ? PyUnicode_FromString("{...}") : NULL;
2043 }
Guido van Rossum255443b1998-04-10 22:47:14 +00002044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 if (mp->ma_used == 0) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01002046 Py_ReprLeave((PyObject *)mp);
2047 return PyUnicode_FromString("{}");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 }
Tim Petersa7259592001-06-16 05:11:17 +00002049
Victor Stinnerf91929b2013-11-19 13:07:38 +01002050 _PyUnicodeWriter_Init(&writer);
2051 writer.overallocate = 1;
2052 /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
2053 writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +00002054
Victor Stinnerf91929b2013-11-19 13:07:38 +01002055 if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
2056 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 /* Do repr() on each key+value pair, and insert ": " between them.
2059 Note that repr may mutate the dict. */
2060 i = 0;
Victor Stinnerf91929b2013-11-19 13:07:38 +01002061 first = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01002063 PyObject *s;
2064 int res;
2065
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002066 /* Prevent repr from deleting key or value during key format. */
2067 Py_INCREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 Py_INCREF(value);
Victor Stinnerf97dfd72013-07-18 01:00:45 +02002069
Victor Stinnerf91929b2013-11-19 13:07:38 +01002070 if (!first) {
2071 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
2072 goto error;
2073 }
2074 first = 0;
2075
2076 s = PyObject_Repr(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 if (s == NULL)
Victor Stinnerf91929b2013-11-19 13:07:38 +01002078 goto error;
2079 res = _PyUnicodeWriter_WriteStr(&writer, s);
2080 Py_DECREF(s);
2081 if (res < 0)
2082 goto error;
2083
2084 if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
2085 goto error;
2086
2087 s = PyObject_Repr(value);
2088 if (s == NULL)
2089 goto error;
2090 res = _PyUnicodeWriter_WriteStr(&writer, s);
2091 Py_DECREF(s);
2092 if (res < 0)
2093 goto error;
2094
2095 Py_CLEAR(key);
2096 Py_CLEAR(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 }
Tim Petersa7259592001-06-16 05:11:17 +00002098
Victor Stinnerf91929b2013-11-19 13:07:38 +01002099 writer.overallocate = 0;
2100 if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
2101 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00002102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 Py_ReprLeave((PyObject *)mp);
Victor Stinnerf91929b2013-11-19 13:07:38 +01002104
2105 return _PyUnicodeWriter_Finish(&writer);
2106
2107error:
2108 Py_ReprLeave((PyObject *)mp);
2109 _PyUnicodeWriter_Dealloc(&writer);
2110 Py_XDECREF(key);
2111 Py_XDECREF(value);
2112 return NULL;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002113}
2114
Martin v. Löwis18e16552006-02-15 17:27:45 +00002115static Py_ssize_t
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002116dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 return mp->ma_used;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002119}
2120
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002121static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002122dict_subscript(PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 PyObject *v;
Victor Stinner742da042016-09-07 17:40:12 -07002125 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002126 Py_hash_t hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002127 PyObject **value_addr;
2128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002130 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 hash = PyObject_Hash(key);
2132 if (hash == -1)
2133 return NULL;
2134 }
Victor Stinner742da042016-09-07 17:40:12 -07002135 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2136 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002138 if (ix == DKIX_EMPTY || *value_addr == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 if (!PyDict_CheckExact(mp)) {
2140 /* Look up __missing__ method if we're a subclass. */
2141 PyObject *missing, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05002142 _Py_IDENTIFIER(__missing__);
2143 missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 if (missing != NULL) {
2145 res = PyObject_CallFunctionObjArgs(missing,
2146 key, NULL);
2147 Py_DECREF(missing);
2148 return res;
2149 }
2150 else if (PyErr_Occurred())
2151 return NULL;
2152 }
Raymond Hettinger69492da2013-09-02 15:59:26 -07002153 _PyErr_SetKeyError(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 return NULL;
2155 }
Victor Stinner742da042016-09-07 17:40:12 -07002156 v = *value_addr;
2157 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002159}
2160
2161static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002162dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 if (w == NULL)
2165 return PyDict_DelItem((PyObject *)mp, v);
2166 else
2167 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002168}
2169
Guido van Rossuma9e7a811997-05-13 21:02:11 +00002170static PyMappingMethods dict_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 (lenfunc)dict_length, /*mp_length*/
2172 (binaryfunc)dict_subscript, /*mp_subscript*/
2173 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002174};
2175
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002176static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002177dict_keys(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002178{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002179 PyObject *v;
2180 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002181 PyDictKeyEntry *ep;
2182 Py_ssize_t size, n, offset;
2183 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002184
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002185 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 n = mp->ma_used;
2187 v = PyList_New(n);
2188 if (v == NULL)
2189 return NULL;
2190 if (n != mp->ma_used) {
2191 /* Durnit. The allocations caused the dict to resize.
2192 * Just start over, this shouldn't normally happen.
2193 */
2194 Py_DECREF(v);
2195 goto again;
2196 }
Victor Stinner742da042016-09-07 17:40:12 -07002197 ep = DK_ENTRIES(mp->ma_keys);
2198 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002199 if (mp->ma_values) {
2200 value_ptr = mp->ma_values;
2201 offset = sizeof(PyObject *);
2202 }
2203 else {
2204 value_ptr = &ep[0].me_value;
2205 offset = sizeof(PyDictKeyEntry);
2206 }
2207 for (i = 0, j = 0; i < size; i++) {
2208 if (*value_ptr != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 PyObject *key = ep[i].me_key;
2210 Py_INCREF(key);
2211 PyList_SET_ITEM(v, j, key);
2212 j++;
2213 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002214 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 }
2216 assert(j == n);
2217 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002218}
2219
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002220static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002221dict_values(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002222{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002223 PyObject *v;
2224 Py_ssize_t i, j;
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002225 PyDictKeyEntry *ep;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002226 Py_ssize_t size, n, offset;
2227 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002228
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002229 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 n = mp->ma_used;
2231 v = PyList_New(n);
2232 if (v == NULL)
2233 return NULL;
2234 if (n != mp->ma_used) {
2235 /* Durnit. The allocations caused the dict to resize.
2236 * Just start over, this shouldn't normally happen.
2237 */
2238 Py_DECREF(v);
2239 goto again;
2240 }
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002241 ep = DK_ENTRIES(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002242 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002243 if (mp->ma_values) {
2244 value_ptr = mp->ma_values;
2245 offset = sizeof(PyObject *);
2246 }
2247 else {
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002248 value_ptr = &ep[0].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002249 offset = sizeof(PyDictKeyEntry);
2250 }
2251 for (i = 0, j = 0; i < size; i++) {
2252 PyObject *value = *value_ptr;
2253 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2254 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 Py_INCREF(value);
2256 PyList_SET_ITEM(v, j, value);
2257 j++;
2258 }
2259 }
2260 assert(j == n);
2261 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002262}
2263
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002264static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002265dict_items(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002266{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002267 PyObject *v;
2268 Py_ssize_t i, j, n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002269 Py_ssize_t size, offset;
2270 PyObject *item, *key;
2271 PyDictKeyEntry *ep;
2272 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 /* Preallocate the list of tuples, to avoid allocations during
2275 * the loop over the items, which could trigger GC, which
2276 * could resize the dict. :-(
2277 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002278 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 n = mp->ma_used;
2280 v = PyList_New(n);
2281 if (v == NULL)
2282 return NULL;
2283 for (i = 0; i < n; i++) {
2284 item = PyTuple_New(2);
2285 if (item == NULL) {
2286 Py_DECREF(v);
2287 return NULL;
2288 }
2289 PyList_SET_ITEM(v, i, item);
2290 }
2291 if (n != mp->ma_used) {
2292 /* Durnit. The allocations caused the dict to resize.
2293 * Just start over, this shouldn't normally happen.
2294 */
2295 Py_DECREF(v);
2296 goto again;
2297 }
2298 /* Nothing we do below makes any function calls. */
Victor Stinner742da042016-09-07 17:40:12 -07002299 ep = DK_ENTRIES(mp->ma_keys);
2300 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002301 if (mp->ma_values) {
2302 value_ptr = mp->ma_values;
2303 offset = sizeof(PyObject *);
2304 }
2305 else {
2306 value_ptr = &ep[0].me_value;
2307 offset = sizeof(PyDictKeyEntry);
2308 }
2309 for (i = 0, j = 0; i < size; i++) {
2310 PyObject *value = *value_ptr;
2311 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2312 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 key = ep[i].me_key;
2314 item = PyList_GET_ITEM(v, j);
2315 Py_INCREF(key);
2316 PyTuple_SET_ITEM(item, 0, key);
2317 Py_INCREF(value);
2318 PyTuple_SET_ITEM(item, 1, value);
2319 j++;
2320 }
2321 }
2322 assert(j == n);
2323 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002324}
2325
Larry Hastings5c661892014-01-24 06:17:25 -08002326/*[clinic input]
2327@classmethod
2328dict.fromkeys
Larry Hastings5c661892014-01-24 06:17:25 -08002329 iterable: object
2330 value: object=None
2331 /
2332
2333Returns a new dict with keys from iterable and values equal to value.
2334[clinic start generated code]*/
2335
Larry Hastings5c661892014-01-24 06:17:25 -08002336static PyObject *
2337dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002338/*[clinic end generated code: output=8fb98e4b10384999 input=b85a667f9bf4669d]*/
Larry Hastings5c661892014-01-24 06:17:25 -08002339{
Eric Snow96c6af92015-05-29 22:21:39 -06002340 return _PyDict_FromKeys((PyObject *)type, iterable, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002341}
2342
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002343static int
Victor Stinner742da042016-09-07 17:40:12 -07002344dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
2345 const char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 PyObject *arg = NULL;
2348 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
2351 result = -1;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 else if (arg != NULL) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02002354 _Py_IDENTIFIER(keys);
2355 if (_PyObject_HasAttrId(arg, &PyId_keys))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 result = PyDict_Merge(self, arg, 1);
2357 else
2358 result = PyDict_MergeFromSeq2(self, arg, 1);
2359 }
2360 if (result == 0 && kwds != NULL) {
2361 if (PyArg_ValidateKeywordArguments(kwds))
2362 result = PyDict_Merge(self, kwds, 1);
2363 else
2364 result = -1;
2365 }
2366 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002367}
2368
2369static PyObject *
2370dict_update(PyObject *self, PyObject *args, PyObject *kwds)
2371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 if (dict_update_common(self, args, kwds, "update") != -1)
2373 Py_RETURN_NONE;
2374 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002375}
2376
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002377/* Update unconditionally replaces existing items.
2378 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00002379 otherwise it leaves existing items unchanged.
2380
2381 PyDict_{Update,Merge} update/merge from a mapping object.
2382
Tim Petersf582b822001-12-11 18:51:08 +00002383 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00002384 producing iterable objects of length 2.
2385*/
2386
Tim Petersf582b822001-12-11 18:51:08 +00002387int
Tim Peters1fc240e2001-10-26 05:06:50 +00002388PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
2389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 PyObject *it; /* iter(seq2) */
2391 Py_ssize_t i; /* index into seq2 of current element */
2392 PyObject *item; /* seq2[i] */
2393 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00002394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 assert(d != NULL);
2396 assert(PyDict_Check(d));
2397 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 it = PyObject_GetIter(seq2);
2400 if (it == NULL)
2401 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 for (i = 0; ; ++i) {
2404 PyObject *key, *value;
2405 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00002406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 fast = NULL;
2408 item = PyIter_Next(it);
2409 if (item == NULL) {
2410 if (PyErr_Occurred())
2411 goto Fail;
2412 break;
2413 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 /* Convert item to sequence, and verify length 2. */
2416 fast = PySequence_Fast(item, "");
2417 if (fast == NULL) {
2418 if (PyErr_ExceptionMatches(PyExc_TypeError))
2419 PyErr_Format(PyExc_TypeError,
2420 "cannot convert dictionary update "
2421 "sequence element #%zd to a sequence",
2422 i);
2423 goto Fail;
2424 }
2425 n = PySequence_Fast_GET_SIZE(fast);
2426 if (n != 2) {
2427 PyErr_Format(PyExc_ValueError,
2428 "dictionary update sequence element #%zd "
2429 "has length %zd; 2 is required",
2430 i, n);
2431 goto Fail;
2432 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 /* Update/merge with this (key, value) pair. */
2435 key = PySequence_Fast_GET_ITEM(fast, 0);
2436 value = PySequence_Fast_GET_ITEM(fast, 1);
Serhiy Storchaka564398a2017-05-20 13:06:26 +03002437 Py_INCREF(key);
2438 Py_INCREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 if (override || PyDict_GetItem(d, key) == NULL) {
2440 int status = PyDict_SetItem(d, key, value);
Serhiy Storchaka564398a2017-05-20 13:06:26 +03002441 if (status < 0) {
2442 Py_DECREF(key);
2443 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 goto Fail;
Serhiy Storchaka564398a2017-05-20 13:06:26 +03002445 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 }
Serhiy Storchaka564398a2017-05-20 13:06:26 +03002447 Py_DECREF(key);
2448 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 Py_DECREF(fast);
2450 Py_DECREF(item);
2451 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 i = 0;
Victor Stinner611b0fa2016-09-14 15:02:01 +02002454 assert(_PyDict_CheckConsistency((PyDictObject *)d));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00002456Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 Py_XDECREF(item);
2458 Py_XDECREF(fast);
2459 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002460Return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 Py_DECREF(it);
2462 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00002463}
2464
doko@ubuntu.comde69ee72016-10-11 08:04:02 +02002465static int
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002466dict_merge(PyObject *a, PyObject *b, int override)
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002467{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002468 PyDictObject *mp, *other;
2469 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -07002470 PyDictKeyEntry *entry, *ep0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002471
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002472 assert(0 <= override && override <= 2);
2473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 /* We accept for the argument either a concrete dictionary object,
2475 * or an abstract "mapping" object. For the former, we can do
2476 * things quite efficiently. For the latter, we only require that
2477 * PyMapping_Keys() and PyObject_GetItem() be supported.
2478 */
2479 if (a == NULL || !PyDict_Check(a) || b == NULL) {
2480 PyErr_BadInternalCall();
2481 return -1;
2482 }
2483 mp = (PyDictObject*)a;
2484 if (PyDict_Check(b)) {
2485 other = (PyDictObject*)b;
2486 if (other == mp || other->ma_used == 0)
2487 /* a.update(a) or a.update({}); nothing to do */
2488 return 0;
2489 if (mp->ma_used == 0)
2490 /* Since the target dict is empty, PyDict_GetItem()
2491 * always returns NULL. Setting override to 1
2492 * skips the unnecessary test.
2493 */
2494 override = 1;
2495 /* Do one big resize at the start, rather than
2496 * incrementally resizing as we insert new items. Expect
2497 * that there will be no (or few) overlapping keys.
2498 */
INADA Naokib1152be2016-10-27 19:26:50 +09002499 if (USABLE_FRACTION(mp->ma_keys->dk_size) < other->ma_used) {
2500 if (dictresize(mp, ESTIMATE_SIZE(mp->ma_used + other->ma_used))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 return -1;
INADA Naokib1152be2016-10-27 19:26:50 +09002502 }
2503 }
Victor Stinner742da042016-09-07 17:40:12 -07002504 ep0 = DK_ENTRIES(other->ma_keys);
2505 for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002506 PyObject *key, *value;
2507 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002508 entry = &ep0[i];
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002509 key = entry->me_key;
2510 hash = entry->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002511 if (other->ma_values)
2512 value = other->ma_values[i];
2513 else
2514 value = entry->me_value;
2515
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002516 if (value != NULL) {
2517 int err = 0;
2518 Py_INCREF(key);
2519 Py_INCREF(value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002520 if (override == 1)
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002521 err = insertdict(mp, key, hash, value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002522 else if (_PyDict_GetItem_KnownHash(a, key, hash) == NULL) {
2523 if (PyErr_Occurred()) {
2524 Py_DECREF(value);
2525 Py_DECREF(key);
2526 return -1;
2527 }
2528 err = insertdict(mp, key, hash, value);
2529 }
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002530 else if (override != 0) {
2531 _PyErr_SetKeyError(key);
2532 Py_DECREF(value);
2533 Py_DECREF(key);
2534 return -1;
2535 }
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002536 Py_DECREF(value);
2537 Py_DECREF(key);
2538 if (err != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 return -1;
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002540
Victor Stinner742da042016-09-07 17:40:12 -07002541 if (n != other->ma_keys->dk_nentries) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002542 PyErr_SetString(PyExc_RuntimeError,
2543 "dict mutated during update");
2544 return -1;
2545 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 }
2547 }
2548 }
2549 else {
2550 /* Do it the generic, slower way */
2551 PyObject *keys = PyMapping_Keys(b);
2552 PyObject *iter;
2553 PyObject *key, *value;
2554 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 if (keys == NULL)
2557 /* Docstring says this is equivalent to E.keys() so
2558 * if E doesn't have a .keys() method we want
2559 * AttributeError to percolate up. Might as well
2560 * do the same for any other error.
2561 */
2562 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 iter = PyObject_GetIter(keys);
2565 Py_DECREF(keys);
2566 if (iter == NULL)
2567 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002570 if (override != 1 && PyDict_GetItem(a, key) != NULL) {
2571 if (override != 0) {
2572 _PyErr_SetKeyError(key);
2573 Py_DECREF(key);
2574 Py_DECREF(iter);
2575 return -1;
2576 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 Py_DECREF(key);
2578 continue;
2579 }
2580 value = PyObject_GetItem(b, key);
2581 if (value == NULL) {
2582 Py_DECREF(iter);
2583 Py_DECREF(key);
2584 return -1;
2585 }
2586 status = PyDict_SetItem(a, key, value);
2587 Py_DECREF(key);
2588 Py_DECREF(value);
2589 if (status < 0) {
2590 Py_DECREF(iter);
2591 return -1;
2592 }
2593 }
2594 Py_DECREF(iter);
2595 if (PyErr_Occurred())
2596 /* Iterator completed, via error */
2597 return -1;
2598 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02002599 assert(_PyDict_CheckConsistency((PyDictObject *)a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002601}
2602
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002603int
2604PyDict_Update(PyObject *a, PyObject *b)
2605{
2606 return dict_merge(a, b, 1);
2607}
2608
2609int
2610PyDict_Merge(PyObject *a, PyObject *b, int override)
2611{
2612 /* XXX Deprecate override not in (0, 1). */
2613 return dict_merge(a, b, override != 0);
2614}
2615
2616int
2617_PyDict_MergeEx(PyObject *a, PyObject *b, int override)
2618{
2619 return dict_merge(a, b, override);
2620}
2621
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002622static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002623dict_copy(PyDictObject *mp)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002626}
2627
2628PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002629PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 PyObject *copy;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002632 PyDictObject *mp;
2633 Py_ssize_t i, n;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 if (o == NULL || !PyDict_Check(o)) {
2636 PyErr_BadInternalCall();
2637 return NULL;
2638 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002639 mp = (PyDictObject *)o;
2640 if (_PyDict_HasSplitTable(mp)) {
2641 PyDictObject *split_copy;
Victor Stinner742da042016-09-07 17:40:12 -07002642 Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
2643 PyObject **newvalues;
2644 newvalues = new_values(size);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002645 if (newvalues == NULL)
2646 return PyErr_NoMemory();
2647 split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
2648 if (split_copy == NULL) {
2649 free_values(newvalues);
2650 return NULL;
2651 }
2652 split_copy->ma_values = newvalues;
2653 split_copy->ma_keys = mp->ma_keys;
2654 split_copy->ma_used = mp->ma_used;
2655 DK_INCREF(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002656 for (i = 0, n = size; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002657 PyObject *value = mp->ma_values[i];
2658 Py_XINCREF(value);
2659 split_copy->ma_values[i] = value;
2660 }
Benjamin Peterson7ce67e42012-04-24 10:32:57 -04002661 if (_PyObject_GC_IS_TRACKED(mp))
2662 _PyObject_GC_TRACK(split_copy);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002663 return (PyObject *)split_copy;
2664 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 copy = PyDict_New();
2666 if (copy == NULL)
2667 return NULL;
2668 if (PyDict_Merge(copy, o, 1) == 0)
2669 return copy;
2670 Py_DECREF(copy);
2671 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002672}
2673
Martin v. Löwis18e16552006-02-15 17:27:45 +00002674Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00002675PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00002676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 if (mp == NULL || !PyDict_Check(mp)) {
2678 PyErr_BadInternalCall();
2679 return -1;
2680 }
2681 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00002682}
2683
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002684PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002685PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 if (mp == NULL || !PyDict_Check(mp)) {
2688 PyErr_BadInternalCall();
2689 return NULL;
2690 }
2691 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002692}
2693
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002694PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002695PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 if (mp == NULL || !PyDict_Check(mp)) {
2698 PyErr_BadInternalCall();
2699 return NULL;
2700 }
2701 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002702}
2703
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002704PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002705PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 if (mp == NULL || !PyDict_Check(mp)) {
2708 PyErr_BadInternalCall();
2709 return NULL;
2710 }
2711 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002712}
2713
Tim Peterse63415e2001-05-08 04:38:29 +00002714/* Return 1 if dicts equal, 0 if not, -1 if error.
2715 * Gets out as soon as any difference is detected.
2716 * Uses only Py_EQ comparison.
2717 */
2718static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002719dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00002720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00002722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 if (a->ma_used != b->ma_used)
2724 /* can't be equal if # of entries differ */
2725 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Victor Stinner742da042016-09-07 17:40:12 -07002727 for (i = 0; i < a->ma_keys->dk_nentries; i++) {
2728 PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002729 PyObject *aval;
2730 if (a->ma_values)
2731 aval = a->ma_values[i];
2732 else
2733 aval = ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 if (aval != NULL) {
2735 int cmp;
2736 PyObject *bval;
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002737 PyObject **vaddr;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002738 PyObject *key = ep->me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 /* temporarily bump aval's refcount to ensure it stays
2740 alive until we're done with it */
2741 Py_INCREF(aval);
2742 /* ditto for key */
2743 Py_INCREF(key);
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002744 /* reuse the known hash value */
Victor Stinner742da042016-09-07 17:40:12 -07002745 if ((b->ma_keys->dk_lookup)(b, key, ep->me_hash, &vaddr, NULL) < 0)
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002746 bval = NULL;
2747 else
2748 bval = *vaddr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 if (bval == NULL) {
Serhiy Storchaka564398a2017-05-20 13:06:26 +03002750 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 Py_DECREF(aval);
2752 if (PyErr_Occurred())
2753 return -1;
2754 return 0;
2755 }
2756 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
Serhiy Storchaka564398a2017-05-20 13:06:26 +03002757 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 Py_DECREF(aval);
2759 if (cmp <= 0) /* error or not equal */
2760 return cmp;
2761 }
2762 }
2763 return 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002764}
Tim Peterse63415e2001-05-08 04:38:29 +00002765
2766static PyObject *
2767dict_richcompare(PyObject *v, PyObject *w, int op)
2768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 int cmp;
2770 PyObject *res;
Tim Peterse63415e2001-05-08 04:38:29 +00002771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 if (!PyDict_Check(v) || !PyDict_Check(w)) {
2773 res = Py_NotImplemented;
2774 }
2775 else if (op == Py_EQ || op == Py_NE) {
2776 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
2777 if (cmp < 0)
2778 return NULL;
2779 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
2780 }
2781 else
2782 res = Py_NotImplemented;
2783 Py_INCREF(res);
2784 return res;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002785}
Tim Peterse63415e2001-05-08 04:38:29 +00002786
Larry Hastings61272b72014-01-07 12:41:53 -08002787/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002788
2789@coexist
2790dict.__contains__
2791
2792 key: object
2793 /
2794
Meador Ingee02de8c2014-01-14 16:48:31 -06002795True if D has a key k, else False.
Larry Hastings61272b72014-01-07 12:41:53 -08002796[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002797
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002798static PyObject *
Larry Hastingsc2047262014-01-25 20:43:29 -08002799dict___contains__(PyDictObject *self, PyObject *key)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002800/*[clinic end generated code: output=a3d03db709ed6e6b input=b852b2a19b51ab24]*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002801{
Larry Hastingsc2047262014-01-25 20:43:29 -08002802 register PyDictObject *mp = self;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002803 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002804 Py_ssize_t ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002805 PyObject **value_addr;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002808 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 hash = PyObject_Hash(key);
2810 if (hash == -1)
2811 return NULL;
2812 }
Victor Stinner742da042016-09-07 17:40:12 -07002813 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2814 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002816 if (ix == DKIX_EMPTY || *value_addr == NULL)
2817 Py_RETURN_FALSE;
2818 Py_RETURN_TRUE;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002819}
2820
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002821static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002822dict_get(PyDictObject *mp, PyObject *args)
Barry Warsawc38c5da1997-10-06 17:49:20 +00002823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 PyObject *key;
2825 PyObject *failobj = Py_None;
2826 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002827 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002828 Py_ssize_t ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002829 PyObject **value_addr;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
2832 return NULL;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002835 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 hash = PyObject_Hash(key);
2837 if (hash == -1)
2838 return NULL;
2839 }
Victor Stinner742da042016-09-07 17:40:12 -07002840 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2841 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002843 if (ix == DKIX_EMPTY || *value_addr == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 val = failobj;
Victor Stinner742da042016-09-07 17:40:12 -07002845 else
2846 val = *value_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 Py_INCREF(val);
2848 return val;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002849}
2850
Benjamin Peterson00e98862013-03-07 22:16:29 -05002851PyObject *
2852PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
Guido van Rossum164452c2000-08-08 16:12:54 +00002853{
Benjamin Peterson00e98862013-03-07 22:16:29 -05002854 PyDictObject *mp = (PyDictObject *)d;
INADA Naoki93f26f72016-11-02 18:45:16 +09002855 PyObject *value;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002856 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002857 Py_ssize_t hashpos, ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002858 PyObject **value_addr;
Guido van Rossum164452c2000-08-08 16:12:54 +00002859
Benjamin Peterson00e98862013-03-07 22:16:29 -05002860 if (!PyDict_Check(d)) {
2861 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 return NULL;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002863 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002866 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 hash = PyObject_Hash(key);
2868 if (hash == -1)
2869 return NULL;
2870 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002871
2872 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
2873 if (insertion_resize(mp) < 0)
2874 return NULL;
2875 }
2876
Victor Stinner742da042016-09-07 17:40:12 -07002877 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
2878 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 return NULL;
INADA Naoki93f26f72016-11-02 18:45:16 +09002880
2881 if (_PyDict_HasSplitTable(mp) &&
2882 ((ix >= 0 && *value_addr == NULL && mp->ma_used != ix) ||
2883 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
2884 if (insertion_resize(mp) < 0) {
2885 return NULL;
2886 }
2887 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
2888 ix = DKIX_EMPTY;
2889 }
2890
2891 if (ix == DKIX_EMPTY) {
2892 PyDictKeyEntry *ep, *ep0;
2893 value = defaultobj;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002894 if (mp->ma_keys->dk_usable <= 0) {
Victor Stinner3c336c52016-09-12 14:17:40 +02002895 if (insertion_resize(mp) < 0) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002896 return NULL;
Victor Stinner3c336c52016-09-12 14:17:40 +02002897 }
Victor Stinner742da042016-09-07 17:40:12 -07002898 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002899 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002900 ep0 = DK_ENTRIES(mp->ma_keys);
2901 ep = &ep0[mp->ma_keys->dk_nentries];
2902 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
Benjamin Petersonb1efa532013-03-04 09:47:50 -05002903 Py_INCREF(key);
INADA Naoki93f26f72016-11-02 18:45:16 +09002904 Py_INCREF(value);
2905 MAINTAIN_TRACKING(mp, key, value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002906 ep->me_key = key;
2907 ep->me_hash = hash;
Victor Stinner742da042016-09-07 17:40:12 -07002908 if (mp->ma_values) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002909 assert(mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
2910 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Victor Stinner742da042016-09-07 17:40:12 -07002911 }
2912 else {
INADA Naoki93f26f72016-11-02 18:45:16 +09002913 ep->me_value = value;
Victor Stinner742da042016-09-07 17:40:12 -07002914 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002915 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07002916 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naoki93f26f72016-11-02 18:45:16 +09002917 mp->ma_keys->dk_usable--;
2918 mp->ma_keys->dk_nentries++;
2919 assert(mp->ma_keys->dk_usable >= 0);
2920 }
2921 else if (*value_addr == NULL) {
2922 value = defaultobj;
2923 assert(_PyDict_HasSplitTable(mp));
2924 assert(ix == mp->ma_used);
2925 Py_INCREF(value);
2926 MAINTAIN_TRACKING(mp, key, value);
2927 *value_addr = value;
2928 mp->ma_used++;
2929 mp->ma_version_tag = DICT_NEXT_VERSION();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02002931 else {
INADA Naoki93f26f72016-11-02 18:45:16 +09002932 value = *value_addr;
Victor Stinner611b0fa2016-09-14 15:02:01 +02002933 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002934
2935 assert(_PyDict_CheckConsistency(mp));
2936 return value;
Guido van Rossum164452c2000-08-08 16:12:54 +00002937}
2938
Benjamin Peterson00e98862013-03-07 22:16:29 -05002939static PyObject *
2940dict_setdefault(PyDictObject *mp, PyObject *args)
2941{
2942 PyObject *key, *val;
2943 PyObject *defaultobj = Py_None;
2944
2945 if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &defaultobj))
2946 return NULL;
2947
Benjamin Peterson55898502013-03-08 08:36:49 -05002948 val = PyDict_SetDefault((PyObject *)mp, key, defaultobj);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002949 Py_XINCREF(val);
2950 return val;
2951}
Guido van Rossum164452c2000-08-08 16:12:54 +00002952
2953static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002954dict_clear(PyDictObject *mp)
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 PyDict_Clear((PyObject *)mp);
2957 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002958}
2959
Guido van Rossumba6ab842000-12-12 22:02:18 +00002960static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002961dict_pop(PyDictObject *mp, PyObject *args)
Guido van Rossume027d982002-04-12 15:11:59 +00002962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 PyObject *key, *deflt = NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00002964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
2966 return NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06002967
Yury Selivanov684ef2c2016-10-28 19:01:21 -04002968 return _PyDict_Pop((PyObject*)mp, key, deflt);
Guido van Rossume027d982002-04-12 15:11:59 +00002969}
2970
2971static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002972dict_popitem(PyDictObject *mp)
Guido van Rossumba6ab842000-12-12 22:02:18 +00002973{
Victor Stinner742da042016-09-07 17:40:12 -07002974 Py_ssize_t i, j;
2975 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 PyObject *res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 /* Allocate the result tuple before checking the size. Believe it
2979 * or not, this allocation could trigger a garbage collection which
2980 * could empty the dict, so if we checked the size first and that
2981 * happened, the result would be an infinite loop (searching for an
2982 * entry that no longer exists). Note that the usual popitem()
2983 * idiom is "while d: k, v = d.popitem()". so needing to throw the
2984 * tuple away if the dict *is* empty isn't a significant
2985 * inefficiency -- possible, but unlikely in practice.
2986 */
2987 res = PyTuple_New(2);
2988 if (res == NULL)
2989 return NULL;
2990 if (mp->ma_used == 0) {
2991 Py_DECREF(res);
2992 PyErr_SetString(PyExc_KeyError,
2993 "popitem(): dictionary is empty");
2994 return NULL;
2995 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002996 /* Convert split table to combined table */
2997 if (mp->ma_keys->dk_lookup == lookdict_split) {
2998 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
2999 Py_DECREF(res);
3000 return NULL;
3001 }
3002 }
3003 ENSURE_ALLOWS_DELETIONS(mp);
Victor Stinner742da042016-09-07 17:40:12 -07003004
3005 /* Pop last item */
3006 ep0 = DK_ENTRIES(mp->ma_keys);
3007 i = mp->ma_keys->dk_nentries - 1;
3008 while (i >= 0 && ep0[i].me_value == NULL) {
3009 i--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 }
Victor Stinner742da042016-09-07 17:40:12 -07003011 assert(i >= 0);
3012
3013 ep = &ep0[i];
3014 j = lookdict_index(mp->ma_keys, ep->me_hash, i);
3015 assert(j >= 0);
3016 assert(dk_get_index(mp->ma_keys, j) == i);
3017 dk_set_index(mp->ma_keys, j, DKIX_DUMMY);
3018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 PyTuple_SET_ITEM(res, 0, ep->me_key);
3020 PyTuple_SET_ITEM(res, 1, ep->me_value);
Victor Stinner742da042016-09-07 17:40:12 -07003021 ep->me_key = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 ep->me_value = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07003023 /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
3024 mp->ma_keys->dk_nentries = i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07003026 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner611b0fa2016-09-14 15:02:01 +02003027 assert(_PyDict_CheckConsistency(mp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 return res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00003029}
3030
Jeremy Hylton8caad492000-06-23 14:18:11 +00003031static int
3032dict_traverse(PyObject *op, visitproc visit, void *arg)
3033{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003034 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson55f44522016-09-05 12:12:59 -07003035 PyDictKeysObject *keys = mp->ma_keys;
Serhiy Storchaka46825d22016-09-26 21:29:34 +03003036 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Victor Stinner742da042016-09-07 17:40:12 -07003037 Py_ssize_t i, n = keys->dk_nentries;
3038
Benjamin Peterson55f44522016-09-05 12:12:59 -07003039 if (keys->dk_lookup == lookdict) {
3040 for (i = 0; i < n; i++) {
3041 if (entries[i].me_value != NULL) {
3042 Py_VISIT(entries[i].me_value);
3043 Py_VISIT(entries[i].me_key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003044 }
3045 }
Victor Stinner742da042016-09-07 17:40:12 -07003046 }
3047 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003048 if (mp->ma_values != NULL) {
Benjamin Peterson55f44522016-09-05 12:12:59 -07003049 for (i = 0; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003050 Py_VISIT(mp->ma_values[i]);
3051 }
3052 }
3053 else {
Benjamin Peterson55f44522016-09-05 12:12:59 -07003054 for (i = 0; i < n; i++) {
3055 Py_VISIT(entries[i].me_value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003056 }
3057 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 }
3059 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00003060}
3061
3062static int
3063dict_tp_clear(PyObject *op)
3064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 PyDict_Clear(op);
3066 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00003067}
3068
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003069static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003070
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003071Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003072_PyDict_SizeOf(PyDictObject *mp)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003073{
Victor Stinner742da042016-09-07 17:40:12 -07003074 Py_ssize_t size, usable, res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003075
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003076 size = DK_SIZE(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07003077 usable = USABLE_FRACTION(size);
3078
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02003079 res = _PyObject_SIZE(Py_TYPE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003080 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07003081 res += usable * sizeof(PyObject*);
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003082 /* If the dictionary is split, the keys portion is accounted-for
3083 in the type object. */
3084 if (mp->ma_keys->dk_refcnt == 1)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003085 res += (sizeof(PyDictKeysObject)
3086 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
3087 + DK_IXSIZE(mp->ma_keys) * size
3088 + sizeof(PyDictKeyEntry) * usable);
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003089 return res;
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003090}
3091
3092Py_ssize_t
3093_PyDict_KeysSize(PyDictKeysObject *keys)
3094{
Victor Stinner98ee9d52016-09-08 09:33:56 -07003095 return (sizeof(PyDictKeysObject)
3096 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
3097 + DK_IXSIZE(keys) * DK_SIZE(keys)
3098 + USABLE_FRACTION(DK_SIZE(keys)) * sizeof(PyDictKeyEntry));
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003099}
3100
doko@ubuntu.com17210f52016-01-14 14:04:59 +01003101static PyObject *
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003102dict_sizeof(PyDictObject *mp)
3103{
3104 return PyLong_FromSsize_t(_PyDict_SizeOf(mp));
3105}
3106
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003107PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
3108
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003109PyDoc_STRVAR(sizeof__doc__,
3110"D.__sizeof__() -> size of D in memory, in bytes");
3111
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003112PyDoc_STRVAR(get__doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00003113"D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.");
Tim Petersf7f88b12000-12-13 23:18:45 +00003114
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003115PyDoc_STRVAR(setdefault_doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00003116"D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D");
Tim Petersf7f88b12000-12-13 23:18:45 +00003117
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003118PyDoc_STRVAR(pop__doc__,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00003119"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00003120If key is not found, d is returned if given, otherwise KeyError is raised");
Guido van Rossume027d982002-04-12 15:11:59 +00003121
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003122PyDoc_STRVAR(popitem__doc__,
Tim Petersf7f88b12000-12-13 23:18:45 +00003123"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000031242-tuple; but raise KeyError if D is empty.");
Tim Petersf7f88b12000-12-13 23:18:45 +00003125
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003126PyDoc_STRVAR(update__doc__,
Brett Cannonf2754162013-05-11 14:46:48 -04003127"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n\
3128If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]\n\
3129If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n\
3130In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00003131
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003132PyDoc_STRVAR(clear__doc__,
3133"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00003134
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003135PyDoc_STRVAR(copy__doc__,
3136"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00003137
Guido van Rossumb90c8482007-02-10 01:11:45 +00003138/* Forward */
3139static PyObject *dictkeys_new(PyObject *);
3140static PyObject *dictitems_new(PyObject *);
3141static PyObject *dictvalues_new(PyObject *);
3142
Guido van Rossum45c85d12007-07-27 16:31:40 +00003143PyDoc_STRVAR(keys__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 "D.keys() -> a set-like object providing a view on D's keys");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003145PyDoc_STRVAR(items__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 "D.items() -> a set-like object providing a view on D's items");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003147PyDoc_STRVAR(values__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 "D.values() -> an object providing a view on D's values");
Guido van Rossumb90c8482007-02-10 01:11:45 +00003149
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003150static PyMethodDef mapp_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -07003151 DICT___CONTAINS___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
3153 getitem__doc__},
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003154 {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 sizeof__doc__},
3156 {"get", (PyCFunction)dict_get, METH_VARARGS,
3157 get__doc__},
3158 {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS,
3159 setdefault_doc__},
3160 {"pop", (PyCFunction)dict_pop, METH_VARARGS,
3161 pop__doc__},
3162 {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
3163 popitem__doc__},
3164 {"keys", (PyCFunction)dictkeys_new, METH_NOARGS,
3165 keys__doc__},
3166 {"items", (PyCFunction)dictitems_new, METH_NOARGS,
3167 items__doc__},
3168 {"values", (PyCFunction)dictvalues_new, METH_NOARGS,
3169 values__doc__},
3170 {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
3171 update__doc__},
Larry Hastings5c661892014-01-24 06:17:25 -08003172 DICT_FROMKEYS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
3174 clear__doc__},
3175 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
3176 copy__doc__},
3177 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003178};
3179
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00003180/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00003181int
3182PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003183{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003184 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07003185 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003187 PyObject **value_addr;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003190 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 hash = PyObject_Hash(key);
3192 if (hash == -1)
3193 return -1;
3194 }
Victor Stinner742da042016-09-07 17:40:12 -07003195 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
3196 if (ix == DKIX_ERROR)
3197 return -1;
3198 return (ix != DKIX_EMPTY && *value_addr != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003199}
3200
Thomas Wouterscf297e42007-02-23 15:07:44 +00003201/* Internal version of PyDict_Contains used when the hash value is already known */
3202int
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003203_PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00003204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003206 PyObject **value_addr;
Victor Stinner742da042016-09-07 17:40:12 -07003207 Py_ssize_t ix;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003208
Victor Stinner742da042016-09-07 17:40:12 -07003209 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
3210 if (ix == DKIX_ERROR)
3211 return -1;
3212 return (ix != DKIX_EMPTY && *value_addr != NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00003213}
3214
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003215/* Hack to implement "key in dict" */
3216static PySequenceMethods dict_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 0, /* sq_length */
3218 0, /* sq_concat */
3219 0, /* sq_repeat */
3220 0, /* sq_item */
3221 0, /* sq_slice */
3222 0, /* sq_ass_item */
3223 0, /* sq_ass_slice */
3224 PyDict_Contains, /* sq_contains */
3225 0, /* sq_inplace_concat */
3226 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003227};
3228
Guido van Rossum09e563a2001-05-01 12:10:21 +00003229static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003230dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 PyObject *self;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003233 PyDictObject *d;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 assert(type != NULL && type->tp_alloc != NULL);
3236 self = type->tp_alloc(type, 0);
Victor Stinnera9f61a52013-07-16 22:17:26 +02003237 if (self == NULL)
3238 return NULL;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003239 d = (PyDictObject *)self;
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003240
Victor Stinnera9f61a52013-07-16 22:17:26 +02003241 /* The object has been implicitly tracked by tp_alloc */
3242 if (type == &PyDict_Type)
3243 _PyObject_GC_UNTRACK(d);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003244
3245 d->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07003246 d->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07003247 d->ma_keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003248 if (d->ma_keys == NULL) {
3249 Py_DECREF(self);
3250 return NULL;
3251 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02003252 assert(_PyDict_CheckConsistency(d));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 return self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003254}
3255
Tim Peters25786c02001-09-02 08:22:48 +00003256static int
3257dict_init(PyObject *self, PyObject *args, PyObject *kwds)
3258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00003260}
3261
Tim Peters6d6c1a32001-08-02 04:15:00 +00003262static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003263dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00003264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003266}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003267
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003268PyDoc_STRVAR(dictionary_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00003269"dict() -> new empty dictionary\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00003270"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003271" (key, value) pairs\n"
3272"dict(iterable) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00003273" d = {}\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003274" for k, v in iterable:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00003275" d[k] = v\n"
3276"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
3277" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00003278
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003279PyTypeObject PyDict_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3281 "dict",
3282 sizeof(PyDictObject),
3283 0,
3284 (destructor)dict_dealloc, /* tp_dealloc */
3285 0, /* tp_print */
3286 0, /* tp_getattr */
3287 0, /* tp_setattr */
3288 0, /* tp_reserved */
3289 (reprfunc)dict_repr, /* tp_repr */
3290 0, /* tp_as_number */
3291 &dict_as_sequence, /* tp_as_sequence */
3292 &dict_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003293 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 0, /* tp_call */
3295 0, /* tp_str */
3296 PyObject_GenericGetAttr, /* tp_getattro */
3297 0, /* tp_setattro */
3298 0, /* tp_as_buffer */
3299 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3300 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
3301 dictionary_doc, /* tp_doc */
3302 dict_traverse, /* tp_traverse */
3303 dict_tp_clear, /* tp_clear */
3304 dict_richcompare, /* tp_richcompare */
3305 0, /* tp_weaklistoffset */
3306 (getiterfunc)dict_iter, /* tp_iter */
3307 0, /* tp_iternext */
3308 mapp_methods, /* tp_methods */
3309 0, /* tp_members */
3310 0, /* tp_getset */
3311 0, /* tp_base */
3312 0, /* tp_dict */
3313 0, /* tp_descr_get */
3314 0, /* tp_descr_set */
3315 0, /* tp_dictoffset */
3316 dict_init, /* tp_init */
3317 PyType_GenericAlloc, /* tp_alloc */
3318 dict_new, /* tp_new */
3319 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003320};
3321
Victor Stinner3c1e4812012-03-26 22:10:51 +02003322PyObject *
3323_PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
3324{
3325 PyObject *kv;
3326 kv = _PyUnicode_FromId(key); /* borrowed */
Victor Stinner5b3b1002013-07-22 23:50:57 +02003327 if (kv == NULL) {
3328 PyErr_Clear();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003329 return NULL;
Victor Stinner5b3b1002013-07-22 23:50:57 +02003330 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003331 return PyDict_GetItem(dp, kv);
3332}
3333
Guido van Rossum3cca2451997-05-16 14:23:33 +00003334/* For backward compatibility with old dictionary interface */
3335
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003336PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003337PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003339 PyObject *kv, *rv;
3340 kv = PyUnicode_FromString(key);
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003341 if (kv == NULL) {
3342 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 return NULL;
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003344 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 rv = PyDict_GetItem(v, kv);
3346 Py_DECREF(kv);
3347 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003348}
3349
3350int
Victor Stinner3c1e4812012-03-26 22:10:51 +02003351_PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
3352{
3353 PyObject *kv;
3354 kv = _PyUnicode_FromId(key); /* borrowed */
3355 if (kv == NULL)
3356 return -1;
3357 return PyDict_SetItem(v, kv, item);
3358}
3359
3360int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003361PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 PyObject *kv;
3364 int err;
3365 kv = PyUnicode_FromString(key);
3366 if (kv == NULL)
3367 return -1;
3368 PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
3369 err = PyDict_SetItem(v, kv, item);
3370 Py_DECREF(kv);
3371 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003372}
3373
3374int
Victor Stinner5fd2e5a2013-11-06 18:58:22 +01003375_PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
3376{
3377 PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
3378 if (kv == NULL)
3379 return -1;
3380 return PyDict_DelItem(v, kv);
3381}
3382
3383int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003384PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 PyObject *kv;
3387 int err;
3388 kv = PyUnicode_FromString(key);
3389 if (kv == NULL)
3390 return -1;
3391 err = PyDict_DelItem(v, kv);
3392 Py_DECREF(kv);
3393 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003394}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003395
Raymond Hettinger019a1482004-03-18 02:41:19 +00003396/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003397
3398typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 PyObject_HEAD
3400 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
3401 Py_ssize_t di_used;
3402 Py_ssize_t di_pos;
3403 PyObject* di_result; /* reusable result tuple for iteritems */
3404 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003405} dictiterobject;
3406
3407static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003408dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 dictiterobject *di;
3411 di = PyObject_GC_New(dictiterobject, itertype);
3412 if (di == NULL)
3413 return NULL;
3414 Py_INCREF(dict);
3415 di->di_dict = dict;
3416 di->di_used = dict->ma_used;
3417 di->di_pos = 0;
3418 di->len = dict->ma_used;
3419 if (itertype == &PyDictIterItem_Type) {
3420 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
3421 if (di->di_result == NULL) {
3422 Py_DECREF(di);
3423 return NULL;
3424 }
3425 }
3426 else
3427 di->di_result = NULL;
3428 _PyObject_GC_TRACK(di);
3429 return (PyObject *)di;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003430}
3431
3432static void
3433dictiter_dealloc(dictiterobject *di)
3434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 Py_XDECREF(di->di_dict);
3436 Py_XDECREF(di->di_result);
3437 PyObject_GC_Del(di);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003438}
3439
3440static int
3441dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
3442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 Py_VISIT(di->di_dict);
3444 Py_VISIT(di->di_result);
3445 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003446}
3447
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003448static PyObject *
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003449dictiter_len(dictiterobject *di)
3450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 Py_ssize_t len = 0;
3452 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
3453 len = di->len;
3454 return PyLong_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003455}
3456
Guido van Rossumb90c8482007-02-10 01:11:45 +00003457PyDoc_STRVAR(length_hint_doc,
3458 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003459
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003460static PyObject *
3461dictiter_reduce(dictiterobject *di);
3462
3463PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3464
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003465static PyMethodDef dictiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS,
3467 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003468 {"__reduce__", (PyCFunction)dictiter_reduce, METH_NOARGS,
3469 reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003470 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003471};
3472
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003473static PyObject*
3474dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00003475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 PyObject *key;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003477 Py_ssize_t i, n;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003478 PyDictKeysObject *k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 PyDictObject *d = di->di_dict;
Guido van Rossum213c7a62001-04-23 14:08:49 +00003480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 if (d == NULL)
3482 return NULL;
3483 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00003484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003485 if (di->di_used != d->ma_used) {
3486 PyErr_SetString(PyExc_RuntimeError,
3487 "dictionary changed size during iteration");
3488 di->di_used = -1; /* Make this state sticky */
3489 return NULL;
3490 }
Guido van Rossum2147df72002-07-16 20:30:22 +00003491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 i = di->di_pos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003493 k = d->ma_keys;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003494 n = k->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003495 if (d->ma_values) {
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003496 PyObject **value_ptr = &d->ma_values[i];
3497 while (i < n && *value_ptr == NULL) {
3498 value_ptr++;
3499 i++;
3500 }
3501 if (i >= n)
3502 goto fail;
3503 key = DK_ENTRIES(k)[i].me_key;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003504 }
3505 else {
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003506 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
3507 while (i < n && entry_ptr->me_value == NULL) {
3508 entry_ptr++;
3509 i++;
3510 }
3511 if (i >= n)
3512 goto fail;
3513 key = entry_ptr->me_key;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003514 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 di->di_pos = i+1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 di->len--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 Py_INCREF(key);
3518 return key;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003519
3520fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003522 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003524}
3525
Raymond Hettinger019a1482004-03-18 02:41:19 +00003526PyTypeObject PyDictIterKey_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3528 "dict_keyiterator", /* tp_name */
3529 sizeof(dictiterobject), /* tp_basicsize */
3530 0, /* tp_itemsize */
3531 /* methods */
3532 (destructor)dictiter_dealloc, /* tp_dealloc */
3533 0, /* tp_print */
3534 0, /* tp_getattr */
3535 0, /* tp_setattr */
3536 0, /* tp_reserved */
3537 0, /* tp_repr */
3538 0, /* tp_as_number */
3539 0, /* tp_as_sequence */
3540 0, /* tp_as_mapping */
3541 0, /* tp_hash */
3542 0, /* tp_call */
3543 0, /* tp_str */
3544 PyObject_GenericGetAttr, /* tp_getattro */
3545 0, /* tp_setattro */
3546 0, /* tp_as_buffer */
3547 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3548 0, /* tp_doc */
3549 (traverseproc)dictiter_traverse, /* tp_traverse */
3550 0, /* tp_clear */
3551 0, /* tp_richcompare */
3552 0, /* tp_weaklistoffset */
3553 PyObject_SelfIter, /* tp_iter */
3554 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
3555 dictiter_methods, /* tp_methods */
3556 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003557};
3558
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003559static PyObject *
3560dictiter_iternextvalue(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 PyObject *value;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003563 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 if (d == NULL)
3567 return NULL;
3568 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 if (di->di_used != d->ma_used) {
3571 PyErr_SetString(PyExc_RuntimeError,
3572 "dictionary changed size during iteration");
3573 di->di_used = -1; /* Make this state sticky */
3574 return NULL;
3575 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 i = di->di_pos;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003578 n = d->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003579 if (d->ma_values) {
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003580 PyObject **value_ptr = &d->ma_values[i];
3581 while (i < n && *value_ptr == NULL) {
3582 value_ptr++;
3583 i++;
3584 }
3585 if (i >= n)
3586 goto fail;
3587 value = *value_ptr;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003588 }
3589 else {
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)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003596 goto fail;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003597 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 }
3599 di->di_pos = i+1;
3600 di->len--;
3601 Py_INCREF(value);
3602 return value;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003603
3604fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003606 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003608}
3609
3610PyTypeObject PyDictIterValue_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3612 "dict_valueiterator", /* tp_name */
3613 sizeof(dictiterobject), /* tp_basicsize */
3614 0, /* tp_itemsize */
3615 /* methods */
3616 (destructor)dictiter_dealloc, /* tp_dealloc */
3617 0, /* tp_print */
3618 0, /* tp_getattr */
3619 0, /* tp_setattr */
3620 0, /* tp_reserved */
3621 0, /* tp_repr */
3622 0, /* tp_as_number */
3623 0, /* tp_as_sequence */
3624 0, /* tp_as_mapping */
3625 0, /* tp_hash */
3626 0, /* tp_call */
3627 0, /* tp_str */
3628 PyObject_GenericGetAttr, /* tp_getattro */
3629 0, /* tp_setattro */
3630 0, /* tp_as_buffer */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003631 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 0, /* tp_doc */
3633 (traverseproc)dictiter_traverse, /* tp_traverse */
3634 0, /* tp_clear */
3635 0, /* tp_richcompare */
3636 0, /* tp_weaklistoffset */
3637 PyObject_SelfIter, /* tp_iter */
3638 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
3639 dictiter_methods, /* tp_methods */
3640 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003641};
3642
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003643static PyObject *
3644dictiter_iternextitem(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003645{
Serhiy Storchaka564398a2017-05-20 13:06:26 +03003646 PyObject *key, *value, *result;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003647 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 if (d == NULL)
3651 return NULL;
3652 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 if (di->di_used != d->ma_used) {
3655 PyErr_SetString(PyExc_RuntimeError,
3656 "dictionary changed size during iteration");
3657 di->di_used = -1; /* Make this state sticky */
3658 return NULL;
3659 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003661 i = di->di_pos;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003662 n = d->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003663 if (d->ma_values) {
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003664 PyObject **value_ptr = &d->ma_values[i];
3665 while (i < n && *value_ptr == NULL) {
3666 value_ptr++;
3667 i++;
3668 }
3669 if (i >= n)
3670 goto fail;
3671 key = DK_ENTRIES(d->ma_keys)[i].me_key;
3672 value = *value_ptr;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003673 }
3674 else {
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003675 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3676 while (i < n && entry_ptr->me_value == NULL) {
3677 entry_ptr++;
3678 i++;
3679 }
3680 if (i >= n)
3681 goto fail;
3682 key = entry_ptr->me_key;
3683 value = entry_ptr->me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003684 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685 di->di_pos = i+1;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003686 di->len--;
Serhiy Storchaka564398a2017-05-20 13:06:26 +03003687 Py_INCREF(key);
3688 Py_INCREF(value);
3689 result = di->di_result;
3690 if (Py_REFCNT(result) == 1) {
3691 PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
3692 PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
3693 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3694 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 Py_INCREF(result);
Serhiy Storchaka564398a2017-05-20 13:06:26 +03003696 Py_DECREF(oldkey);
3697 Py_DECREF(oldvalue);
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003698 }
3699 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 result = PyTuple_New(2);
3701 if (result == NULL)
3702 return NULL;
Serhiy Storchaka564398a2017-05-20 13:06:26 +03003703 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3704 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003706 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003707
3708fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003709 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003710 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003711 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003712}
3713
3714PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003715 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3716 "dict_itemiterator", /* tp_name */
3717 sizeof(dictiterobject), /* tp_basicsize */
3718 0, /* tp_itemsize */
3719 /* methods */
3720 (destructor)dictiter_dealloc, /* tp_dealloc */
3721 0, /* tp_print */
3722 0, /* tp_getattr */
3723 0, /* tp_setattr */
3724 0, /* tp_reserved */
3725 0, /* tp_repr */
3726 0, /* tp_as_number */
3727 0, /* tp_as_sequence */
3728 0, /* tp_as_mapping */
3729 0, /* tp_hash */
3730 0, /* tp_call */
3731 0, /* tp_str */
3732 PyObject_GenericGetAttr, /* tp_getattro */
3733 0, /* tp_setattro */
3734 0, /* tp_as_buffer */
3735 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3736 0, /* tp_doc */
3737 (traverseproc)dictiter_traverse, /* tp_traverse */
3738 0, /* tp_clear */
3739 0, /* tp_richcompare */
3740 0, /* tp_weaklistoffset */
3741 PyObject_SelfIter, /* tp_iter */
3742 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
3743 dictiter_methods, /* tp_methods */
3744 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003745};
Guido van Rossumb90c8482007-02-10 01:11:45 +00003746
3747
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003748static PyObject *
3749dictiter_reduce(dictiterobject *di)
3750{
3751 PyObject *list;
3752 dictiterobject tmp;
3753
3754 list = PyList_New(0);
3755 if (!list)
3756 return NULL;
3757
3758 /* copy the itertor state */
3759 tmp = *di;
3760 Py_XINCREF(tmp.di_dict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003761
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003762 /* iterate the temporary into a list */
3763 for(;;) {
3764 PyObject *element = 0;
3765 if (Py_TYPE(di) == &PyDictIterItem_Type)
3766 element = dictiter_iternextitem(&tmp);
3767 else if (Py_TYPE(di) == &PyDictIterKey_Type)
3768 element = dictiter_iternextkey(&tmp);
3769 else if (Py_TYPE(di) == &PyDictIterValue_Type)
3770 element = dictiter_iternextvalue(&tmp);
3771 else
3772 assert(0);
3773 if (element) {
3774 if (PyList_Append(list, element)) {
3775 Py_DECREF(element);
3776 Py_DECREF(list);
3777 Py_XDECREF(tmp.di_dict);
3778 return NULL;
3779 }
3780 Py_DECREF(element);
3781 } else
3782 break;
3783 }
3784 Py_XDECREF(tmp.di_dict);
3785 /* check for error */
3786 if (tmp.di_dict != NULL) {
3787 /* we have an error */
3788 Py_DECREF(list);
3789 return NULL;
3790 }
Antoine Pitroua7013882012-04-05 00:04:20 +02003791 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003792}
3793
Guido van Rossum3ac67412007-02-10 18:55:06 +00003794/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003795/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00003796/***********************************************/
3797
Guido van Rossumb90c8482007-02-10 01:11:45 +00003798/* The instance lay-out is the same for all three; but the type differs. */
3799
Guido van Rossumb90c8482007-02-10 01:11:45 +00003800static void
Eric Snow96c6af92015-05-29 22:21:39 -06003801dictview_dealloc(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 Py_XDECREF(dv->dv_dict);
3804 PyObject_GC_Del(dv);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003805}
3806
3807static int
Eric Snow96c6af92015-05-29 22:21:39 -06003808dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003810 Py_VISIT(dv->dv_dict);
3811 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003812}
3813
Guido van Rossum83825ac2007-02-10 04:54:19 +00003814static Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003815dictview_len(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003817 Py_ssize_t len = 0;
3818 if (dv->dv_dict != NULL)
3819 len = dv->dv_dict->ma_used;
3820 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003821}
3822
Eric Snow96c6af92015-05-29 22:21:39 -06003823PyObject *
3824_PyDictView_New(PyObject *dict, PyTypeObject *type)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003825{
Eric Snow96c6af92015-05-29 22:21:39 -06003826 _PyDictViewObject *dv;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827 if (dict == NULL) {
3828 PyErr_BadInternalCall();
3829 return NULL;
3830 }
3831 if (!PyDict_Check(dict)) {
3832 /* XXX Get rid of this restriction later */
3833 PyErr_Format(PyExc_TypeError,
3834 "%s() requires a dict argument, not '%s'",
3835 type->tp_name, dict->ob_type->tp_name);
3836 return NULL;
3837 }
Eric Snow96c6af92015-05-29 22:21:39 -06003838 dv = PyObject_GC_New(_PyDictViewObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 if (dv == NULL)
3840 return NULL;
3841 Py_INCREF(dict);
3842 dv->dv_dict = (PyDictObject *)dict;
3843 _PyObject_GC_TRACK(dv);
3844 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003845}
3846
Neal Norwitze36f2ba2007-02-26 23:12:28 +00003847/* TODO(guido): The views objects are not complete:
3848
3849 * support more set operations
3850 * support arbitrary mappings?
3851 - either these should be static or exported in dictobject.h
3852 - if public then they should probably be in builtins
3853*/
3854
Guido van Rossumaac530c2007-08-24 22:33:45 +00003855/* Return 1 if self is a subset of other, iterating over self;
3856 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00003857static int
3858all_contained_in(PyObject *self, PyObject *other)
3859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 PyObject *iter = PyObject_GetIter(self);
3861 int ok = 1;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003863 if (iter == NULL)
3864 return -1;
3865 for (;;) {
3866 PyObject *next = PyIter_Next(iter);
3867 if (next == NULL) {
3868 if (PyErr_Occurred())
3869 ok = -1;
3870 break;
3871 }
3872 ok = PySequence_Contains(other, next);
3873 Py_DECREF(next);
3874 if (ok <= 0)
3875 break;
3876 }
3877 Py_DECREF(iter);
3878 return ok;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003879}
3880
3881static PyObject *
3882dictview_richcompare(PyObject *self, PyObject *other, int op)
3883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 Py_ssize_t len_self, len_other;
3885 int ok;
3886 PyObject *result;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 assert(self != NULL);
3889 assert(PyDictViewSet_Check(self));
3890 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00003891
Brian Curtindfc80e32011-08-10 20:28:54 -05003892 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
3893 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 len_self = PyObject_Size(self);
3896 if (len_self < 0)
3897 return NULL;
3898 len_other = PyObject_Size(other);
3899 if (len_other < 0)
3900 return NULL;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 ok = 0;
3903 switch(op) {
Guido van Rossumaac530c2007-08-24 22:33:45 +00003904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 case Py_NE:
3906 case Py_EQ:
3907 if (len_self == len_other)
3908 ok = all_contained_in(self, other);
3909 if (op == Py_NE && ok >= 0)
3910 ok = !ok;
3911 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 case Py_LT:
3914 if (len_self < len_other)
3915 ok = all_contained_in(self, other);
3916 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003918 case Py_LE:
3919 if (len_self <= len_other)
3920 ok = all_contained_in(self, other);
3921 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 case Py_GT:
3924 if (len_self > len_other)
3925 ok = all_contained_in(other, self);
3926 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 case Py_GE:
3929 if (len_self >= len_other)
3930 ok = all_contained_in(other, self);
3931 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003933 }
3934 if (ok < 0)
3935 return NULL;
3936 result = ok ? Py_True : Py_False;
3937 Py_INCREF(result);
3938 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003939}
3940
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003941static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003942dictview_repr(_PyDictViewObject *dv)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 PyObject *seq;
3945 PyObject *result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 seq = PySequence_List((PyObject *)dv);
3948 if (seq == NULL)
3949 return NULL;
3950
3951 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
3952 Py_DECREF(seq);
3953 return result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003954}
3955
Guido van Rossum3ac67412007-02-10 18:55:06 +00003956/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003957
3958static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003959dictkeys_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 if (dv->dv_dict == NULL) {
3962 Py_RETURN_NONE;
3963 }
3964 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003965}
3966
3967static int
Eric Snow96c6af92015-05-29 22:21:39 -06003968dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00003969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 if (dv->dv_dict == NULL)
3971 return 0;
3972 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003973}
3974
Guido van Rossum83825ac2007-02-10 04:54:19 +00003975static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 (lenfunc)dictview_len, /* sq_length */
3977 0, /* sq_concat */
3978 0, /* sq_repeat */
3979 0, /* sq_item */
3980 0, /* sq_slice */
3981 0, /* sq_ass_item */
3982 0, /* sq_ass_slice */
3983 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003984};
3985
Guido van Rossum523259b2007-08-24 23:41:22 +00003986static PyObject*
3987dictviews_sub(PyObject* self, PyObject *other)
3988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003989 PyObject *result = PySet_New(self);
3990 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003991 _Py_IDENTIFIER(difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 if (result == NULL)
3994 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003995
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003996 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 if (tmp == NULL) {
3998 Py_DECREF(result);
3999 return NULL;
4000 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004002 Py_DECREF(tmp);
4003 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004004}
4005
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004006PyObject*
4007_PyDictView_Intersect(PyObject* self, PyObject *other)
Guido van Rossum523259b2007-08-24 23:41:22 +00004008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004009 PyObject *result = PySet_New(self);
4010 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004011 _Py_IDENTIFIER(intersection_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004013 if (result == NULL)
4014 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004015
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08004016 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_intersection_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 if (tmp == NULL) {
4018 Py_DECREF(result);
4019 return NULL;
4020 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 Py_DECREF(tmp);
4023 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004024}
4025
4026static PyObject*
4027dictviews_or(PyObject* self, PyObject *other)
4028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004029 PyObject *result = PySet_New(self);
4030 PyObject *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02004031 _Py_IDENTIFIER(update);
Victor Stinnerd1a9cc22011-10-13 22:51:17 +02004032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004033 if (result == NULL)
4034 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004035
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08004036 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004037 if (tmp == NULL) {
4038 Py_DECREF(result);
4039 return NULL;
4040 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004042 Py_DECREF(tmp);
4043 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004044}
4045
4046static PyObject*
4047dictviews_xor(PyObject* self, PyObject *other)
4048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 PyObject *result = PySet_New(self);
4050 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004051 _Py_IDENTIFIER(symmetric_difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 if (result == NULL)
4054 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004055
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08004056 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_symmetric_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 if (tmp == NULL) {
4058 Py_DECREF(result);
4059 return NULL;
4060 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 Py_DECREF(tmp);
4063 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004064}
4065
4066static PyNumberMethods dictviews_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004067 0, /*nb_add*/
4068 (binaryfunc)dictviews_sub, /*nb_subtract*/
4069 0, /*nb_multiply*/
4070 0, /*nb_remainder*/
4071 0, /*nb_divmod*/
4072 0, /*nb_power*/
4073 0, /*nb_negative*/
4074 0, /*nb_positive*/
4075 0, /*nb_absolute*/
4076 0, /*nb_bool*/
4077 0, /*nb_invert*/
4078 0, /*nb_lshift*/
4079 0, /*nb_rshift*/
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004080 (binaryfunc)_PyDictView_Intersect, /*nb_and*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004081 (binaryfunc)dictviews_xor, /*nb_xor*/
4082 (binaryfunc)dictviews_or, /*nb_or*/
Guido van Rossum523259b2007-08-24 23:41:22 +00004083};
4084
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004085static PyObject*
4086dictviews_isdisjoint(PyObject *self, PyObject *other)
4087{
4088 PyObject *it;
4089 PyObject *item = NULL;
4090
4091 if (self == other) {
Eric Snow96c6af92015-05-29 22:21:39 -06004092 if (dictview_len((_PyDictViewObject *)self) == 0)
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004093 Py_RETURN_TRUE;
4094 else
4095 Py_RETURN_FALSE;
4096 }
4097
4098 /* Iterate over the shorter object (only if other is a set,
4099 * because PySequence_Contains may be expensive otherwise): */
4100 if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
Eric Snow96c6af92015-05-29 22:21:39 -06004101 Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004102 Py_ssize_t len_other = PyObject_Size(other);
4103 if (len_other == -1)
4104 return NULL;
4105
4106 if ((len_other > len_self)) {
4107 PyObject *tmp = other;
4108 other = self;
4109 self = tmp;
4110 }
4111 }
4112
4113 it = PyObject_GetIter(other);
4114 if (it == NULL)
4115 return NULL;
4116
4117 while ((item = PyIter_Next(it)) != NULL) {
4118 int contains = PySequence_Contains(self, item);
4119 Py_DECREF(item);
4120 if (contains == -1) {
4121 Py_DECREF(it);
4122 return NULL;
4123 }
4124
4125 if (contains) {
4126 Py_DECREF(it);
4127 Py_RETURN_FALSE;
4128 }
4129 }
4130 Py_DECREF(it);
4131 if (PyErr_Occurred())
4132 return NULL; /* PyIter_Next raised an exception. */
4133 Py_RETURN_TRUE;
4134}
4135
4136PyDoc_STRVAR(isdisjoint_doc,
4137"Return True if the view and the given iterable have a null intersection.");
4138
Guido van Rossumb90c8482007-02-10 01:11:45 +00004139static PyMethodDef dictkeys_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004140 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4141 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004142 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004143};
4144
4145PyTypeObject PyDictKeys_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4147 "dict_keys", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004148 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 0, /* tp_itemsize */
4150 /* methods */
4151 (destructor)dictview_dealloc, /* tp_dealloc */
4152 0, /* tp_print */
4153 0, /* tp_getattr */
4154 0, /* tp_setattr */
4155 0, /* tp_reserved */
4156 (reprfunc)dictview_repr, /* tp_repr */
4157 &dictviews_as_number, /* tp_as_number */
4158 &dictkeys_as_sequence, /* tp_as_sequence */
4159 0, /* tp_as_mapping */
4160 0, /* tp_hash */
4161 0, /* tp_call */
4162 0, /* tp_str */
4163 PyObject_GenericGetAttr, /* tp_getattro */
4164 0, /* tp_setattro */
4165 0, /* tp_as_buffer */
4166 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4167 0, /* tp_doc */
4168 (traverseproc)dictview_traverse, /* tp_traverse */
4169 0, /* tp_clear */
4170 dictview_richcompare, /* tp_richcompare */
4171 0, /* tp_weaklistoffset */
4172 (getiterfunc)dictkeys_iter, /* tp_iter */
4173 0, /* tp_iternext */
4174 dictkeys_methods, /* tp_methods */
4175 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004176};
4177
4178static PyObject *
4179dictkeys_new(PyObject *dict)
4180{
Eric Snow96c6af92015-05-29 22:21:39 -06004181 return _PyDictView_New(dict, &PyDictKeys_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004182}
4183
Guido van Rossum3ac67412007-02-10 18:55:06 +00004184/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004185
4186static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004187dictitems_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 if (dv->dv_dict == NULL) {
4190 Py_RETURN_NONE;
4191 }
4192 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00004193}
4194
4195static int
Eric Snow96c6af92015-05-29 22:21:39 -06004196dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00004197{
Serhiy Storchaka564398a2017-05-20 13:06:26 +03004198 int result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004199 PyObject *key, *value, *found;
4200 if (dv->dv_dict == NULL)
4201 return 0;
4202 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
4203 return 0;
4204 key = PyTuple_GET_ITEM(obj, 0);
4205 value = PyTuple_GET_ITEM(obj, 1);
Raymond Hettinger6692f012016-09-18 21:46:08 -07004206 found = PyDict_GetItemWithError((PyObject *)dv->dv_dict, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004207 if (found == NULL) {
4208 if (PyErr_Occurred())
4209 return -1;
4210 return 0;
4211 }
Serhiy Storchaka564398a2017-05-20 13:06:26 +03004212 Py_INCREF(found);
4213 result = PyObject_RichCompareBool(value, found, Py_EQ);
4214 Py_DECREF(found);
4215 return result;
Guido van Rossumb90c8482007-02-10 01:11:45 +00004216}
4217
Guido van Rossum83825ac2007-02-10 04:54:19 +00004218static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 (lenfunc)dictview_len, /* sq_length */
4220 0, /* sq_concat */
4221 0, /* sq_repeat */
4222 0, /* sq_item */
4223 0, /* sq_slice */
4224 0, /* sq_ass_item */
4225 0, /* sq_ass_slice */
4226 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004227};
4228
Guido van Rossumb90c8482007-02-10 01:11:45 +00004229static PyMethodDef dictitems_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004230 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4231 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004232 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004233};
4234
4235PyTypeObject PyDictItems_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4237 "dict_items", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004238 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 0, /* tp_itemsize */
4240 /* methods */
4241 (destructor)dictview_dealloc, /* tp_dealloc */
4242 0, /* tp_print */
4243 0, /* tp_getattr */
4244 0, /* tp_setattr */
4245 0, /* tp_reserved */
4246 (reprfunc)dictview_repr, /* tp_repr */
4247 &dictviews_as_number, /* tp_as_number */
4248 &dictitems_as_sequence, /* tp_as_sequence */
4249 0, /* tp_as_mapping */
4250 0, /* tp_hash */
4251 0, /* tp_call */
4252 0, /* tp_str */
4253 PyObject_GenericGetAttr, /* tp_getattro */
4254 0, /* tp_setattro */
4255 0, /* tp_as_buffer */
4256 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4257 0, /* tp_doc */
4258 (traverseproc)dictview_traverse, /* tp_traverse */
4259 0, /* tp_clear */
4260 dictview_richcompare, /* tp_richcompare */
4261 0, /* tp_weaklistoffset */
4262 (getiterfunc)dictitems_iter, /* tp_iter */
4263 0, /* tp_iternext */
4264 dictitems_methods, /* tp_methods */
4265 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004266};
4267
4268static PyObject *
4269dictitems_new(PyObject *dict)
4270{
Eric Snow96c6af92015-05-29 22:21:39 -06004271 return _PyDictView_New(dict, &PyDictItems_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004272}
4273
Guido van Rossum3ac67412007-02-10 18:55:06 +00004274/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004275
4276static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004277dictvalues_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004279 if (dv->dv_dict == NULL) {
4280 Py_RETURN_NONE;
4281 }
4282 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004283}
4284
Guido van Rossum83825ac2007-02-10 04:54:19 +00004285static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 (lenfunc)dictview_len, /* sq_length */
4287 0, /* sq_concat */
4288 0, /* sq_repeat */
4289 0, /* sq_item */
4290 0, /* sq_slice */
4291 0, /* sq_ass_item */
4292 0, /* sq_ass_slice */
4293 (objobjproc)0, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004294};
4295
Guido van Rossumb90c8482007-02-10 01:11:45 +00004296static PyMethodDef dictvalues_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004298};
4299
4300PyTypeObject PyDictValues_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004301 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4302 "dict_values", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004303 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004304 0, /* tp_itemsize */
4305 /* methods */
4306 (destructor)dictview_dealloc, /* tp_dealloc */
4307 0, /* tp_print */
4308 0, /* tp_getattr */
4309 0, /* tp_setattr */
4310 0, /* tp_reserved */
4311 (reprfunc)dictview_repr, /* tp_repr */
4312 0, /* tp_as_number */
4313 &dictvalues_as_sequence, /* tp_as_sequence */
4314 0, /* tp_as_mapping */
4315 0, /* tp_hash */
4316 0, /* tp_call */
4317 0, /* tp_str */
4318 PyObject_GenericGetAttr, /* tp_getattro */
4319 0, /* tp_setattro */
4320 0, /* tp_as_buffer */
4321 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4322 0, /* tp_doc */
4323 (traverseproc)dictview_traverse, /* tp_traverse */
4324 0, /* tp_clear */
4325 0, /* tp_richcompare */
4326 0, /* tp_weaklistoffset */
4327 (getiterfunc)dictvalues_iter, /* tp_iter */
4328 0, /* tp_iternext */
4329 dictvalues_methods, /* tp_methods */
4330 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004331};
4332
4333static PyObject *
4334dictvalues_new(PyObject *dict)
4335{
Eric Snow96c6af92015-05-29 22:21:39 -06004336 return _PyDictView_New(dict, &PyDictValues_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004337}
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004338
4339/* Returns NULL if cannot allocate a new PyDictKeysObject,
4340 but does not set an error */
4341PyDictKeysObject *
4342_PyDict_NewKeysForClass(void)
4343{
Victor Stinner742da042016-09-07 17:40:12 -07004344 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004345 if (keys == NULL)
4346 PyErr_Clear();
4347 else
4348 keys->dk_lookup = lookdict_split;
4349 return keys;
4350}
4351
4352#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
4353
4354PyObject *
4355PyObject_GenericGetDict(PyObject *obj, void *context)
4356{
4357 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
4358 if (dictptr == NULL) {
4359 PyErr_SetString(PyExc_AttributeError,
4360 "This object has no __dict__");
4361 return NULL;
4362 }
4363 dict = *dictptr;
4364 if (dict == NULL) {
4365 PyTypeObject *tp = Py_TYPE(obj);
4366 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
4367 DK_INCREF(CACHED_KEYS(tp));
4368 *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
4369 }
4370 else {
4371 *dictptr = dict = PyDict_New();
4372 }
4373 }
4374 Py_XINCREF(dict);
4375 return dict;
4376}
4377
4378int
4379_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
Victor Stinner742da042016-09-07 17:40:12 -07004380 PyObject *key, PyObject *value)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004381{
4382 PyObject *dict;
4383 int res;
4384 PyDictKeysObject *cached;
4385
4386 assert(dictptr != NULL);
4387 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
4388 assert(dictptr != NULL);
4389 dict = *dictptr;
4390 if (dict == NULL) {
4391 DK_INCREF(cached);
4392 dict = new_dict_with_shared_keys(cached);
4393 if (dict == NULL)
4394 return -1;
4395 *dictptr = dict;
4396 }
4397 if (value == NULL) {
4398 res = PyDict_DelItem(dict, key);
INADA Naoki89ddffb2017-02-13 09:19:05 +09004399 // Since key sharing dict doesn't allow deletion, PyDict_DelItem()
4400 // always converts dict to combined form.
4401 if ((cached = CACHED_KEYS(tp)) != NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004402 CACHED_KEYS(tp) = NULL;
4403 DK_DECREF(cached);
4404 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01004405 }
4406 else {
INADA Naoki89ddffb2017-02-13 09:19:05 +09004407 int was_shared = (cached == ((PyDictObject *)dict)->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004408 res = PyDict_SetItem(dict, key, value);
INADA Naoki89ddffb2017-02-13 09:19:05 +09004409 if (was_shared &&
4410 (cached = CACHED_KEYS(tp)) != NULL &&
4411 cached != ((PyDictObject *)dict)->ma_keys) {
Victor Stinner3d3f2642016-12-15 17:21:23 +01004412 /* PyDict_SetItem() may call dictresize and convert split table
4413 * into combined table. In such case, convert it to split
4414 * table again and update type's shared key only when this is
4415 * the only dict sharing key with the type.
4416 *
4417 * This is to allow using shared key in class like this:
4418 *
4419 * class C:
4420 * def __init__(self):
4421 * # one dict resize happens
4422 * self.a, self.b, self.c = 1, 2, 3
4423 * self.d, self.e, self.f = 4, 5, 6
4424 * a = C()
4425 */
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004426 if (cached->dk_refcnt == 1) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004427 CACHED_KEYS(tp) = make_keys_shared(dict);
Victor Stinner742da042016-09-07 17:40:12 -07004428 }
4429 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004430 CACHED_KEYS(tp) = NULL;
4431 }
4432 DK_DECREF(cached);
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004433 if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
4434 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004435 }
4436 }
4437 } else {
4438 dict = *dictptr;
4439 if (dict == NULL) {
4440 dict = PyDict_New();
4441 if (dict == NULL)
4442 return -1;
4443 *dictptr = dict;
4444 }
4445 if (value == NULL) {
4446 res = PyDict_DelItem(dict, key);
4447 } else {
4448 res = PyDict_SetItem(dict, key, value);
4449 }
4450 }
4451 return res;
4452}
4453
4454void
4455_PyDictKeys_DecRef(PyDictKeysObject *keys)
4456{
4457 DK_DECREF(keys);
4458}