blob: 00fd58c81d359c2f039bf3afa2e6c51f7484507b [file] [log] [blame]
Guido van Rossum2bc13791999-03-24 19:06:42 +00001/* Dictionary object implementation using a hash table */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002
Raymond Hettinger930427b2003-05-03 06:51:59 +00003/* The distribution includes a separate file, Objects/dictnotes.txt,
Tim Peters60b29962006-01-01 01:19:23 +00004 describing explorations into dictionary design and optimization.
Raymond Hettinger930427b2003-05-03 06:51:59 +00005 It covers typical dictionary use patterns, the parameters for
6 tuning dictionaries, and several ideas for possible optimizations.
7*/
8
Victor Stinner742da042016-09-07 17:40:12 -07009/* PyDictKeysObject
10
11This implements the dictionary's hashtable.
12
Raymond Hettingerb12785d2016-10-22 09:58:14 -070013As of Python 3.6, this is compact and ordered. Basic idea is described here:
14* https://mail.python.org/pipermail/python-dev/2012-December/123028.html
15* https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html
Victor Stinner742da042016-09-07 17:40:12 -070016
17layout:
18
19+---------------+
20| dk_refcnt |
21| dk_size |
22| dk_lookup |
23| dk_usable |
24| dk_nentries |
25+---------------+
26| dk_indices |
27| |
28+---------------+
29| dk_entries |
30| |
31+---------------+
32
33dk_indices is actual hashtable. It holds index in entries, or DKIX_EMPTY(-1)
34or DKIX_DUMMY(-2).
35Size of indices is dk_size. Type of each index in indices is vary on dk_size:
36
37* int8 for dk_size <= 128
38* int16 for 256 <= dk_size <= 2**15
39* int32 for 2**16 <= dk_size <= 2**31
40* int64 for 2**32 <= dk_size
41
42dk_entries is array of PyDictKeyEntry. It's size is USABLE_FRACTION(dk_size).
43DK_ENTRIES(dk) can be used to get pointer to entries.
44
45NOTE: Since negative value is used for DKIX_EMPTY and DKIX_DUMMY, type of
46dk_indices entry is signed integer and int16 is used for table which
47dk_size == 256.
48*/
49
Benjamin Peterson7d95e402012-04-23 11:24:50 -040050
51/*
Benjamin Peterson7d95e402012-04-23 11:24:50 -040052The DictObject can be in one of two forms.
Victor Stinner742da042016-09-07 17:40:12 -070053
Benjamin Peterson7d95e402012-04-23 11:24:50 -040054Either:
55 A combined table:
56 ma_values == NULL, dk_refcnt == 1.
57 Values are stored in the me_value field of the PyDictKeysObject.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040058Or:
59 A split table:
60 ma_values != NULL, dk_refcnt >= 1
61 Values are stored in the ma_values array.
Victor Stinner742da042016-09-07 17:40:12 -070062 Only string (unicode) keys are allowed.
63 All dicts sharing same key must have same insertion order.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040064
Victor Stinner742da042016-09-07 17:40:12 -070065There are four kinds of slots in the table (slot is index, and
66DK_ENTRIES(keys)[index] if index >= 0):
67
681. Unused. index == DKIX_EMPTY
69 Does not hold an active (key, value) pair now and never did. Unused can
70 transition to Active upon key insertion. This is each slot's initial state.
71
722. Active. index >= 0, me_key != NULL and me_value != NULL
73 Holds an active (key, value) pair. Active can transition to Dummy or
74 Pending upon key deletion (for combined and split tables respectively).
75 This is the only case in which me_value != NULL.
76
773. Dummy. index == DKIX_DUMMY (combined only)
78 Previously held an active (key, value) pair, but that was deleted and an
79 active pair has not yet overwritten the slot. Dummy can transition to
80 Active upon key insertion. Dummy slots cannot be made Unused again
81 else the probe sequence in case of collision would have no way to know
82 they were once active.
83
844. Pending. index >= 0, key != NULL, and value == NULL (split only)
85 Not yet inserted in split-table.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040086*/
87
Victor Stinner742da042016-09-07 17:40:12 -070088/*
89Preserving insertion order
Benjamin Peterson7d95e402012-04-23 11:24:50 -040090
Victor Stinner742da042016-09-07 17:40:12 -070091It's simple for combined table. Since dk_entries is mostly append only, we can
92get insertion order by just iterating dk_entries.
93
94One exception is .popitem(). It removes last item in dk_entries and decrement
95dk_nentries to achieve amortized O(1). Since there are DKIX_DUMMY remains in
96dk_indices, we can't increment dk_usable even though dk_nentries is
97decremented.
98
99In split table, inserting into pending entry is allowed only for dk_entries[ix]
100where ix == mp->ma_used. Inserting into other index and deleting item cause
101converting the dict to the combined table.
102*/
103
104/* PyDict_MINSIZE is the starting size for any new dict.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400105 * 8 allows dicts with no more than 5 active entries; experiments suggested
106 * this suffices for the majority of dicts (consisting mostly of usually-small
107 * dicts created to pass keyword arguments).
108 * Making this 8, rather than 4 reduces the number of resizes for most
109 * dictionaries, without any significant extra memory use.
110 */
Victor Stinner742da042016-09-07 17:40:12 -0700111#define PyDict_MINSIZE 8
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400112
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113#include "Python.h"
Eric Snow96c6af92015-05-29 22:21:39 -0600114#include "dict-common.h"
Victor Stinner990397e2016-09-09 20:22:59 -0700115#include "stringlib/eq.h" /* to get unicode_eq() */
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000116
Larry Hastings61272b72014-01-07 12:41:53 -0800117/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -0800118class dict "PyDictObject *" "&PyDict_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800119[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -0800120/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f157a5a0ce9589d6]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800121
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400122
123/*
124To ensure the lookup algorithm terminates, there must be at least one Unused
125slot (NULL key) in the table.
126To avoid slowing down lookups on a near-full table, we resize the table when
127it's USABLE_FRACTION (currently two-thirds) full.
128*/
Guido van Rossum16e93a81997-01-28 00:00:11 +0000129
Tim Peterseb28ef22001-06-02 05:27:19 +0000130#define PERTURB_SHIFT 5
131
Guido van Rossum16e93a81997-01-28 00:00:11 +0000132/*
Tim Peterseb28ef22001-06-02 05:27:19 +0000133Major subtleties ahead: Most hash schemes depend on having a "good" hash
134function, in the sense of simulating randomness. Python doesn't: its most
R David Murray537ad7a2016-07-10 12:33:18 -0400135important hash functions (for ints) are very regular in common
Tim Peterseb28ef22001-06-02 05:27:19 +0000136cases:
Tim Peters15d49292001-05-27 07:39:22 +0000137
R David Murray537ad7a2016-07-10 12:33:18 -0400138 >>>[hash(i) for i in range(4)]
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000139 [0, 1, 2, 3]
Tim Peters15d49292001-05-27 07:39:22 +0000140
Tim Peterseb28ef22001-06-02 05:27:19 +0000141This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
142the low-order i bits as the initial table index is extremely fast, and there
R David Murray537ad7a2016-07-10 12:33:18 -0400143are no collisions at all for dicts indexed by a contiguous range of ints. So
144this gives better-than-random behavior in common cases, and that's very
145desirable.
Tim Peters15d49292001-05-27 07:39:22 +0000146
Tim Peterseb28ef22001-06-02 05:27:19 +0000147OTOH, when collisions occur, the tendency to fill contiguous slices of the
148hash table makes a good collision resolution strategy crucial. Taking only
149the last i bits of the hash code is also vulnerable: for example, consider
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150the list [i << 16 for i in range(20000)] as a set of keys. Since ints are
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000151their own hash codes, and this fits in a dict of size 2**15, the last 15 bits
152 of every hash code are all 0: they *all* map to the same table index.
Tim Peters15d49292001-05-27 07:39:22 +0000153
Tim Peterseb28ef22001-06-02 05:27:19 +0000154But catering to unusual cases should not slow the usual ones, so we just take
155the last i bits anyway. It's up to collision resolution to do the rest. If
156we *usually* find the key we're looking for on the first try (and, it turns
157out, we usually do -- the table load factor is kept under 2/3, so the odds
158are solidly in our favor), then it makes best sense to keep the initial index
159computation dirt cheap.
Tim Peters15d49292001-05-27 07:39:22 +0000160
Tim Peterseb28ef22001-06-02 05:27:19 +0000161The first half of collision resolution is to visit table indices via this
162recurrence:
Tim Peters15d49292001-05-27 07:39:22 +0000163
Tim Peterseb28ef22001-06-02 05:27:19 +0000164 j = ((5*j) + 1) mod 2**i
Tim Peters15d49292001-05-27 07:39:22 +0000165
Tim Peterseb28ef22001-06-02 05:27:19 +0000166For any initial j in range(2**i), repeating that 2**i times generates each
167int in range(2**i) exactly once (see any text on random-number generation for
168proof). By itself, this doesn't help much: like linear probing (setting
169j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
170order. This would be bad, except that's not the only thing we do, and it's
171actually *good* in the common cases where hash keys are consecutive. In an
172example that's really too small to make this entirely clear, for a table of
173size 2**3 the order of indices is:
Tim Peters15d49292001-05-27 07:39:22 +0000174
Tim Peterseb28ef22001-06-02 05:27:19 +0000175 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
176
177If two things come in at index 5, the first place we look after is index 2,
178not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
179Linear probing is deadly in this case because there the fixed probe order
180is the *same* as the order consecutive keys are likely to arrive. But it's
181extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
182and certain that consecutive hash codes do not.
183
184The other half of the strategy is to get the other bits of the hash code
185into play. This is done by initializing a (unsigned) vrbl "perturb" to the
186full hash code, and changing the recurrence to:
187
Tim Peterseb28ef22001-06-02 05:27:19 +0000188 perturb >>= PERTURB_SHIFT;
INADA Naoki267941c2016-10-06 15:19:07 +0900189 j = (5*j) + 1 + perturb;
Tim Peterseb28ef22001-06-02 05:27:19 +0000190 use j % 2**i as the next table index;
191
192Now the probe sequence depends (eventually) on every bit in the hash code,
193and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
194because it quickly magnifies small differences in the bits that didn't affect
195the initial index. Note that because perturb is unsigned, if the recurrence
196is executed often enough perturb eventually becomes and remains 0. At that
197point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
198that's certain to find an empty slot eventually (since it generates every int
199in range(2**i), and we make sure there's always at least one empty slot).
200
201Selecting a good value for PERTURB_SHIFT is a balancing act. You want it
202small so that the high bits of the hash code continue to affect the probe
203sequence across iterations; but you want it large so that in really bad cases
204the high-order hash bits have an effect on early iterations. 5 was "the
205best" in minimizing total collisions across experiments Tim Peters ran (on
206both normal and pathological cases), but 4 and 6 weren't significantly worse.
207
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000208Historical: Reimer Behrends contributed the idea of using a polynomial-based
Tim Peterseb28ef22001-06-02 05:27:19 +0000209approach, using repeated multiplication by x in GF(2**n) where an irreducible
210polynomial for each table size was chosen such that x was a primitive root.
211Christian Tismer later extended that to use division by x instead, as an
212efficient way to get the high bits of the hash code into play. This scheme
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000213also gave excellent collision statistics, but was more expensive: two
214if-tests were required inside the loop; computing "the next" index took about
215the same number of operations but without as much potential parallelism
216(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
217above, and then shifting perturb can be done while the table index is being
218masked); and the PyDictObject struct required a member to hold the table's
219polynomial. In Tim's experiments the current scheme ran faster, produced
220equally good collision statistics, needed less code & used less memory.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000221
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000222*/
Tim Petersdea48ec2001-05-22 20:40:22 +0000223
Fred Drake1bff34a2000-08-31 19:31:38 +0000224/* forward declarations */
Victor Stinner742da042016-09-07 17:40:12 -0700225static Py_ssize_t lookdict(PyDictObject *mp, PyObject *key,
INADA Naokiba609772016-12-07 20:41:42 +0900226 Py_hash_t hash, PyObject **value_addr,
Victor Stinner742da042016-09-07 17:40:12 -0700227 Py_ssize_t *hashpos);
228static Py_ssize_t lookdict_unicode(PyDictObject *mp, PyObject *key,
INADA Naokiba609772016-12-07 20:41:42 +0900229 Py_hash_t hash, PyObject **value_addr,
Victor Stinner742da042016-09-07 17:40:12 -0700230 Py_ssize_t *hashpos);
231static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400232lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
INADA Naokiba609772016-12-07 20:41:42 +0900233 Py_hash_t hash, PyObject **value_addr,
Victor Stinner742da042016-09-07 17:40:12 -0700234 Py_ssize_t *hashpos);
235static Py_ssize_t lookdict_split(PyDictObject *mp, PyObject *key,
INADA Naokiba609772016-12-07 20:41:42 +0900236 Py_hash_t hash, PyObject **value_addr,
Victor Stinner742da042016-09-07 17:40:12 -0700237 Py_ssize_t *hashpos);
Fred Drake1bff34a2000-08-31 19:31:38 +0000238
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400239static int dictresize(PyDictObject *mp, Py_ssize_t minused);
Tim Petersdea48ec2001-05-22 20:40:22 +0000240
Benjamin Peterson3c569292016-09-08 13:16:41 -0700241/*Global counter used to set ma_version_tag field of dictionary.
Victor Stinner3b6a6b42016-09-08 12:51:24 -0700242 * It is incremented each time that a dictionary is created and each
243 * time that a dictionary is modified. */
244static uint64_t pydict_global_version = 0;
245
246#define DICT_NEXT_VERSION() (++pydict_global_version)
247
Victor Stinner742da042016-09-07 17:40:12 -0700248/* Dictionary reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +0000249#ifndef PyDict_MAXFREELIST
250#define PyDict_MAXFREELIST 80
251#endif
252static PyDictObject *free_list[PyDict_MAXFREELIST];
253static int numfree = 0;
Victor Stinner742da042016-09-07 17:40:12 -0700254static PyDictKeysObject *keys_free_list[PyDict_MAXFREELIST];
255static int numfreekeys = 0;
Raymond Hettinger43442782004-03-17 21:55:03 +0000256
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300257#include "clinic/dictobject.c.h"
258
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100259int
260PyDict_ClearFreeList(void)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 PyDictObject *op;
Victor Stinner742da042016-09-07 17:40:12 -0700263 int ret = numfree + numfreekeys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 while (numfree) {
265 op = free_list[--numfree];
266 assert(PyDict_CheckExact(op));
267 PyObject_GC_Del(op);
268 }
Victor Stinner742da042016-09-07 17:40:12 -0700269 while (numfreekeys) {
270 PyObject_FREE(keys_free_list[--numfreekeys]);
271 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100272 return ret;
273}
274
David Malcolm49526f42012-06-22 14:55:41 -0400275/* Print summary info about the state of the optimized allocator */
276void
277_PyDict_DebugMallocStats(FILE *out)
278{
279 _PyDebugAllocatorStats(out,
280 "free PyDictObject", numfree, sizeof(PyDictObject));
281}
282
283
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100284void
285PyDict_Fini(void)
286{
287 PyDict_ClearFreeList();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000288}
289
Victor Stinner742da042016-09-07 17:40:12 -0700290#define DK_SIZE(dk) ((dk)->dk_size)
291#if SIZEOF_VOID_P > 4
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700292#define DK_IXSIZE(dk) \
293 (DK_SIZE(dk) <= 0xff ? \
294 1 : DK_SIZE(dk) <= 0xffff ? \
295 2 : DK_SIZE(dk) <= 0xffffffff ? \
Benjamin Peterson3c569292016-09-08 13:16:41 -0700296 4 : sizeof(int64_t))
Victor Stinner742da042016-09-07 17:40:12 -0700297#else
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700298#define DK_IXSIZE(dk) \
299 (DK_SIZE(dk) <= 0xff ? \
300 1 : DK_SIZE(dk) <= 0xffff ? \
Benjamin Peterson3c569292016-09-08 13:16:41 -0700301 2 : sizeof(int32_t))
Victor Stinner742da042016-09-07 17:40:12 -0700302#endif
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700303#define DK_ENTRIES(dk) \
Benjamin Peterson186122e2016-09-08 12:20:12 -0700304 ((PyDictKeyEntry*)(&(dk)->dk_indices.as_1[DK_SIZE(dk) * DK_IXSIZE(dk)]))
Victor Stinner742da042016-09-07 17:40:12 -0700305
Antoine Pitrou2d169b22012-05-12 23:43:44 +0200306#define DK_DEBUG_INCREF _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA
307#define DK_DEBUG_DECREF _Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA
308
309#define DK_INCREF(dk) (DK_DEBUG_INCREF ++(dk)->dk_refcnt)
310#define DK_DECREF(dk) if (DK_DEBUG_DECREF (--(dk)->dk_refcnt) == 0) free_keys_object(dk)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400311#define DK_MASK(dk) (((dk)->dk_size)-1)
312#define IS_POWER_OF_2(x) (((x) & (x-1)) == 0)
313
Victor Stinner742da042016-09-07 17:40:12 -0700314/* lookup indices. returns DKIX_EMPTY, DKIX_DUMMY, or ix >=0 */
Benjamin Peterson73222252016-09-08 09:58:47 -0700315static inline Py_ssize_t
Victor Stinner742da042016-09-07 17:40:12 -0700316dk_get_index(PyDictKeysObject *keys, Py_ssize_t i)
317{
318 Py_ssize_t s = DK_SIZE(keys);
Victor Stinner71211e32016-09-08 10:52:46 -0700319 Py_ssize_t ix;
320
Victor Stinner742da042016-09-07 17:40:12 -0700321 if (s <= 0xff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700322 int8_t *indices = keys->dk_indices.as_1;
Victor Stinner208857e2016-09-08 11:35:46 -0700323 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700324 }
325 else if (s <= 0xffff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700326 int16_t *indices = keys->dk_indices.as_2;
Victor Stinner208857e2016-09-08 11:35:46 -0700327 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700328 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700329#if SIZEOF_VOID_P > 4
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300330 else if (s > 0xffffffff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700331 int64_t *indices = keys->dk_indices.as_8;
Victor Stinner208857e2016-09-08 11:35:46 -0700332 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700333 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700334#endif
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300335 else {
336 int32_t *indices = keys->dk_indices.as_4;
337 ix = indices[i];
338 }
Victor Stinner71211e32016-09-08 10:52:46 -0700339 assert(ix >= DKIX_DUMMY);
340 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700341}
342
343/* write to indices. */
Benjamin Peterson73222252016-09-08 09:58:47 -0700344static inline void
Victor Stinner742da042016-09-07 17:40:12 -0700345dk_set_index(PyDictKeysObject *keys, Py_ssize_t i, Py_ssize_t ix)
346{
347 Py_ssize_t s = DK_SIZE(keys);
Victor Stinner71211e32016-09-08 10:52:46 -0700348
349 assert(ix >= DKIX_DUMMY);
350
Victor Stinner742da042016-09-07 17:40:12 -0700351 if (s <= 0xff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700352 int8_t *indices = keys->dk_indices.as_1;
Victor Stinner71211e32016-09-08 10:52:46 -0700353 assert(ix <= 0x7f);
Victor Stinner208857e2016-09-08 11:35:46 -0700354 indices[i] = (char)ix;
Victor Stinner742da042016-09-07 17:40:12 -0700355 }
356 else if (s <= 0xffff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700357 int16_t *indices = keys->dk_indices.as_2;
Victor Stinner71211e32016-09-08 10:52:46 -0700358 assert(ix <= 0x7fff);
Victor Stinner208857e2016-09-08 11:35:46 -0700359 indices[i] = (int16_t)ix;
Victor Stinner742da042016-09-07 17:40:12 -0700360 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700361#if SIZEOF_VOID_P > 4
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300362 else if (s > 0xffffffff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700363 int64_t *indices = keys->dk_indices.as_8;
Victor Stinner208857e2016-09-08 11:35:46 -0700364 indices[i] = ix;
Victor Stinner742da042016-09-07 17:40:12 -0700365 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700366#endif
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300367 else {
368 int32_t *indices = keys->dk_indices.as_4;
369 assert(ix <= 0x7fffffff);
370 indices[i] = (int32_t)ix;
371 }
Victor Stinner742da042016-09-07 17:40:12 -0700372}
373
374
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200375/* USABLE_FRACTION is the maximum dictionary load.
Victor Stinner742da042016-09-07 17:40:12 -0700376 * Increasing this ratio makes dictionaries more dense resulting in more
377 * collisions. Decreasing it improves sparseness at the expense of spreading
378 * indices over more cache lines and at the cost of total memory consumed.
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200379 *
380 * USABLE_FRACTION must obey the following:
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400381 * (0 < USABLE_FRACTION(n) < n) for all n >= 2
382 *
Victor Stinner742da042016-09-07 17:40:12 -0700383 * USABLE_FRACTION should be quick to calculate.
384 * Fractions around 1/2 to 2/3 seem to work well in practice.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400385 */
Victor Stinner742da042016-09-07 17:40:12 -0700386#define USABLE_FRACTION(n) (((n) << 1)/3)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400387
Victor Stinner742da042016-09-07 17:40:12 -0700388/* ESTIMATE_SIZE is reverse function of USABLE_FRACTION.
389 * This can be used to reserve enough size to insert n entries without
390 * resizing.
391 */
INADA Naoki92c50ee2016-11-22 00:57:02 +0900392#define ESTIMATE_SIZE(n) (((n)*3+1) >> 1)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400393
Victor Stinner742da042016-09-07 17:40:12 -0700394/* Alternative fraction that is otherwise close enough to 2n/3 to make
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400395 * little difference. 8 * 2/3 == 8 * 5/8 == 5. 16 * 2/3 == 16 * 5/8 == 10.
396 * 32 * 2/3 = 21, 32 * 5/8 = 20.
397 * Its advantage is that it is faster to compute on machines with slow division.
398 * #define USABLE_FRACTION(n) (((n) >> 1) + ((n) >> 2) - ((n) >> 3))
Victor Stinner742da042016-09-07 17:40:12 -0700399 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400400
Victor Stinnera9f61a52013-07-16 22:17:26 +0200401/* GROWTH_RATE. Growth rate upon hitting maximum load.
402 * Currently set to used*2 + capacity/2.
403 * This means that dicts double in size when growing without deletions,
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700404 * but have more head room when the number of deletions is on a par with the
405 * number of insertions.
406 * Raising this to used*4 doubles memory consumption depending on the size of
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200407 * the dictionary, but results in half the number of resizes, less effort to
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700408 * resize.
409 * GROWTH_RATE was set to used*4 up to version 3.2.
410 * GROWTH_RATE was set to used*2 in version 3.3.0
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200411 */
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700412#define GROWTH_RATE(d) (((d)->ma_used*2)+((d)->ma_keys->dk_size>>1))
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400413
414#define ENSURE_ALLOWS_DELETIONS(d) \
415 if ((d)->ma_keys->dk_lookup == lookdict_unicode_nodummy) { \
416 (d)->ma_keys->dk_lookup = lookdict_unicode; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400418
419/* This immutable, empty PyDictKeysObject is used for PyDict_Clear()
420 * (which cannot fail and thus can do no allocation).
421 */
422static PyDictKeysObject empty_keys_struct = {
Serhiy Storchaka97932e42016-09-26 23:01:23 +0300423 1, /* dk_refcnt */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400424 1, /* dk_size */
425 lookdict_split, /* dk_lookup */
426 0, /* dk_usable (immutable) */
Victor Stinner742da042016-09-07 17:40:12 -0700427 0, /* dk_nentries */
Benjamin Peterson186122e2016-09-08 12:20:12 -0700428 .dk_indices = { .as_1 = {DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY,
429 DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY}},
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400430};
431
432static PyObject *empty_values[1] = { NULL };
433
434#define Py_EMPTY_KEYS &empty_keys_struct
435
Victor Stinner611b0fa2016-09-14 15:02:01 +0200436/* Uncomment to check the dict content in _PyDict_CheckConsistency() */
437/* #define DEBUG_PYDICT */
438
439
440#ifdef Py_DEBUG
441static int
442_PyDict_CheckConsistency(PyDictObject *mp)
443{
444 PyDictKeysObject *keys = mp->ma_keys;
445 int splitted = _PyDict_HasSplitTable(mp);
446 Py_ssize_t usable = USABLE_FRACTION(keys->dk_size);
447#ifdef DEBUG_PYDICT
448 PyDictKeyEntry *entries = DK_ENTRIES(keys);
449 Py_ssize_t i;
450#endif
451
452 assert(0 <= mp->ma_used && mp->ma_used <= usable);
453 assert(IS_POWER_OF_2(keys->dk_size));
454 assert(0 <= keys->dk_usable
455 && keys->dk_usable <= usable);
456 assert(0 <= keys->dk_nentries
457 && keys->dk_nentries <= usable);
458 assert(keys->dk_usable + keys->dk_nentries <= usable);
459
460 if (!splitted) {
461 /* combined table */
462 assert(keys->dk_refcnt == 1);
463 }
464
465#ifdef DEBUG_PYDICT
466 for (i=0; i < keys->dk_size; i++) {
467 Py_ssize_t ix = dk_get_index(keys, i);
468 assert(DKIX_DUMMY <= ix && ix <= usable);
469 }
470
471 for (i=0; i < usable; i++) {
472 PyDictKeyEntry *entry = &entries[i];
473 PyObject *key = entry->me_key;
474
475 if (key != NULL) {
476 if (PyUnicode_CheckExact(key)) {
477 Py_hash_t hash = ((PyASCIIObject *)key)->hash;
478 assert(hash != -1);
479 assert(entry->me_hash == hash);
480 }
481 else {
482 /* test_dict fails if PyObject_Hash() is called again */
483 assert(entry->me_hash != -1);
484 }
485 if (!splitted) {
486 assert(entry->me_value != NULL);
487 }
488 }
489
490 if (splitted) {
491 assert(entry->me_value == NULL);
492 }
493 }
494
495 if (splitted) {
496 /* splitted table */
497 for (i=0; i < mp->ma_used; i++) {
498 assert(mp->ma_values[i] != NULL);
499 }
500 }
501#endif
502
503 return 1;
504}
505#endif
506
507
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400508static PyDictKeysObject *new_keys_object(Py_ssize_t size)
509{
510 PyDictKeysObject *dk;
Victor Stinner742da042016-09-07 17:40:12 -0700511 Py_ssize_t es, usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400512
Victor Stinner742da042016-09-07 17:40:12 -0700513 assert(size >= PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400514 assert(IS_POWER_OF_2(size));
Victor Stinner742da042016-09-07 17:40:12 -0700515
516 usable = USABLE_FRACTION(size);
517 if (size <= 0xff) {
518 es = 1;
519 }
520 else if (size <= 0xffff) {
521 es = 2;
522 }
523#if SIZEOF_VOID_P > 4
524 else if (size <= 0xffffffff) {
525 es = 4;
526 }
527#endif
528 else {
529 es = sizeof(Py_ssize_t);
530 }
531
532 if (size == PyDict_MINSIZE && numfreekeys > 0) {
533 dk = keys_free_list[--numfreekeys];
534 }
535 else {
Victor Stinner98ee9d52016-09-08 09:33:56 -0700536 dk = PyObject_MALLOC(sizeof(PyDictKeysObject)
537 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
538 + es * size
539 + sizeof(PyDictKeyEntry) * usable);
Victor Stinner742da042016-09-07 17:40:12 -0700540 if (dk == NULL) {
541 PyErr_NoMemory();
542 return NULL;
543 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400544 }
Antoine Pitrou2d169b22012-05-12 23:43:44 +0200545 DK_DEBUG_INCREF dk->dk_refcnt = 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400546 dk->dk_size = size;
Victor Stinner742da042016-09-07 17:40:12 -0700547 dk->dk_usable = usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400548 dk->dk_lookup = lookdict_unicode_nodummy;
Victor Stinner742da042016-09-07 17:40:12 -0700549 dk->dk_nentries = 0;
Benjamin Peterson186122e2016-09-08 12:20:12 -0700550 memset(&dk->dk_indices.as_1[0], 0xff, es * size);
Victor Stinner742da042016-09-07 17:40:12 -0700551 memset(DK_ENTRIES(dk), 0, sizeof(PyDictKeyEntry) * usable);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400552 return dk;
553}
554
555static void
556free_keys_object(PyDictKeysObject *keys)
557{
Victor Stinner742da042016-09-07 17:40:12 -0700558 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400559 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -0700560 for (i = 0, n = keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400561 Py_XDECREF(entries[i].me_key);
562 Py_XDECREF(entries[i].me_value);
563 }
Victor Stinner742da042016-09-07 17:40:12 -0700564 if (keys->dk_size == PyDict_MINSIZE && numfreekeys < PyDict_MAXFREELIST) {
565 keys_free_list[numfreekeys++] = keys;
566 return;
567 }
Raymond Hettingerce5179f2016-01-31 08:56:21 -0800568 PyObject_FREE(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400569}
570
571#define new_values(size) PyMem_NEW(PyObject *, size)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400572#define free_values(values) PyMem_FREE(values)
573
574/* Consumes a reference to the keys object */
575static PyObject *
576new_dict(PyDictKeysObject *keys, PyObject **values)
577{
578 PyDictObject *mp;
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200579 assert(keys != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 if (numfree) {
581 mp = free_list[--numfree];
582 assert (mp != NULL);
583 assert (Py_TYPE(mp) == &PyDict_Type);
584 _Py_NewReference((PyObject *)mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400586 else {
587 mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
588 if (mp == NULL) {
589 DK_DECREF(keys);
590 free_values(values);
591 return NULL;
592 }
593 }
594 mp->ma_keys = keys;
595 mp->ma_values = values;
596 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -0700597 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner611b0fa2016-09-14 15:02:01 +0200598 assert(_PyDict_CheckConsistency(mp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000600}
601
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400602/* Consumes a reference to the keys object */
603static PyObject *
604new_dict_with_shared_keys(PyDictKeysObject *keys)
605{
606 PyObject **values;
607 Py_ssize_t i, size;
608
Victor Stinner742da042016-09-07 17:40:12 -0700609 size = USABLE_FRACTION(DK_SIZE(keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400610 values = new_values(size);
611 if (values == NULL) {
612 DK_DECREF(keys);
613 return PyErr_NoMemory();
614 }
615 for (i = 0; i < size; i++) {
616 values[i] = NULL;
617 }
618 return new_dict(keys, values);
619}
620
621PyObject *
622PyDict_New(void)
623{
Victor Stinner742da042016-09-07 17:40:12 -0700624 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200625 if (keys == NULL)
626 return NULL;
627 return new_dict(keys, NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400628}
629
Victor Stinner742da042016-09-07 17:40:12 -0700630/* Search index of hash table from offset of entry table */
631static Py_ssize_t
632lookdict_index(PyDictKeysObject *k, Py_hash_t hash, Py_ssize_t index)
633{
INADA Naoki267941c2016-10-06 15:19:07 +0900634 size_t i;
Victor Stinner742da042016-09-07 17:40:12 -0700635 size_t mask = DK_MASK(k);
636 Py_ssize_t ix;
637
638 i = (size_t)hash & mask;
639 ix = dk_get_index(k, i);
640 if (ix == index) {
641 return i;
642 }
643 if (ix == DKIX_EMPTY) {
644 return DKIX_EMPTY;
645 }
646
INADA Naoki267941c2016-10-06 15:19:07 +0900647 for (size_t perturb = hash;;) {
648 perturb >>= PERTURB_SHIFT;
Victor Stinner742da042016-09-07 17:40:12 -0700649 i = mask & ((i << 2) + i + perturb + 1);
650 ix = dk_get_index(k, i);
651 if (ix == index) {
652 return i;
653 }
654 if (ix == DKIX_EMPTY) {
655 return DKIX_EMPTY;
656 }
657 }
658 assert(0); /* NOT REACHED */
659 return DKIX_ERROR;
660}
661
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000662/*
663The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000664This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000665Open addressing is preferred over chaining since the link overhead for
666chaining would be substantial (100% with typical malloc overhead).
667
Tim Peterseb28ef22001-06-02 05:27:19 +0000668The initial probe index is computed as hash mod the table size. Subsequent
669probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000670
671All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000672
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000673The details in this version are due to Tim Peters, building on many past
Tim Peterseb28ef22001-06-02 05:27:19 +0000674contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000675Christian Tismer.
Fred Drake1bff34a2000-08-31 19:31:38 +0000676
Victor Stinner742da042016-09-07 17:40:12 -0700677lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a
Victor Stinnera4348cc2016-09-08 12:01:25 -0700678comparison raises an exception.
Guido van Rossum89d8c602007-09-18 17:26:56 +0000679lookdict_unicode() below is specialized to string keys, comparison of which can
Victor Stinner742da042016-09-07 17:40:12 -0700680never raise an exception; that function can never return DKIX_ERROR.
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 Stinnerc7a8f672016-11-15 15:13:40 +0100686static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400687lookdict(PyDictObject *mp, PyObject *key,
INADA Naokiba609772016-12-07 20:41:42 +0900688 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) {
INADA Naokiba609772016-12-07 20:41:42 +0900717 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700718 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) {
INADA Naokiba609772016-12-07 20:41:42 +0900733 *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 }
INADA Naokiba609772016-12-07 20:41:42 +0900769 *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 }
INADA Naokiba609772016-12-07 20:41:42 +0900786 *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 Stinnerc7a8f672016-11-15 15:13:40 +0100801static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400802lookdict_unicode(PyDictObject *mp, PyObject *key,
INADA Naokiba609772016-12-07 20:41:42 +0900803 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;
INADA Naokiba609772016-12-07 20:41:42 +0900837 *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))) {
INADA Naokiba609772016-12-07 20:41:42 +0900863 *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 Stinnerc7a8f672016-11-15 15:13:40 +0100876static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400877lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
INADA Naokiba609772016-12-07 20:41:42 +0900878 Py_hash_t hash, PyObject **value_addr,
Victor Stinner742da042016-09-07 17:40:12 -0700879 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;
INADA Naokiba609772016-12-07 20:41:42 +0900911 *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;
INADA Naokiba609772016-12-07 20:41:42 +0900931 *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 Stinnerc7a8f672016-11-15 15:13:40 +0100944static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400945lookdict_split(PyDictObject *mp, PyObject *key,
INADA Naokiba609772016-12-07 20:41:42 +0900946 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) {
INADA Naokiba609772016-12-07 20:41:42 +0900958 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700959 }
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;
INADA Naokiba609772016-12-07 20:41:42 +0900978 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700979 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;
INADA Naokiba609772016-12-07 20:41:42 +0900998 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700999 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. */
INADA Naokiba609772016-12-07 20:41:42 +09001071static Py_ssize_t
1072find_empty_slot(PyDictKeysObject *keys, PyObject *key, Py_hash_t hash)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001073{
INADA Naoki267941c2016-10-06 15:19:07 +09001074 size_t i;
INADA Naokiba609772016-12-07 20:41:42 +09001075 size_t mask = DK_MASK(keys);
Victor Stinner742da042016-09-07 17:40:12 -07001076 Py_ssize_t ix;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001077
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001078 assert(key != NULL);
Victor Stinner3c336c52016-09-12 14:17:40 +02001079
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001080 i = hash & mask;
INADA Naokiba609772016-12-07 20:41:42 +09001081 ix = dk_get_index(keys, i);
INADA Naoki267941c2016-10-06 15:19:07 +09001082 for (size_t perturb = hash; ix != DKIX_EMPTY;) {
1083 perturb >>= PERTURB_SHIFT;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001084 i = (i << 2) + i + perturb + 1;
INADA Naokiba609772016-12-07 20:41:42 +09001085 ix = dk_get_index(keys, i & mask);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 }
INADA Naokiba609772016-12-07 20:41:42 +09001087 assert(DK_ENTRIES(keys)[keys->dk_nentries].me_value == NULL);
1088 return i & mask;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001089}
1090
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001091static int
1092insertion_resize(PyDictObject *mp)
1093{
Raymond Hettinger36f74aa2013-05-17 03:01:13 -07001094 return dictresize(mp, GROWTH_RATE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001095}
Antoine Pitroue965d972012-02-27 00:45:12 +01001096
1097/*
1098Internal routine to insert a new item into the table.
1099Used both by the internal resize routine and by the public insert routine.
Antoine Pitroue965d972012-02-27 00:45:12 +01001100Returns -1 if an error occurred, or 0 on success.
1101*/
1102static int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001103insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001104{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001105 PyObject *old_value;
INADA Naokiba609772016-12-07 20:41:42 +09001106 PyDictKeyEntry *ep;
Victor Stinner742da042016-09-07 17:40:12 -07001107 Py_ssize_t hashpos, ix;
Antoine Pitroue965d972012-02-27 00:45:12 +01001108
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001109 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
1110 if (insertion_resize(mp) < 0)
1111 return -1;
1112 }
1113
INADA Naokiba609772016-12-07 20:41:42 +09001114 ix = mp->ma_keys->dk_lookup(mp, key, hash, &old_value, &hashpos);
Victor Stinner742da042016-09-07 17:40:12 -07001115 if (ix == DKIX_ERROR) {
Antoine Pitroue965d972012-02-27 00:45:12 +01001116 return -1;
1117 }
Victor Stinner742da042016-09-07 17:40:12 -07001118
Antoine Pitroud6967322014-10-18 00:35:00 +02001119 assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
Benjamin Petersona6f195e2012-04-30 10:23:40 -04001120 Py_INCREF(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001121 MAINTAIN_TRACKING(mp, key, value);
Victor Stinner742da042016-09-07 17:40:12 -07001122
1123 /* When insertion order is different from shared key, we can't share
1124 * the key anymore. Convert this instance to combine table.
1125 */
1126 if (_PyDict_HasSplitTable(mp) &&
INADA Naokiba609772016-12-07 20:41:42 +09001127 ((ix >= 0 && old_value == NULL && mp->ma_used != ix) ||
Victor Stinner742da042016-09-07 17:40:12 -07001128 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
1129 if (insertion_resize(mp) < 0) {
1130 Py_DECREF(value);
1131 return -1;
1132 }
INADA Naokiba609772016-12-07 20:41:42 +09001133 hashpos = find_empty_slot(mp->ma_keys, key, hash);
Victor Stinner742da042016-09-07 17:40:12 -07001134 ix = DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001135 }
Victor Stinner742da042016-09-07 17:40:12 -07001136
1137 if (ix == DKIX_EMPTY) {
1138 /* Insert into new slot. */
INADA Naokiba609772016-12-07 20:41:42 +09001139 assert(old_value == NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001140 if (mp->ma_keys->dk_usable <= 0) {
1141 /* Need to resize. */
1142 if (insertion_resize(mp) < 0) {
1143 Py_DECREF(value);
1144 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001145 }
INADA Naokiba609772016-12-07 20:41:42 +09001146 hashpos = find_empty_slot(mp->ma_keys, key, hash);
Victor Stinner742da042016-09-07 17:40:12 -07001147 }
INADA Naokiba609772016-12-07 20:41:42 +09001148 ep = &DK_ENTRIES(mp->ma_keys)[mp->ma_keys->dk_nentries];
Victor Stinner742da042016-09-07 17:40:12 -07001149 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
1150 Py_INCREF(key);
1151 ep->me_key = key;
1152 ep->me_hash = hash;
1153 if (mp->ma_values) {
1154 assert (mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
1155 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001156 }
1157 else {
Victor Stinner742da042016-09-07 17:40:12 -07001158 ep->me_value = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001159 }
1160 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001161 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07001162 mp->ma_keys->dk_usable--;
1163 mp->ma_keys->dk_nentries++;
1164 assert(mp->ma_keys->dk_usable >= 0);
Victor Stinner611b0fa2016-09-14 15:02:01 +02001165 assert(_PyDict_CheckConsistency(mp));
Victor Stinner742da042016-09-07 17:40:12 -07001166 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001167 }
Victor Stinner742da042016-09-07 17:40:12 -07001168
INADA Naokiba609772016-12-07 20:41:42 +09001169 if (_PyDict_HasSplitTable(mp)) {
1170 mp->ma_values[ix] = value;
1171 if (old_value == NULL) {
1172 /* pending state */
1173 assert(ix == mp->ma_used);
1174 mp->ma_used++;
1175 }
1176 }
1177 else {
1178 assert(old_value != NULL);
1179 DK_ENTRIES(mp->ma_keys)[ix].me_value = value;
Victor Stinner742da042016-09-07 17:40:12 -07001180 }
1181
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001182 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naokiba609772016-12-07 20:41:42 +09001183 Py_XDECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
Victor Stinner611b0fa2016-09-14 15:02:01 +02001184 assert(_PyDict_CheckConsistency(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001185 return 0;
Antoine Pitroue965d972012-02-27 00:45:12 +01001186}
1187
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001188/*
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001189Internal routine used by dictresize() to buid a hashtable of entries.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001190*/
1191static void
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001192build_indices(PyDictKeysObject *keys, PyDictKeyEntry *ep, Py_ssize_t n)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001193{
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001194 size_t mask = (size_t)DK_SIZE(keys) - 1;
1195 for (Py_ssize_t ix = 0; ix != n; ix++, ep++) {
1196 Py_hash_t hash = ep->me_hash;
1197 size_t i = hash & mask;
1198 for (size_t perturb = hash; dk_get_index(keys, i) != DKIX_EMPTY;) {
1199 perturb >>= PERTURB_SHIFT;
1200 i = mask & ((i << 2) + i + perturb + 1);
1201 }
1202 dk_set_index(keys, i, ix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001204}
1205
1206/*
1207Restructure the table by allocating a new table and reinserting all
1208items again. When entries have been deleted, the new table may
1209actually be smaller than the old one.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001210If a table is split (its keys and hashes are shared, its values are not),
1211then the values are temporarily copied into the table, it is resized as
1212a combined table, then the me_value slots in the old table are NULLed out.
1213After resizing a table is always combined,
1214but can be resplit by make_keys_shared().
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001215*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001216static int
Victor Stinner3d3f2642016-12-15 17:21:23 +01001217dictresize(PyDictObject *mp, Py_ssize_t minsize)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001218{
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001219 Py_ssize_t newsize, numentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001220 PyDictKeysObject *oldkeys;
1221 PyObject **oldvalues;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001222 PyDictKeyEntry *oldentries, *newentries;
Tim Peters91a364d2001-05-19 07:04:38 +00001223
Victor Stinner742da042016-09-07 17:40:12 -07001224 /* Find the smallest table size > minused. */
1225 for (newsize = PyDict_MINSIZE;
Victor Stinner3d3f2642016-12-15 17:21:23 +01001226 newsize < minsize && newsize > 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 newsize <<= 1)
1228 ;
1229 if (newsize <= 0) {
1230 PyErr_NoMemory();
1231 return -1;
1232 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001233
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001234 oldkeys = mp->ma_keys;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001235
1236 /* NOTE: Current odict checks mp->ma_keys to detect resize happen.
1237 * So we can't reuse oldkeys even if oldkeys->dk_size == newsize.
1238 * TODO: Try reusing oldkeys when reimplement odict.
1239 */
1240
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001241 /* Allocate a new table. */
1242 mp->ma_keys = new_keys_object(newsize);
1243 if (mp->ma_keys == NULL) {
1244 mp->ma_keys = oldkeys;
1245 return -1;
1246 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01001247 // New table must be large enough.
1248 assert(mp->ma_keys->dk_usable >= mp->ma_used);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001249 if (oldkeys->dk_lookup == lookdict)
1250 mp->ma_keys->dk_lookup = lookdict;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001251
1252 numentries = mp->ma_used;
1253 oldentries = DK_ENTRIES(oldkeys);
1254 newentries = DK_ENTRIES(mp->ma_keys);
1255 oldvalues = mp->ma_values;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001256 if (oldvalues != NULL) {
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001257 /* Convert split table into new combined table.
1258 * We must incref keys; we can transfer values.
1259 * Note that values of split table is always dense.
1260 */
1261 for (Py_ssize_t i = 0; i < numentries; i++) {
1262 assert(oldvalues[i] != NULL);
1263 PyDictKeyEntry *ep = &oldentries[i];
1264 PyObject *key = ep->me_key;
1265 Py_INCREF(key);
1266 newentries[i].me_key = key;
1267 newentries[i].me_hash = ep->me_hash;
1268 newentries[i].me_value = oldvalues[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001270
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001271 DK_DECREF(oldkeys);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001272 mp->ma_values = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001273 if (oldvalues != empty_values) {
1274 free_values(oldvalues);
1275 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001276 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001277 else { // combined table.
1278 if (oldkeys->dk_nentries == numentries) {
1279 memcpy(newentries, oldentries, numentries * sizeof(PyDictKeyEntry));
1280 }
1281 else {
1282 PyDictKeyEntry *ep = oldentries;
1283 for (Py_ssize_t i = 0; i < numentries; i++) {
1284 while (ep->me_value == NULL)
1285 ep++;
1286 newentries[i] = *ep++;
1287 }
1288 }
1289
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001290 assert(oldkeys->dk_lookup != lookdict_split);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001291 assert(oldkeys->dk_refcnt == 1);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001292 if (oldkeys->dk_size == PyDict_MINSIZE &&
1293 numfreekeys < PyDict_MAXFREELIST) {
1294 DK_DEBUG_DECREF keys_free_list[numfreekeys++] = oldkeys;
1295 }
1296 else {
1297 DK_DEBUG_DECREF PyObject_FREE(oldkeys);
1298 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001299 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001300
1301 build_indices(mp->ma_keys, newentries, numentries);
1302 mp->ma_keys->dk_usable -= numentries;
1303 mp->ma_keys->dk_nentries = numentries;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001305}
1306
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001307/* Returns NULL if unable to split table.
1308 * A NULL return does not necessarily indicate an error */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001309static PyDictKeysObject *
1310make_keys_shared(PyObject *op)
1311{
1312 Py_ssize_t i;
1313 Py_ssize_t size;
1314 PyDictObject *mp = (PyDictObject *)op;
1315
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001316 if (!PyDict_CheckExact(op))
1317 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001318 if (!_PyDict_HasSplitTable(mp)) {
1319 PyDictKeyEntry *ep0;
1320 PyObject **values;
1321 assert(mp->ma_keys->dk_refcnt == 1);
1322 if (mp->ma_keys->dk_lookup == lookdict) {
1323 return NULL;
1324 }
1325 else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
1326 /* Remove dummy keys */
1327 if (dictresize(mp, DK_SIZE(mp->ma_keys)))
1328 return NULL;
1329 }
1330 assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
1331 /* Copy values into a new array */
Victor Stinner742da042016-09-07 17:40:12 -07001332 ep0 = DK_ENTRIES(mp->ma_keys);
1333 size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001334 values = new_values(size);
1335 if (values == NULL) {
1336 PyErr_SetString(PyExc_MemoryError,
1337 "Not enough memory to allocate new values array");
1338 return NULL;
1339 }
1340 for (i = 0; i < size; i++) {
1341 values[i] = ep0[i].me_value;
1342 ep0[i].me_value = NULL;
1343 }
1344 mp->ma_keys->dk_lookup = lookdict_split;
1345 mp->ma_values = values;
1346 }
1347 DK_INCREF(mp->ma_keys);
1348 return mp->ma_keys;
1349}
Christian Heimes99170a52007-12-19 02:07:34 +00001350
1351PyObject *
1352_PyDict_NewPresized(Py_ssize_t minused)
1353{
INADA Naoki92c50ee2016-11-22 00:57:02 +09001354 const Py_ssize_t max_presize = 128 * 1024;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001355 Py_ssize_t newsize;
1356 PyDictKeysObject *new_keys;
INADA Naoki92c50ee2016-11-22 00:57:02 +09001357
1358 /* There are no strict guarantee that returned dict can contain minused
1359 * items without resize. So we create medium size dict instead of very
1360 * large dict or MemoryError.
1361 */
1362 if (minused > USABLE_FRACTION(max_presize)) {
1363 newsize = max_presize;
1364 }
1365 else {
1366 Py_ssize_t minsize = ESTIMATE_SIZE(minused);
1367 newsize = PyDict_MINSIZE;
1368 while (newsize < minsize) {
1369 newsize <<= 1;
1370 }
1371 }
1372 assert(IS_POWER_OF_2(newsize));
1373
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001374 new_keys = new_keys_object(newsize);
1375 if (new_keys == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001377 return new_dict(new_keys, NULL);
Christian Heimes99170a52007-12-19 02:07:34 +00001378}
1379
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001380/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
1381 * that may occur (originally dicts supported only string keys, and exceptions
1382 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001383 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001384 * (suppressed) occurred while computing the key's hash, or that some error
1385 * (suppressed) occurred when comparing keys in the dict's internal probe
1386 * sequence. A nasty example of the latter is when a Python-coded comparison
1387 * function hits a stack-depth error, which can cause this to return NULL
1388 * even if the key is present.
1389 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001390PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001391PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001392{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001393 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001394 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 PyDictObject *mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 PyThreadState *tstate;
INADA Naokiba609772016-12-07 20:41:42 +09001397 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 if (!PyDict_Check(op))
1400 return NULL;
1401 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001402 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 {
1404 hash = PyObject_Hash(key);
1405 if (hash == -1) {
1406 PyErr_Clear();
1407 return NULL;
1408 }
1409 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 /* We can arrive here with a NULL tstate during initialization: try
1412 running "python -Wi" for an example related to string interning.
1413 Let's just hope that no exception occurs then... This must be
1414 _PyThreadState_Current and not PyThreadState_GET() because in debug
1415 mode, the latter complains if tstate is NULL. */
Victor Stinner0cae6092016-11-11 01:43:56 +01001416 tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 if (tstate != NULL && tstate->curexc_type != NULL) {
1418 /* preserve the existing exception */
1419 PyObject *err_type, *err_value, *err_tb;
1420 PyErr_Fetch(&err_type, &err_value, &err_tb);
INADA Naokiba609772016-12-07 20:41:42 +09001421 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 /* ignore errors */
1423 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001424 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 return NULL;
1426 }
1427 else {
INADA Naokiba609772016-12-07 20:41:42 +09001428 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001429 if (ix < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 PyErr_Clear();
1431 return NULL;
1432 }
1433 }
INADA Naokiba609772016-12-07 20:41:42 +09001434 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001435}
1436
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001437/* Same as PyDict_GetItemWithError() but with hash supplied by caller.
1438 This returns NULL *with* an exception set if an exception occurred.
1439 It returns NULL *without* an exception set if the key wasn't present.
1440*/
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001441PyObject *
1442_PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1443{
Victor Stinner742da042016-09-07 17:40:12 -07001444 Py_ssize_t ix;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001445 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001446 PyObject *value;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001447
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001448 if (!PyDict_Check(op)) {
1449 PyErr_BadInternalCall();
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001450 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001451 }
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001452
INADA Naokiba609772016-12-07 20:41:42 +09001453 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001454 if (ix < 0) {
1455 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001456 }
INADA Naokiba609772016-12-07 20:41:42 +09001457 return value;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001458}
1459
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001460/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
1461 This returns NULL *with* an exception set if an exception occurred.
1462 It returns NULL *without* an exception set if the key wasn't present.
1463*/
1464PyObject *
1465PyDict_GetItemWithError(PyObject *op, PyObject *key)
1466{
Victor Stinner742da042016-09-07 17:40:12 -07001467 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001468 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 PyDictObject*mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001470 PyObject *value;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (!PyDict_Check(op)) {
1473 PyErr_BadInternalCall();
1474 return NULL;
1475 }
1476 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001477 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 {
1479 hash = PyObject_Hash(key);
1480 if (hash == -1) {
1481 return NULL;
1482 }
1483 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001484
INADA Naokiba609772016-12-07 20:41:42 +09001485 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001486 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001488 return value;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001489}
1490
Brett Cannonfd074152012-04-14 14:10:13 -04001491PyObject *
1492_PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
1493{
1494 PyObject *kv;
1495 kv = _PyUnicode_FromId(key); /* borrowed */
1496 if (kv == NULL)
1497 return NULL;
1498 return PyDict_GetItemWithError(dp, kv);
1499}
1500
Victor Stinnerb4efc962015-11-20 09:24:02 +01001501/* Fast version of global value lookup (LOAD_GLOBAL).
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001502 * Lookup in globals, then builtins.
Victor Stinnerb4efc962015-11-20 09:24:02 +01001503 *
1504 * Raise an exception and return NULL if an error occurred (ex: computing the
1505 * key hash failed, key comparison failed, ...). Return NULL if the key doesn't
1506 * exist. Return the value if the key exists.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001507 */
1508PyObject *
1509_PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001510{
Victor Stinner742da042016-09-07 17:40:12 -07001511 Py_ssize_t ix;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001512 Py_hash_t hash;
INADA Naokiba609772016-12-07 20:41:42 +09001513 PyObject *value;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001514
1515 if (!PyUnicode_CheckExact(key) ||
1516 (hash = ((PyASCIIObject *) key)->hash) == -1)
1517 {
1518 hash = PyObject_Hash(key);
1519 if (hash == -1)
1520 return NULL;
Antoine Pitroue965d972012-02-27 00:45:12 +01001521 }
Victor Stinnerb4efc962015-11-20 09:24:02 +01001522
1523 /* namespace 1: globals */
INADA Naokiba609772016-12-07 20:41:42 +09001524 ix = globals->ma_keys->dk_lookup(globals, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001525 if (ix == DKIX_ERROR)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001526 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001527 if (ix != DKIX_EMPTY && value != NULL)
1528 return value;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001529
1530 /* namespace 2: builtins */
INADA Naokiba609772016-12-07 20:41:42 +09001531 ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001532 if (ix < 0)
Victor Stinnerb4efc962015-11-20 09:24:02 +01001533 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001534 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001535}
1536
Antoine Pitroue965d972012-02-27 00:45:12 +01001537/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
1538 * dictionary if it's merely replacing the value for an existing key.
1539 * This means that it's safe to loop over a dictionary with PyDict_Next()
1540 * and occasionally replace a value -- but you can't insert new keys or
1541 * remove them.
1542 */
1543int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001544PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001545{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001546 PyDictObject *mp;
1547 Py_hash_t hash;
Antoine Pitroue965d972012-02-27 00:45:12 +01001548 if (!PyDict_Check(op)) {
1549 PyErr_BadInternalCall();
1550 return -1;
1551 }
1552 assert(key);
1553 assert(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001554 mp = (PyDictObject *)op;
1555 if (!PyUnicode_CheckExact(key) ||
1556 (hash = ((PyASCIIObject *) key)->hash) == -1)
1557 {
Antoine Pitroue965d972012-02-27 00:45:12 +01001558 hash = PyObject_Hash(key);
1559 if (hash == -1)
1560 return -1;
1561 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001562
1563 /* insertdict() handles any resizing that might be necessary */
1564 return insertdict(mp, key, hash, value);
Antoine Pitroue965d972012-02-27 00:45:12 +01001565}
1566
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001567int
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001568_PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
1569 Py_hash_t hash)
1570{
1571 PyDictObject *mp;
1572
1573 if (!PyDict_Check(op)) {
1574 PyErr_BadInternalCall();
1575 return -1;
1576 }
1577 assert(key);
1578 assert(value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001579 assert(hash != -1);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001580 mp = (PyDictObject *)op;
1581
1582 /* insertdict() handles any resizing that might be necessary */
1583 return insertdict(mp, key, hash, value);
1584}
1585
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001586static int
Antoine Pitroud741ed42016-12-27 14:23:43 +01001587delitem_common(PyDictObject *mp, Py_ssize_t hashpos, Py_ssize_t ix,
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001588 PyObject *old_value)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001589{
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001590 PyObject *old_key;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001591 PyDictKeyEntry *ep;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001592
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001593 mp->ma_used--;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001594 mp->ma_version_tag = DICT_NEXT_VERSION();
1595 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1596 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1597 ENSURE_ALLOWS_DELETIONS(mp);
1598 old_key = ep->me_key;
1599 ep->me_key = NULL;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001600 ep->me_value = NULL;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001601 Py_DECREF(old_key);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001602 Py_DECREF(old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001603
1604 assert(_PyDict_CheckConsistency(mp));
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001605 return 0;
1606}
1607
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001608int
Tim Peters1f5871e2000-07-04 17:44:48 +00001609PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001610{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001611 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 assert(key);
1613 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001614 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 hash = PyObject_Hash(key);
1616 if (hash == -1)
1617 return -1;
1618 }
Victor Stinner742da042016-09-07 17:40:12 -07001619
1620 return _PyDict_DelItem_KnownHash(op, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001621}
1622
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001623int
1624_PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1625{
Victor Stinner742da042016-09-07 17:40:12 -07001626 Py_ssize_t hashpos, ix;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001627 PyDictObject *mp;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001628 PyObject *old_value;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001629
1630 if (!PyDict_Check(op)) {
1631 PyErr_BadInternalCall();
1632 return -1;
1633 }
1634 assert(key);
1635 assert(hash != -1);
1636 mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001637 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value, &hashpos);
Victor Stinner742da042016-09-07 17:40:12 -07001638 if (ix == DKIX_ERROR)
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001639 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09001640 if (ix == DKIX_EMPTY || old_value == NULL) {
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001641 _PyErr_SetKeyError(key);
1642 return -1;
1643 }
Victor Stinner742da042016-09-07 17:40:12 -07001644 assert(dk_get_index(mp->ma_keys, hashpos) == ix);
Victor Stinner78601a32016-09-09 19:28:36 -07001645
1646 // Split table doesn't allow deletion. Combine it.
1647 if (_PyDict_HasSplitTable(mp)) {
1648 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1649 return -1;
1650 }
INADA Naokiba609772016-12-07 20:41:42 +09001651 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value, &hashpos);
Victor Stinner78601a32016-09-09 19:28:36 -07001652 assert(ix >= 0);
1653 }
1654
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001655 return delitem_common(mp, hashpos, ix, old_value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001656}
1657
Antoine Pitroud741ed42016-12-27 14:23:43 +01001658/* This function promises that the predicate -> deletion sequence is atomic
1659 * (i.e. protected by the GIL), assuming the predicate itself doesn't
1660 * release the GIL.
1661 */
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001662int
1663_PyDict_DelItemIf(PyObject *op, PyObject *key,
1664 int (*predicate)(PyObject *value))
1665{
Antoine Pitroud741ed42016-12-27 14:23:43 +01001666 Py_ssize_t hashpos, ix;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001667 PyDictObject *mp;
1668 Py_hash_t hash;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001669 PyObject *old_value;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001670 int res;
1671
1672 if (!PyDict_Check(op)) {
1673 PyErr_BadInternalCall();
1674 return -1;
1675 }
1676 assert(key);
1677 hash = PyObject_Hash(key);
1678 if (hash == -1)
1679 return -1;
1680 mp = (PyDictObject *)op;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001681 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value, &hashpos);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001682 if (ix == DKIX_ERROR)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001683 return -1;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001684 if (ix == DKIX_EMPTY || old_value == NULL) {
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001685 _PyErr_SetKeyError(key);
1686 return -1;
1687 }
Antoine Pitroud741ed42016-12-27 14:23:43 +01001688 assert(dk_get_index(mp->ma_keys, hashpos) == ix);
1689
1690 // Split table doesn't allow deletion. Combine it.
1691 if (_PyDict_HasSplitTable(mp)) {
1692 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1693 return -1;
1694 }
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001695 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value, &hashpos);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001696 assert(ix >= 0);
1697 }
1698
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001699 res = predicate(old_value);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001700 if (res == -1)
1701 return -1;
1702 if (res > 0)
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001703 return delitem_common(mp, hashpos, ix, old_value);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001704 else
1705 return 0;
1706}
1707
1708
Guido van Rossum25831651993-05-19 14:50:45 +00001709void
Tim Peters1f5871e2000-07-04 17:44:48 +00001710PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 PyDictObject *mp;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001713 PyDictKeysObject *oldkeys;
1714 PyObject **oldvalues;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +00001716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 if (!PyDict_Check(op))
1718 return;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001719 mp = ((PyDictObject *)op);
1720 oldkeys = mp->ma_keys;
1721 oldvalues = mp->ma_values;
1722 if (oldvalues == empty_values)
1723 return;
1724 /* Empty the dict... */
1725 DK_INCREF(Py_EMPTY_KEYS);
1726 mp->ma_keys = Py_EMPTY_KEYS;
1727 mp->ma_values = empty_values;
1728 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001729 mp->ma_version_tag = DICT_NEXT_VERSION();
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001730 /* ...then clear the keys and values */
1731 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001732 n = oldkeys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001733 for (i = 0; i < n; i++)
1734 Py_CLEAR(oldvalues[i]);
1735 free_values(oldvalues);
1736 DK_DECREF(oldkeys);
1737 }
1738 else {
1739 assert(oldkeys->dk_refcnt == 1);
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001740 DK_DECREF(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001741 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02001742 assert(_PyDict_CheckConsistency(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001743}
1744
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001745/* Internal version of PyDict_Next that returns a hash value in addition
1746 * to the key and value.
1747 * Return 1 on success, return 0 when the reached the end of the dictionary
1748 * (or if op is not a dictionary)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001749 */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001750int
1751_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
1752 PyObject **pvalue, Py_hash_t *phash)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001753{
INADA Naokica2d8be2016-11-04 16:59:10 +09001754 Py_ssize_t i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001755 PyDictObject *mp;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001756 PyDictKeyEntry *entry_ptr;
1757 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001758
1759 if (!PyDict_Check(op))
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001760 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 mp = (PyDictObject *)op;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001762 i = *ppos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001763 if (mp->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09001764 if (i < 0 || i >= mp->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001765 return 0;
INADA Naokica2d8be2016-11-04 16:59:10 +09001766 /* values of split table is always dense */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001767 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
INADA Naokica2d8be2016-11-04 16:59:10 +09001768 value = mp->ma_values[i];
1769 assert(value != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001771 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09001772 Py_ssize_t n = mp->ma_keys->dk_nentries;
1773 if (i < 0 || i >= n)
1774 return 0;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001775 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
1776 while (i < n && entry_ptr->me_value == NULL) {
1777 entry_ptr++;
1778 i++;
Victor Stinner742da042016-09-07 17:40:12 -07001779 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001780 if (i >= n)
1781 return 0;
1782 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001784 *ppos = i+1;
1785 if (pkey)
1786 *pkey = entry_ptr->me_key;
1787 if (phash)
1788 *phash = entry_ptr->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001789 if (pvalue)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001790 *pvalue = value;
1791 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001792}
1793
Tim Peters080c88b2003-02-15 03:01:11 +00001794/*
1795 * Iterate over a dict. Use like so:
1796 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001797 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +00001798 * PyObject *key, *value;
1799 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +00001800 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001801 * Refer to borrowed references in key and value.
Tim Peters080c88b2003-02-15 03:01:11 +00001802 * }
1803 *
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001804 * Return 1 on success, return 0 when the reached the end of the dictionary
1805 * (or if op is not a dictionary)
1806 *
Tim Peters080c88b2003-02-15 03:01:11 +00001807 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +00001808 * mutates the dict. One exception: it is safe if the loop merely changes
1809 * the values associated with the keys (but doesn't insert new keys or
1810 * delete keys), via PyDict_SetItem().
1811 */
Guido van Rossum25831651993-05-19 14:50:45 +00001812int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001813PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001814{
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001815 return _PyDict_Next(op, ppos, pkey, pvalue, NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00001816}
1817
Eric Snow96c6af92015-05-29 22:21:39 -06001818/* Internal version of dict.pop(). */
1819PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001820_PyDict_Pop_KnownHash(PyObject *dict, PyObject *key, Py_hash_t hash, PyObject *deflt)
Eric Snow96c6af92015-05-29 22:21:39 -06001821{
Victor Stinner742da042016-09-07 17:40:12 -07001822 Py_ssize_t ix, hashpos;
Eric Snow96c6af92015-05-29 22:21:39 -06001823 PyObject *old_value, *old_key;
1824 PyDictKeyEntry *ep;
Yury Selivanov684ef2c2016-10-28 19:01:21 -04001825 PyDictObject *mp;
1826
1827 assert(PyDict_Check(dict));
1828 mp = (PyDictObject *)dict;
Eric Snow96c6af92015-05-29 22:21:39 -06001829
1830 if (mp->ma_used == 0) {
1831 if (deflt) {
1832 Py_INCREF(deflt);
1833 return deflt;
1834 }
1835 _PyErr_SetKeyError(key);
1836 return NULL;
1837 }
INADA Naokiba609772016-12-07 20:41:42 +09001838 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value, &hashpos);
Victor Stinner742da042016-09-07 17:40:12 -07001839 if (ix == DKIX_ERROR)
Eric Snow96c6af92015-05-29 22:21:39 -06001840 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001841 if (ix == DKIX_EMPTY || old_value == NULL) {
Eric Snow96c6af92015-05-29 22:21:39 -06001842 if (deflt) {
1843 Py_INCREF(deflt);
1844 return deflt;
1845 }
1846 _PyErr_SetKeyError(key);
1847 return NULL;
1848 }
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001849
Victor Stinner78601a32016-09-09 19:28:36 -07001850 // Split table doesn't allow deletion. Combine it.
1851 if (_PyDict_HasSplitTable(mp)) {
1852 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1853 return NULL;
1854 }
INADA Naokiba609772016-12-07 20:41:42 +09001855 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value, &hashpos);
Victor Stinner78601a32016-09-09 19:28:36 -07001856 assert(ix >= 0);
1857 }
1858
Victor Stinner78601a32016-09-09 19:28:36 -07001859 assert(old_value != NULL);
Eric Snow96c6af92015-05-29 22:21:39 -06001860 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001861 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner78601a32016-09-09 19:28:36 -07001862 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1863 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1864 ENSURE_ALLOWS_DELETIONS(mp);
1865 old_key = ep->me_key;
1866 ep->me_key = NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001867 ep->me_value = NULL;
Victor Stinner78601a32016-09-09 19:28:36 -07001868 Py_DECREF(old_key);
Victor Stinner611b0fa2016-09-14 15:02:01 +02001869
1870 assert(_PyDict_CheckConsistency(mp));
Eric Snow96c6af92015-05-29 22:21:39 -06001871 return old_value;
1872}
1873
Serhiy Storchaka67796522017-01-12 18:34:33 +02001874PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001875_PyDict_Pop(PyObject *dict, PyObject *key, PyObject *deflt)
Serhiy Storchaka67796522017-01-12 18:34:33 +02001876{
1877 Py_hash_t hash;
1878
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001879 if (((PyDictObject *)dict)->ma_used == 0) {
Serhiy Storchaka67796522017-01-12 18:34:33 +02001880 if (deflt) {
1881 Py_INCREF(deflt);
1882 return deflt;
1883 }
1884 _PyErr_SetKeyError(key);
1885 return NULL;
1886 }
1887 if (!PyUnicode_CheckExact(key) ||
1888 (hash = ((PyASCIIObject *) key)->hash) == -1) {
1889 hash = PyObject_Hash(key);
1890 if (hash == -1)
1891 return NULL;
1892 }
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001893 return _PyDict_Pop_KnownHash(dict, key, hash, deflt);
Serhiy Storchaka67796522017-01-12 18:34:33 +02001894}
1895
Eric Snow96c6af92015-05-29 22:21:39 -06001896/* Internal version of dict.from_keys(). It is subclass-friendly. */
1897PyObject *
1898_PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
1899{
1900 PyObject *it; /* iter(iterable) */
1901 PyObject *key;
1902 PyObject *d;
1903 int status;
1904
Victor Stinnera5ed5f02016-12-06 18:45:50 +01001905 d = _PyObject_CallNoArg(cls);
Eric Snow96c6af92015-05-29 22:21:39 -06001906 if (d == NULL)
1907 return NULL;
1908
1909 if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
1910 if (PyDict_CheckExact(iterable)) {
1911 PyDictObject *mp = (PyDictObject *)d;
1912 PyObject *oldvalue;
1913 Py_ssize_t pos = 0;
1914 PyObject *key;
1915 Py_hash_t hash;
1916
Victor Stinner742da042016-09-07 17:40:12 -07001917 if (dictresize(mp, ESTIMATE_SIZE(Py_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001918 Py_DECREF(d);
1919 return NULL;
1920 }
1921
1922 while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
1923 if (insertdict(mp, key, hash, value)) {
1924 Py_DECREF(d);
1925 return NULL;
1926 }
1927 }
1928 return d;
1929 }
1930 if (PyAnySet_CheckExact(iterable)) {
1931 PyDictObject *mp = (PyDictObject *)d;
1932 Py_ssize_t pos = 0;
1933 PyObject *key;
1934 Py_hash_t hash;
1935
Victor Stinner742da042016-09-07 17:40:12 -07001936 if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001937 Py_DECREF(d);
1938 return NULL;
1939 }
1940
1941 while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
1942 if (insertdict(mp, key, hash, value)) {
1943 Py_DECREF(d);
1944 return NULL;
1945 }
1946 }
1947 return d;
1948 }
1949 }
1950
1951 it = PyObject_GetIter(iterable);
1952 if (it == NULL){
1953 Py_DECREF(d);
1954 return NULL;
1955 }
1956
1957 if (PyDict_CheckExact(d)) {
1958 while ((key = PyIter_Next(it)) != NULL) {
1959 status = PyDict_SetItem(d, key, value);
1960 Py_DECREF(key);
1961 if (status < 0)
1962 goto Fail;
1963 }
1964 } else {
1965 while ((key = PyIter_Next(it)) != NULL) {
1966 status = PyObject_SetItem(d, key, value);
1967 Py_DECREF(key);
1968 if (status < 0)
1969 goto Fail;
1970 }
1971 }
1972
1973 if (PyErr_Occurred())
1974 goto Fail;
1975 Py_DECREF(it);
1976 return d;
1977
1978Fail:
1979 Py_DECREF(it);
1980 Py_DECREF(d);
1981 return NULL;
1982}
1983
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001984/* Methods */
1985
1986static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001987dict_dealloc(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001988{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001989 PyObject **values = mp->ma_values;
1990 PyDictKeysObject *keys = mp->ma_keys;
1991 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 PyObject_GC_UnTrack(mp);
1993 Py_TRASHCAN_SAFE_BEGIN(mp)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001994 if (values != NULL) {
1995 if (values != empty_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001996 for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001997 Py_XDECREF(values[i]);
1998 }
1999 free_values(values);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002001 DK_DECREF(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 }
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02002003 else if (keys != NULL) {
Antoine Pitrou2d169b22012-05-12 23:43:44 +02002004 assert(keys->dk_refcnt == 1);
2005 DK_DECREF(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002006 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
2008 free_list[numfree++] = mp;
2009 else
2010 Py_TYPE(mp)->tp_free((PyObject *)mp);
2011 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002012}
2013
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002014
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002015static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002016dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 Py_ssize_t i;
Victor Stinnerf91929b2013-11-19 13:07:38 +01002019 PyObject *key = NULL, *value = NULL;
2020 _PyUnicodeWriter writer;
2021 int first;
Guido van Rossum255443b1998-04-10 22:47:14 +00002022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 i = Py_ReprEnter((PyObject *)mp);
2024 if (i != 0) {
2025 return i > 0 ? PyUnicode_FromString("{...}") : NULL;
2026 }
Guido van Rossum255443b1998-04-10 22:47:14 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 if (mp->ma_used == 0) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01002029 Py_ReprLeave((PyObject *)mp);
2030 return PyUnicode_FromString("{}");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 }
Tim Petersa7259592001-06-16 05:11:17 +00002032
Victor Stinnerf91929b2013-11-19 13:07:38 +01002033 _PyUnicodeWriter_Init(&writer);
2034 writer.overallocate = 1;
2035 /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
2036 writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +00002037
Victor Stinnerf91929b2013-11-19 13:07:38 +01002038 if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
2039 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 /* Do repr() on each key+value pair, and insert ": " between them.
2042 Note that repr may mutate the dict. */
2043 i = 0;
Victor Stinnerf91929b2013-11-19 13:07:38 +01002044 first = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01002046 PyObject *s;
2047 int res;
2048
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002049 /* Prevent repr from deleting key or value during key format. */
2050 Py_INCREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 Py_INCREF(value);
Victor Stinnerf97dfd72013-07-18 01:00:45 +02002052
Victor Stinnerf91929b2013-11-19 13:07:38 +01002053 if (!first) {
2054 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
2055 goto error;
2056 }
2057 first = 0;
2058
2059 s = PyObject_Repr(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 if (s == NULL)
Victor Stinnerf91929b2013-11-19 13:07:38 +01002061 goto error;
2062 res = _PyUnicodeWriter_WriteStr(&writer, s);
2063 Py_DECREF(s);
2064 if (res < 0)
2065 goto error;
2066
2067 if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
2068 goto error;
2069
2070 s = PyObject_Repr(value);
2071 if (s == NULL)
2072 goto error;
2073 res = _PyUnicodeWriter_WriteStr(&writer, s);
2074 Py_DECREF(s);
2075 if (res < 0)
2076 goto error;
2077
2078 Py_CLEAR(key);
2079 Py_CLEAR(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 }
Tim Petersa7259592001-06-16 05:11:17 +00002081
Victor Stinnerf91929b2013-11-19 13:07:38 +01002082 writer.overallocate = 0;
2083 if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
2084 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00002085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 Py_ReprLeave((PyObject *)mp);
Victor Stinnerf91929b2013-11-19 13:07:38 +01002087
2088 return _PyUnicodeWriter_Finish(&writer);
2089
2090error:
2091 Py_ReprLeave((PyObject *)mp);
2092 _PyUnicodeWriter_Dealloc(&writer);
2093 Py_XDECREF(key);
2094 Py_XDECREF(value);
2095 return NULL;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002096}
2097
Martin v. Löwis18e16552006-02-15 17:27:45 +00002098static Py_ssize_t
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002099dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 return mp->ma_used;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002102}
2103
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002104static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002105dict_subscript(PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002106{
Victor Stinner742da042016-09-07 17:40:12 -07002107 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002108 Py_hash_t hash;
INADA Naokiba609772016-12-07 20:41:42 +09002109 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002112 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 hash = PyObject_Hash(key);
2114 if (hash == -1)
2115 return NULL;
2116 }
INADA Naokiba609772016-12-07 20:41:42 +09002117 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07002118 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002120 if (ix == DKIX_EMPTY || value == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 if (!PyDict_CheckExact(mp)) {
2122 /* Look up __missing__ method if we're a subclass. */
2123 PyObject *missing, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05002124 _Py_IDENTIFIER(__missing__);
2125 missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 if (missing != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002127 res = PyObject_CallFunctionObjArgs(missing,
2128 key, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 Py_DECREF(missing);
2130 return res;
2131 }
2132 else if (PyErr_Occurred())
2133 return NULL;
2134 }
Raymond Hettinger69492da2013-09-02 15:59:26 -07002135 _PyErr_SetKeyError(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 return NULL;
2137 }
INADA Naokiba609772016-12-07 20:41:42 +09002138 Py_INCREF(value);
2139 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002140}
2141
2142static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002143dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 if (w == NULL)
2146 return PyDict_DelItem((PyObject *)mp, v);
2147 else
2148 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002149}
2150
Guido van Rossuma9e7a811997-05-13 21:02:11 +00002151static PyMappingMethods dict_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 (lenfunc)dict_length, /*mp_length*/
2153 (binaryfunc)dict_subscript, /*mp_subscript*/
2154 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002155};
2156
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002157static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002158dict_keys(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002159{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002160 PyObject *v;
2161 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002162 PyDictKeyEntry *ep;
2163 Py_ssize_t size, n, offset;
2164 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002165
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002166 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 n = mp->ma_used;
2168 v = PyList_New(n);
2169 if (v == NULL)
2170 return NULL;
2171 if (n != mp->ma_used) {
2172 /* Durnit. The allocations caused the dict to resize.
2173 * Just start over, this shouldn't normally happen.
2174 */
2175 Py_DECREF(v);
2176 goto again;
2177 }
Victor Stinner742da042016-09-07 17:40:12 -07002178 ep = DK_ENTRIES(mp->ma_keys);
2179 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002180 if (mp->ma_values) {
2181 value_ptr = mp->ma_values;
2182 offset = sizeof(PyObject *);
2183 }
2184 else {
2185 value_ptr = &ep[0].me_value;
2186 offset = sizeof(PyDictKeyEntry);
2187 }
2188 for (i = 0, j = 0; i < size; i++) {
2189 if (*value_ptr != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 PyObject *key = ep[i].me_key;
2191 Py_INCREF(key);
2192 PyList_SET_ITEM(v, j, key);
2193 j++;
2194 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002195 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 }
2197 assert(j == n);
2198 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002199}
2200
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002201static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002202dict_values(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002203{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002204 PyObject *v;
2205 Py_ssize_t i, j;
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002206 PyDictKeyEntry *ep;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002207 Py_ssize_t size, n, offset;
2208 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002209
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002210 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 n = mp->ma_used;
2212 v = PyList_New(n);
2213 if (v == NULL)
2214 return NULL;
2215 if (n != mp->ma_used) {
2216 /* Durnit. The allocations caused the dict to resize.
2217 * Just start over, this shouldn't normally happen.
2218 */
2219 Py_DECREF(v);
2220 goto again;
2221 }
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002222 ep = DK_ENTRIES(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002223 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002224 if (mp->ma_values) {
2225 value_ptr = mp->ma_values;
2226 offset = sizeof(PyObject *);
2227 }
2228 else {
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002229 value_ptr = &ep[0].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002230 offset = sizeof(PyDictKeyEntry);
2231 }
2232 for (i = 0, j = 0; i < size; i++) {
2233 PyObject *value = *value_ptr;
2234 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2235 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 Py_INCREF(value);
2237 PyList_SET_ITEM(v, j, value);
2238 j++;
2239 }
2240 }
2241 assert(j == n);
2242 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002243}
2244
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002245static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002246dict_items(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002247{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002248 PyObject *v;
2249 Py_ssize_t i, j, n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002250 Py_ssize_t size, offset;
2251 PyObject *item, *key;
2252 PyDictKeyEntry *ep;
2253 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 /* Preallocate the list of tuples, to avoid allocations during
2256 * the loop over the items, which could trigger GC, which
2257 * could resize the dict. :-(
2258 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002259 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 n = mp->ma_used;
2261 v = PyList_New(n);
2262 if (v == NULL)
2263 return NULL;
2264 for (i = 0; i < n; i++) {
2265 item = PyTuple_New(2);
2266 if (item == NULL) {
2267 Py_DECREF(v);
2268 return NULL;
2269 }
2270 PyList_SET_ITEM(v, i, item);
2271 }
2272 if (n != mp->ma_used) {
2273 /* Durnit. The allocations caused the dict to resize.
2274 * Just start over, this shouldn't normally happen.
2275 */
2276 Py_DECREF(v);
2277 goto again;
2278 }
2279 /* Nothing we do below makes any function calls. */
Victor Stinner742da042016-09-07 17:40:12 -07002280 ep = DK_ENTRIES(mp->ma_keys);
2281 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002282 if (mp->ma_values) {
2283 value_ptr = mp->ma_values;
2284 offset = sizeof(PyObject *);
2285 }
2286 else {
2287 value_ptr = &ep[0].me_value;
2288 offset = sizeof(PyDictKeyEntry);
2289 }
2290 for (i = 0, j = 0; i < size; i++) {
2291 PyObject *value = *value_ptr;
2292 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2293 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 key = ep[i].me_key;
2295 item = PyList_GET_ITEM(v, j);
2296 Py_INCREF(key);
2297 PyTuple_SET_ITEM(item, 0, key);
2298 Py_INCREF(value);
2299 PyTuple_SET_ITEM(item, 1, value);
2300 j++;
2301 }
2302 }
2303 assert(j == n);
2304 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002305}
2306
Larry Hastings5c661892014-01-24 06:17:25 -08002307/*[clinic input]
2308@classmethod
2309dict.fromkeys
Larry Hastings5c661892014-01-24 06:17:25 -08002310 iterable: object
2311 value: object=None
2312 /
2313
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002314Create a new dictionary with keys from iterable and values set to value.
Larry Hastings5c661892014-01-24 06:17:25 -08002315[clinic start generated code]*/
2316
Larry Hastings5c661892014-01-24 06:17:25 -08002317static PyObject *
2318dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002319/*[clinic end generated code: output=8fb98e4b10384999 input=382ba4855d0f74c3]*/
Larry Hastings5c661892014-01-24 06:17:25 -08002320{
Eric Snow96c6af92015-05-29 22:21:39 -06002321 return _PyDict_FromKeys((PyObject *)type, iterable, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002322}
2323
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002324static int
Victor Stinner742da042016-09-07 17:40:12 -07002325dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
2326 const char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 PyObject *arg = NULL;
2329 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
2332 result = -1;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 else if (arg != NULL) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02002335 _Py_IDENTIFIER(keys);
2336 if (_PyObject_HasAttrId(arg, &PyId_keys))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 result = PyDict_Merge(self, arg, 1);
2338 else
2339 result = PyDict_MergeFromSeq2(self, arg, 1);
2340 }
2341 if (result == 0 && kwds != NULL) {
2342 if (PyArg_ValidateKeywordArguments(kwds))
2343 result = PyDict_Merge(self, kwds, 1);
2344 else
2345 result = -1;
2346 }
2347 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002348}
2349
Victor Stinner91f0d4a2017-01-19 12:45:06 +01002350/* Note: dict.update() uses the METH_VARARGS|METH_KEYWORDS calling convention.
2351 Using METH_FASTCALL would make dict.update(**dict2) calls slower, see the
2352 issue #29312. */
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002353static PyObject *
2354dict_update(PyObject *self, PyObject *args, PyObject *kwds)
2355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 if (dict_update_common(self, args, kwds, "update") != -1)
2357 Py_RETURN_NONE;
2358 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002359}
2360
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002361/* Update unconditionally replaces existing items.
2362 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00002363 otherwise it leaves existing items unchanged.
2364
2365 PyDict_{Update,Merge} update/merge from a mapping object.
2366
Tim Petersf582b822001-12-11 18:51:08 +00002367 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00002368 producing iterable objects of length 2.
2369*/
2370
Tim Petersf582b822001-12-11 18:51:08 +00002371int
Tim Peters1fc240e2001-10-26 05:06:50 +00002372PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
2373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 PyObject *it; /* iter(seq2) */
2375 Py_ssize_t i; /* index into seq2 of current element */
2376 PyObject *item; /* seq2[i] */
2377 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 assert(d != NULL);
2380 assert(PyDict_Check(d));
2381 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 it = PyObject_GetIter(seq2);
2384 if (it == NULL)
2385 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 for (i = 0; ; ++i) {
2388 PyObject *key, *value;
2389 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 fast = NULL;
2392 item = PyIter_Next(it);
2393 if (item == NULL) {
2394 if (PyErr_Occurred())
2395 goto Fail;
2396 break;
2397 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 /* Convert item to sequence, and verify length 2. */
2400 fast = PySequence_Fast(item, "");
2401 if (fast == NULL) {
2402 if (PyErr_ExceptionMatches(PyExc_TypeError))
2403 PyErr_Format(PyExc_TypeError,
2404 "cannot convert dictionary update "
2405 "sequence element #%zd to a sequence",
2406 i);
2407 goto Fail;
2408 }
2409 n = PySequence_Fast_GET_SIZE(fast);
2410 if (n != 2) {
2411 PyErr_Format(PyExc_ValueError,
2412 "dictionary update sequence element #%zd "
2413 "has length %zd; 2 is required",
2414 i, n);
2415 goto Fail;
2416 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 /* Update/merge with this (key, value) pair. */
2419 key = PySequence_Fast_GET_ITEM(fast, 0);
2420 value = PySequence_Fast_GET_ITEM(fast, 1);
2421 if (override || PyDict_GetItem(d, key) == NULL) {
2422 int status = PyDict_SetItem(d, key, value);
2423 if (status < 0)
2424 goto Fail;
2425 }
2426 Py_DECREF(fast);
2427 Py_DECREF(item);
2428 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 i = 0;
Victor Stinner611b0fa2016-09-14 15:02:01 +02002431 assert(_PyDict_CheckConsistency((PyDictObject *)d));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00002433Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 Py_XDECREF(item);
2435 Py_XDECREF(fast);
2436 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002437Return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 Py_DECREF(it);
2439 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00002440}
2441
doko@ubuntu.comc96df682016-10-11 08:04:02 +02002442static int
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002443dict_merge(PyObject *a, PyObject *b, int override)
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002444{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002445 PyDictObject *mp, *other;
2446 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -07002447 PyDictKeyEntry *entry, *ep0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002448
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002449 assert(0 <= override && override <= 2);
2450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 /* We accept for the argument either a concrete dictionary object,
2452 * or an abstract "mapping" object. For the former, we can do
2453 * things quite efficiently. For the latter, we only require that
2454 * PyMapping_Keys() and PyObject_GetItem() be supported.
2455 */
2456 if (a == NULL || !PyDict_Check(a) || b == NULL) {
2457 PyErr_BadInternalCall();
2458 return -1;
2459 }
2460 mp = (PyDictObject*)a;
2461 if (PyDict_Check(b)) {
2462 other = (PyDictObject*)b;
2463 if (other == mp || other->ma_used == 0)
2464 /* a.update(a) or a.update({}); nothing to do */
2465 return 0;
2466 if (mp->ma_used == 0)
2467 /* Since the target dict is empty, PyDict_GetItem()
2468 * always returns NULL. Setting override to 1
2469 * skips the unnecessary test.
2470 */
2471 override = 1;
2472 /* Do one big resize at the start, rather than
2473 * incrementally resizing as we insert new items. Expect
2474 * that there will be no (or few) overlapping keys.
2475 */
INADA Naokib1152be2016-10-27 19:26:50 +09002476 if (USABLE_FRACTION(mp->ma_keys->dk_size) < other->ma_used) {
2477 if (dictresize(mp, ESTIMATE_SIZE(mp->ma_used + other->ma_used))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 return -1;
INADA Naokib1152be2016-10-27 19:26:50 +09002479 }
2480 }
Victor Stinner742da042016-09-07 17:40:12 -07002481 ep0 = DK_ENTRIES(other->ma_keys);
2482 for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002483 PyObject *key, *value;
2484 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002485 entry = &ep0[i];
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002486 key = entry->me_key;
2487 hash = entry->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002488 if (other->ma_values)
2489 value = other->ma_values[i];
2490 else
2491 value = entry->me_value;
2492
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002493 if (value != NULL) {
2494 int err = 0;
2495 Py_INCREF(key);
2496 Py_INCREF(value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002497 if (override == 1)
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002498 err = insertdict(mp, key, hash, value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002499 else if (_PyDict_GetItem_KnownHash(a, key, hash) == NULL) {
2500 if (PyErr_Occurred()) {
2501 Py_DECREF(value);
2502 Py_DECREF(key);
2503 return -1;
2504 }
2505 err = insertdict(mp, key, hash, value);
2506 }
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002507 else if (override != 0) {
2508 _PyErr_SetKeyError(key);
2509 Py_DECREF(value);
2510 Py_DECREF(key);
2511 return -1;
2512 }
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002513 Py_DECREF(value);
2514 Py_DECREF(key);
2515 if (err != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 return -1;
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002517
Victor Stinner742da042016-09-07 17:40:12 -07002518 if (n != other->ma_keys->dk_nentries) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002519 PyErr_SetString(PyExc_RuntimeError,
2520 "dict mutated during update");
2521 return -1;
2522 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 }
2524 }
2525 }
2526 else {
2527 /* Do it the generic, slower way */
2528 PyObject *keys = PyMapping_Keys(b);
2529 PyObject *iter;
2530 PyObject *key, *value;
2531 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 if (keys == NULL)
2534 /* Docstring says this is equivalent to E.keys() so
2535 * if E doesn't have a .keys() method we want
2536 * AttributeError to percolate up. Might as well
2537 * do the same for any other error.
2538 */
2539 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 iter = PyObject_GetIter(keys);
2542 Py_DECREF(keys);
2543 if (iter == NULL)
2544 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002547 if (override != 1 && PyDict_GetItem(a, key) != NULL) {
2548 if (override != 0) {
2549 _PyErr_SetKeyError(key);
2550 Py_DECREF(key);
2551 Py_DECREF(iter);
2552 return -1;
2553 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 Py_DECREF(key);
2555 continue;
2556 }
2557 value = PyObject_GetItem(b, key);
2558 if (value == NULL) {
2559 Py_DECREF(iter);
2560 Py_DECREF(key);
2561 return -1;
2562 }
2563 status = PyDict_SetItem(a, key, value);
2564 Py_DECREF(key);
2565 Py_DECREF(value);
2566 if (status < 0) {
2567 Py_DECREF(iter);
2568 return -1;
2569 }
2570 }
2571 Py_DECREF(iter);
2572 if (PyErr_Occurred())
2573 /* Iterator completed, via error */
2574 return -1;
2575 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02002576 assert(_PyDict_CheckConsistency((PyDictObject *)a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002578}
2579
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002580int
2581PyDict_Update(PyObject *a, PyObject *b)
2582{
2583 return dict_merge(a, b, 1);
2584}
2585
2586int
2587PyDict_Merge(PyObject *a, PyObject *b, int override)
2588{
2589 /* XXX Deprecate override not in (0, 1). */
2590 return dict_merge(a, b, override != 0);
2591}
2592
2593int
2594_PyDict_MergeEx(PyObject *a, PyObject *b, int override)
2595{
2596 return dict_merge(a, b, override);
2597}
2598
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002599static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002600dict_copy(PyDictObject *mp)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002603}
2604
2605PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002606PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 PyObject *copy;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002609 PyDictObject *mp;
2610 Py_ssize_t i, n;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 if (o == NULL || !PyDict_Check(o)) {
2613 PyErr_BadInternalCall();
2614 return NULL;
2615 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002616 mp = (PyDictObject *)o;
2617 if (_PyDict_HasSplitTable(mp)) {
2618 PyDictObject *split_copy;
Victor Stinner742da042016-09-07 17:40:12 -07002619 Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
2620 PyObject **newvalues;
2621 newvalues = new_values(size);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002622 if (newvalues == NULL)
2623 return PyErr_NoMemory();
2624 split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
2625 if (split_copy == NULL) {
2626 free_values(newvalues);
2627 return NULL;
2628 }
2629 split_copy->ma_values = newvalues;
2630 split_copy->ma_keys = mp->ma_keys;
2631 split_copy->ma_used = mp->ma_used;
2632 DK_INCREF(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002633 for (i = 0, n = size; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002634 PyObject *value = mp->ma_values[i];
2635 Py_XINCREF(value);
2636 split_copy->ma_values[i] = value;
2637 }
Benjamin Peterson7ce67e42012-04-24 10:32:57 -04002638 if (_PyObject_GC_IS_TRACKED(mp))
2639 _PyObject_GC_TRACK(split_copy);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002640 return (PyObject *)split_copy;
2641 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 copy = PyDict_New();
2643 if (copy == NULL)
2644 return NULL;
2645 if (PyDict_Merge(copy, o, 1) == 0)
2646 return copy;
2647 Py_DECREF(copy);
2648 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002649}
2650
Martin v. Löwis18e16552006-02-15 17:27:45 +00002651Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00002652PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00002653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 if (mp == NULL || !PyDict_Check(mp)) {
2655 PyErr_BadInternalCall();
2656 return -1;
2657 }
2658 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00002659}
2660
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002661PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002662PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 if (mp == NULL || !PyDict_Check(mp)) {
2665 PyErr_BadInternalCall();
2666 return NULL;
2667 }
2668 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002669}
2670
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002671PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002672PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 if (mp == NULL || !PyDict_Check(mp)) {
2675 PyErr_BadInternalCall();
2676 return NULL;
2677 }
2678 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002679}
2680
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002681PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002682PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 if (mp == NULL || !PyDict_Check(mp)) {
2685 PyErr_BadInternalCall();
2686 return NULL;
2687 }
2688 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002689}
2690
Tim Peterse63415e2001-05-08 04:38:29 +00002691/* Return 1 if dicts equal, 0 if not, -1 if error.
2692 * Gets out as soon as any difference is detected.
2693 * Uses only Py_EQ comparison.
2694 */
2695static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002696dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00002697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00002699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 if (a->ma_used != b->ma_used)
2701 /* can't be equal if # of entries differ */
2702 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Victor Stinner742da042016-09-07 17:40:12 -07002704 for (i = 0; i < a->ma_keys->dk_nentries; i++) {
2705 PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002706 PyObject *aval;
2707 if (a->ma_values)
2708 aval = a->ma_values[i];
2709 else
2710 aval = ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 if (aval != NULL) {
2712 int cmp;
2713 PyObject *bval;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002714 PyObject *key = ep->me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 /* temporarily bump aval's refcount to ensure it stays
2716 alive until we're done with it */
2717 Py_INCREF(aval);
2718 /* ditto for key */
2719 Py_INCREF(key);
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002720 /* reuse the known hash value */
INADA Naokiba609772016-12-07 20:41:42 +09002721 b->ma_keys->dk_lookup(b, key, ep->me_hash, &bval, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 Py_DECREF(key);
2723 if (bval == NULL) {
2724 Py_DECREF(aval);
2725 if (PyErr_Occurred())
2726 return -1;
2727 return 0;
2728 }
2729 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
2730 Py_DECREF(aval);
2731 if (cmp <= 0) /* error or not equal */
2732 return cmp;
2733 }
2734 }
2735 return 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002736}
Tim Peterse63415e2001-05-08 04:38:29 +00002737
2738static PyObject *
2739dict_richcompare(PyObject *v, PyObject *w, int op)
2740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 int cmp;
2742 PyObject *res;
Tim Peterse63415e2001-05-08 04:38:29 +00002743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 if (!PyDict_Check(v) || !PyDict_Check(w)) {
2745 res = Py_NotImplemented;
2746 }
2747 else if (op == Py_EQ || op == Py_NE) {
2748 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
2749 if (cmp < 0)
2750 return NULL;
2751 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
2752 }
2753 else
2754 res = Py_NotImplemented;
2755 Py_INCREF(res);
2756 return res;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002757}
Tim Peterse63415e2001-05-08 04:38:29 +00002758
Larry Hastings61272b72014-01-07 12:41:53 -08002759/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002760
2761@coexist
2762dict.__contains__
2763
2764 key: object
2765 /
2766
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002767True if the dictionary has the specified key, else False.
Larry Hastings61272b72014-01-07 12:41:53 -08002768[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002769
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002770static PyObject *
Larry Hastingsc2047262014-01-25 20:43:29 -08002771dict___contains__(PyDictObject *self, PyObject *key)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002772/*[clinic end generated code: output=a3d03db709ed6e6b input=f39613886bf975b7]*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002773{
Larry Hastingsc2047262014-01-25 20:43:29 -08002774 register PyDictObject *mp = self;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002775 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002776 Py_ssize_t ix;
INADA Naokiba609772016-12-07 20:41:42 +09002777 PyObject *value;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002780 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 hash = PyObject_Hash(key);
2782 if (hash == -1)
2783 return NULL;
2784 }
INADA Naokiba609772016-12-07 20:41:42 +09002785 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07002786 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002788 if (ix == DKIX_EMPTY || value == NULL)
Victor Stinner742da042016-09-07 17:40:12 -07002789 Py_RETURN_FALSE;
2790 Py_RETURN_TRUE;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002791}
2792
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002793/*[clinic input]
2794dict.get
2795
2796 key: object
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002797 default: object = None
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002798 /
2799
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002800Return the value for key if key is in the dictionary, else default.
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002801[clinic start generated code]*/
2802
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002803static PyObject *
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002804dict_get_impl(PyDictObject *self, PyObject *key, PyObject *default_value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002805/*[clinic end generated code: output=bba707729dee05bf input=279ddb5790b6b107]*/
Barry Warsawc38c5da1997-10-06 17:49:20 +00002806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002808 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002809 Py_ssize_t ix;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002812 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 hash = PyObject_Hash(key);
2814 if (hash == -1)
2815 return NULL;
2816 }
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002817 ix = (self->ma_keys->dk_lookup) (self, key, hash, &val, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07002818 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002820 if (ix == DKIX_EMPTY || val == NULL) {
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002821 val = default_value;
INADA Naokiba609772016-12-07 20:41:42 +09002822 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 Py_INCREF(val);
2824 return val;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002825}
2826
Benjamin Peterson00e98862013-03-07 22:16:29 -05002827PyObject *
2828PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
Guido van Rossum164452c2000-08-08 16:12:54 +00002829{
Benjamin Peterson00e98862013-03-07 22:16:29 -05002830 PyDictObject *mp = (PyDictObject *)d;
INADA Naoki93f26f72016-11-02 18:45:16 +09002831 PyObject *value;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002832 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002833 Py_ssize_t hashpos, ix;
Guido van Rossum164452c2000-08-08 16:12:54 +00002834
Benjamin Peterson00e98862013-03-07 22:16:29 -05002835 if (!PyDict_Check(d)) {
2836 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 return NULL;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002838 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002841 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 hash = PyObject_Hash(key);
2843 if (hash == -1)
2844 return NULL;
2845 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002846
2847 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
2848 if (insertion_resize(mp) < 0)
2849 return NULL;
2850 }
2851
INADA Naokiba609772016-12-07 20:41:42 +09002852 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, &hashpos);
Victor Stinner742da042016-09-07 17:40:12 -07002853 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 return NULL;
INADA Naoki93f26f72016-11-02 18:45:16 +09002855
2856 if (_PyDict_HasSplitTable(mp) &&
INADA Naokiba609772016-12-07 20:41:42 +09002857 ((ix >= 0 && value == NULL && mp->ma_used != ix) ||
INADA Naoki93f26f72016-11-02 18:45:16 +09002858 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
2859 if (insertion_resize(mp) < 0) {
2860 return NULL;
2861 }
INADA Naokiba609772016-12-07 20:41:42 +09002862 hashpos = find_empty_slot(mp->ma_keys, key, hash);
INADA Naoki93f26f72016-11-02 18:45:16 +09002863 ix = DKIX_EMPTY;
2864 }
2865
2866 if (ix == DKIX_EMPTY) {
2867 PyDictKeyEntry *ep, *ep0;
2868 value = defaultobj;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002869 if (mp->ma_keys->dk_usable <= 0) {
Victor Stinner3c336c52016-09-12 14:17:40 +02002870 if (insertion_resize(mp) < 0) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002871 return NULL;
Victor Stinner3c336c52016-09-12 14:17:40 +02002872 }
INADA Naokiba609772016-12-07 20:41:42 +09002873 hashpos = find_empty_slot(mp->ma_keys, key, hash);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002874 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002875 ep0 = DK_ENTRIES(mp->ma_keys);
2876 ep = &ep0[mp->ma_keys->dk_nentries];
2877 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
Benjamin Petersonb1efa532013-03-04 09:47:50 -05002878 Py_INCREF(key);
INADA Naoki93f26f72016-11-02 18:45:16 +09002879 Py_INCREF(value);
2880 MAINTAIN_TRACKING(mp, key, value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002881 ep->me_key = key;
2882 ep->me_hash = hash;
INADA Naokiba609772016-12-07 20:41:42 +09002883 if (_PyDict_HasSplitTable(mp)) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002884 assert(mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
2885 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Victor Stinner742da042016-09-07 17:40:12 -07002886 }
2887 else {
INADA Naoki93f26f72016-11-02 18:45:16 +09002888 ep->me_value = value;
Victor Stinner742da042016-09-07 17:40:12 -07002889 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002890 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07002891 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naoki93f26f72016-11-02 18:45:16 +09002892 mp->ma_keys->dk_usable--;
2893 mp->ma_keys->dk_nentries++;
2894 assert(mp->ma_keys->dk_usable >= 0);
2895 }
INADA Naokiba609772016-12-07 20:41:42 +09002896 else if (value == NULL) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002897 value = defaultobj;
2898 assert(_PyDict_HasSplitTable(mp));
2899 assert(ix == mp->ma_used);
2900 Py_INCREF(value);
2901 MAINTAIN_TRACKING(mp, key, value);
INADA Naokiba609772016-12-07 20:41:42 +09002902 mp->ma_values[ix] = value;
INADA Naoki93f26f72016-11-02 18:45:16 +09002903 mp->ma_used++;
2904 mp->ma_version_tag = DICT_NEXT_VERSION();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002906
2907 assert(_PyDict_CheckConsistency(mp));
2908 return value;
Guido van Rossum164452c2000-08-08 16:12:54 +00002909}
2910
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002911/*[clinic input]
2912dict.setdefault
2913
2914 key: object
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002915 default: object = None
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002916 /
2917
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002918Insert key with a value of default if key is not in the dictionary.
2919
2920Return the value for key if key is in the dictionary, else default.
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002921[clinic start generated code]*/
2922
Benjamin Peterson00e98862013-03-07 22:16:29 -05002923static PyObject *
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002924dict_setdefault_impl(PyDictObject *self, PyObject *key,
2925 PyObject *default_value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002926/*[clinic end generated code: output=f8c1101ebf69e220 input=0f063756e815fd9d]*/
Benjamin Peterson00e98862013-03-07 22:16:29 -05002927{
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002928 PyObject *val;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002929
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002930 val = PyDict_SetDefault((PyObject *)self, key, default_value);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002931 Py_XINCREF(val);
2932 return val;
2933}
Guido van Rossum164452c2000-08-08 16:12:54 +00002934
2935static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002936dict_clear(PyDictObject *mp)
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 PyDict_Clear((PyObject *)mp);
2939 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002940}
2941
Guido van Rossumba6ab842000-12-12 22:02:18 +00002942static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002943dict_pop(PyDictObject *mp, PyObject *args)
Guido van Rossume027d982002-04-12 15:11:59 +00002944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 PyObject *key, *deflt = NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
2948 return NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06002949
Yury Selivanov684ef2c2016-10-28 19:01:21 -04002950 return _PyDict_Pop((PyObject*)mp, key, deflt);
Guido van Rossume027d982002-04-12 15:11:59 +00002951}
2952
2953static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002954dict_popitem(PyDictObject *mp)
Guido van Rossumba6ab842000-12-12 22:02:18 +00002955{
Victor Stinner742da042016-09-07 17:40:12 -07002956 Py_ssize_t i, j;
2957 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 PyObject *res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 /* Allocate the result tuple before checking the size. Believe it
2961 * or not, this allocation could trigger a garbage collection which
2962 * could empty the dict, so if we checked the size first and that
2963 * happened, the result would be an infinite loop (searching for an
2964 * entry that no longer exists). Note that the usual popitem()
2965 * idiom is "while d: k, v = d.popitem()". so needing to throw the
2966 * tuple away if the dict *is* empty isn't a significant
2967 * inefficiency -- possible, but unlikely in practice.
2968 */
2969 res = PyTuple_New(2);
2970 if (res == NULL)
2971 return NULL;
2972 if (mp->ma_used == 0) {
2973 Py_DECREF(res);
2974 PyErr_SetString(PyExc_KeyError,
2975 "popitem(): dictionary is empty");
2976 return NULL;
2977 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002978 /* Convert split table to combined table */
2979 if (mp->ma_keys->dk_lookup == lookdict_split) {
2980 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
2981 Py_DECREF(res);
2982 return NULL;
2983 }
2984 }
2985 ENSURE_ALLOWS_DELETIONS(mp);
Victor Stinner742da042016-09-07 17:40:12 -07002986
2987 /* Pop last item */
2988 ep0 = DK_ENTRIES(mp->ma_keys);
2989 i = mp->ma_keys->dk_nentries - 1;
2990 while (i >= 0 && ep0[i].me_value == NULL) {
2991 i--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 }
Victor Stinner742da042016-09-07 17:40:12 -07002993 assert(i >= 0);
2994
2995 ep = &ep0[i];
2996 j = lookdict_index(mp->ma_keys, ep->me_hash, i);
2997 assert(j >= 0);
2998 assert(dk_get_index(mp->ma_keys, j) == i);
2999 dk_set_index(mp->ma_keys, j, DKIX_DUMMY);
3000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 PyTuple_SET_ITEM(res, 0, ep->me_key);
3002 PyTuple_SET_ITEM(res, 1, ep->me_value);
Victor Stinner742da042016-09-07 17:40:12 -07003003 ep->me_key = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 ep->me_value = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07003005 /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
3006 mp->ma_keys->dk_nentries = i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07003008 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner611b0fa2016-09-14 15:02:01 +02003009 assert(_PyDict_CheckConsistency(mp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 return res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00003011}
3012
Jeremy Hylton8caad492000-06-23 14:18:11 +00003013static int
3014dict_traverse(PyObject *op, visitproc visit, void *arg)
3015{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003016 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson55f44522016-09-05 12:12:59 -07003017 PyDictKeysObject *keys = mp->ma_keys;
Serhiy Storchaka46825d22016-09-26 21:29:34 +03003018 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Victor Stinner742da042016-09-07 17:40:12 -07003019 Py_ssize_t i, n = keys->dk_nentries;
3020
Benjamin Peterson55f44522016-09-05 12:12:59 -07003021 if (keys->dk_lookup == lookdict) {
3022 for (i = 0; i < n; i++) {
3023 if (entries[i].me_value != NULL) {
3024 Py_VISIT(entries[i].me_value);
3025 Py_VISIT(entries[i].me_key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003026 }
3027 }
Victor Stinner742da042016-09-07 17:40:12 -07003028 }
3029 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003030 if (mp->ma_values != NULL) {
Benjamin Peterson55f44522016-09-05 12:12:59 -07003031 for (i = 0; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003032 Py_VISIT(mp->ma_values[i]);
3033 }
3034 }
3035 else {
Benjamin Peterson55f44522016-09-05 12:12:59 -07003036 for (i = 0; i < n; i++) {
3037 Py_VISIT(entries[i].me_value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003038 }
3039 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 }
3041 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00003042}
3043
3044static int
3045dict_tp_clear(PyObject *op)
3046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 PyDict_Clear(op);
3048 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00003049}
3050
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003051static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003052
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003053Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003054_PyDict_SizeOf(PyDictObject *mp)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003055{
Victor Stinner742da042016-09-07 17:40:12 -07003056 Py_ssize_t size, usable, res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003057
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003058 size = DK_SIZE(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07003059 usable = USABLE_FRACTION(size);
3060
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02003061 res = _PyObject_SIZE(Py_TYPE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003062 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07003063 res += usable * sizeof(PyObject*);
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003064 /* If the dictionary is split, the keys portion is accounted-for
3065 in the type object. */
3066 if (mp->ma_keys->dk_refcnt == 1)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003067 res += (sizeof(PyDictKeysObject)
3068 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
3069 + DK_IXSIZE(mp->ma_keys) * size
3070 + sizeof(PyDictKeyEntry) * usable);
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003071 return res;
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003072}
3073
3074Py_ssize_t
3075_PyDict_KeysSize(PyDictKeysObject *keys)
3076{
Victor Stinner98ee9d52016-09-08 09:33:56 -07003077 return (sizeof(PyDictKeysObject)
3078 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
3079 + DK_IXSIZE(keys) * DK_SIZE(keys)
3080 + USABLE_FRACTION(DK_SIZE(keys)) * sizeof(PyDictKeyEntry));
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003081}
3082
doko@ubuntu.com17210f52016-01-14 14:04:59 +01003083static PyObject *
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003084dict_sizeof(PyDictObject *mp)
3085{
3086 return PyLong_FromSsize_t(_PyDict_SizeOf(mp));
3087}
3088
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003089PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
3090
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003091PyDoc_STRVAR(sizeof__doc__,
3092"D.__sizeof__() -> size of D in memory, in bytes");
3093
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003094PyDoc_STRVAR(pop__doc__,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00003095"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00003096If key is not found, d is returned if given, otherwise KeyError is raised");
Guido van Rossume027d982002-04-12 15:11:59 +00003097
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003098PyDoc_STRVAR(popitem__doc__,
Tim Petersf7f88b12000-12-13 23:18:45 +00003099"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000031002-tuple; but raise KeyError if D is empty.");
Tim Petersf7f88b12000-12-13 23:18:45 +00003101
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003102PyDoc_STRVAR(update__doc__,
Brett Cannonf2754162013-05-11 14:46:48 -04003103"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n\
3104If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]\n\
3105If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n\
3106In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00003107
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003108PyDoc_STRVAR(clear__doc__,
3109"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00003110
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003111PyDoc_STRVAR(copy__doc__,
3112"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00003113
Guido van Rossumb90c8482007-02-10 01:11:45 +00003114/* Forward */
3115static PyObject *dictkeys_new(PyObject *);
3116static PyObject *dictitems_new(PyObject *);
3117static PyObject *dictvalues_new(PyObject *);
3118
Guido van Rossum45c85d12007-07-27 16:31:40 +00003119PyDoc_STRVAR(keys__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 "D.keys() -> a set-like object providing a view on D's keys");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003121PyDoc_STRVAR(items__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 "D.items() -> a set-like object providing a view on D's items");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003123PyDoc_STRVAR(values__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 "D.values() -> an object providing a view on D's values");
Guido van Rossumb90c8482007-02-10 01:11:45 +00003125
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003126static PyMethodDef mapp_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -07003127 DICT___CONTAINS___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
3129 getitem__doc__},
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003130 {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 sizeof__doc__},
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01003132 DICT_GET_METHODDEF
3133 DICT_SETDEFAULT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 {"pop", (PyCFunction)dict_pop, METH_VARARGS,
3135 pop__doc__},
3136 {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
3137 popitem__doc__},
3138 {"keys", (PyCFunction)dictkeys_new, METH_NOARGS,
3139 keys__doc__},
3140 {"items", (PyCFunction)dictitems_new, METH_NOARGS,
3141 items__doc__},
3142 {"values", (PyCFunction)dictvalues_new, METH_NOARGS,
3143 values__doc__},
3144 {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
3145 update__doc__},
Larry Hastings5c661892014-01-24 06:17:25 -08003146 DICT_FROMKEYS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
3148 clear__doc__},
3149 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
3150 copy__doc__},
3151 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003152};
3153
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00003154/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00003155int
3156PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003157{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003158 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07003159 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09003161 PyObject *value;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003164 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 hash = PyObject_Hash(key);
3166 if (hash == -1)
3167 return -1;
3168 }
INADA Naokiba609772016-12-07 20:41:42 +09003169 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07003170 if (ix == DKIX_ERROR)
3171 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09003172 return (ix != DKIX_EMPTY && value != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003173}
3174
Thomas Wouterscf297e42007-02-23 15:07:44 +00003175/* Internal version of PyDict_Contains used when the hash value is already known */
3176int
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003177_PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00003178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09003180 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -07003181 Py_ssize_t ix;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003182
INADA Naokiba609772016-12-07 20:41:42 +09003183 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07003184 if (ix == DKIX_ERROR)
3185 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09003186 return (ix != DKIX_EMPTY && value != NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00003187}
3188
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003189/* Hack to implement "key in dict" */
3190static PySequenceMethods dict_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 0, /* sq_length */
3192 0, /* sq_concat */
3193 0, /* sq_repeat */
3194 0, /* sq_item */
3195 0, /* sq_slice */
3196 0, /* sq_ass_item */
3197 0, /* sq_ass_slice */
3198 PyDict_Contains, /* sq_contains */
3199 0, /* sq_inplace_concat */
3200 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003201};
3202
Guido van Rossum09e563a2001-05-01 12:10:21 +00003203static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003204dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 PyObject *self;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003207 PyDictObject *d;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 assert(type != NULL && type->tp_alloc != NULL);
3210 self = type->tp_alloc(type, 0);
Victor Stinnera9f61a52013-07-16 22:17:26 +02003211 if (self == NULL)
3212 return NULL;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003213 d = (PyDictObject *)self;
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003214
Victor Stinnera9f61a52013-07-16 22:17:26 +02003215 /* The object has been implicitly tracked by tp_alloc */
3216 if (type == &PyDict_Type)
3217 _PyObject_GC_UNTRACK(d);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003218
3219 d->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07003220 d->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07003221 d->ma_keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003222 if (d->ma_keys == NULL) {
3223 Py_DECREF(self);
3224 return NULL;
3225 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02003226 assert(_PyDict_CheckConsistency(d));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 return self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003228}
3229
Tim Peters25786c02001-09-02 08:22:48 +00003230static int
3231dict_init(PyObject *self, PyObject *args, PyObject *kwds)
3232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00003234}
3235
Tim Peters6d6c1a32001-08-02 04:15:00 +00003236static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003237dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00003238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003240}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003241
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003242PyDoc_STRVAR(dictionary_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00003243"dict() -> new empty dictionary\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00003244"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003245" (key, value) pairs\n"
3246"dict(iterable) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00003247" d = {}\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003248" for k, v in iterable:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00003249" d[k] = v\n"
3250"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
3251" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00003252
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003253PyTypeObject PyDict_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3255 "dict",
3256 sizeof(PyDictObject),
3257 0,
3258 (destructor)dict_dealloc, /* tp_dealloc */
3259 0, /* tp_print */
3260 0, /* tp_getattr */
3261 0, /* tp_setattr */
3262 0, /* tp_reserved */
3263 (reprfunc)dict_repr, /* tp_repr */
3264 0, /* tp_as_number */
3265 &dict_as_sequence, /* tp_as_sequence */
3266 &dict_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003267 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 0, /* tp_call */
3269 0, /* tp_str */
3270 PyObject_GenericGetAttr, /* tp_getattro */
3271 0, /* tp_setattro */
3272 0, /* tp_as_buffer */
3273 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3274 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
3275 dictionary_doc, /* tp_doc */
3276 dict_traverse, /* tp_traverse */
3277 dict_tp_clear, /* tp_clear */
3278 dict_richcompare, /* tp_richcompare */
3279 0, /* tp_weaklistoffset */
3280 (getiterfunc)dict_iter, /* tp_iter */
3281 0, /* tp_iternext */
3282 mapp_methods, /* tp_methods */
3283 0, /* tp_members */
3284 0, /* tp_getset */
3285 0, /* tp_base */
3286 0, /* tp_dict */
3287 0, /* tp_descr_get */
3288 0, /* tp_descr_set */
3289 0, /* tp_dictoffset */
3290 dict_init, /* tp_init */
3291 PyType_GenericAlloc, /* tp_alloc */
3292 dict_new, /* tp_new */
3293 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003294};
3295
Victor Stinner3c1e4812012-03-26 22:10:51 +02003296PyObject *
3297_PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
3298{
3299 PyObject *kv;
3300 kv = _PyUnicode_FromId(key); /* borrowed */
Victor Stinner5b3b1002013-07-22 23:50:57 +02003301 if (kv == NULL) {
3302 PyErr_Clear();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003303 return NULL;
Victor Stinner5b3b1002013-07-22 23:50:57 +02003304 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003305 return PyDict_GetItem(dp, kv);
3306}
3307
Guido van Rossum3cca2451997-05-16 14:23:33 +00003308/* For backward compatibility with old dictionary interface */
3309
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003310PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003311PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 PyObject *kv, *rv;
3314 kv = PyUnicode_FromString(key);
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003315 if (kv == NULL) {
3316 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 return NULL;
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003318 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 rv = PyDict_GetItem(v, kv);
3320 Py_DECREF(kv);
3321 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003322}
3323
3324int
Victor Stinner3c1e4812012-03-26 22:10:51 +02003325_PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
3326{
3327 PyObject *kv;
3328 kv = _PyUnicode_FromId(key); /* borrowed */
3329 if (kv == NULL)
3330 return -1;
3331 return PyDict_SetItem(v, kv, item);
3332}
3333
3334int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003335PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 PyObject *kv;
3338 int err;
3339 kv = PyUnicode_FromString(key);
3340 if (kv == NULL)
3341 return -1;
3342 PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
3343 err = PyDict_SetItem(v, kv, item);
3344 Py_DECREF(kv);
3345 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003346}
3347
3348int
Victor Stinner5fd2e5a2013-11-06 18:58:22 +01003349_PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
3350{
3351 PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
3352 if (kv == NULL)
3353 return -1;
3354 return PyDict_DelItem(v, kv);
3355}
3356
3357int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003358PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 PyObject *kv;
3361 int err;
3362 kv = PyUnicode_FromString(key);
3363 if (kv == NULL)
3364 return -1;
3365 err = PyDict_DelItem(v, kv);
3366 Py_DECREF(kv);
3367 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003368}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003369
Raymond Hettinger019a1482004-03-18 02:41:19 +00003370/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003371
3372typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 PyObject_HEAD
3374 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
3375 Py_ssize_t di_used;
3376 Py_ssize_t di_pos;
3377 PyObject* di_result; /* reusable result tuple for iteritems */
3378 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003379} dictiterobject;
3380
3381static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003382dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 dictiterobject *di;
3385 di = PyObject_GC_New(dictiterobject, itertype);
3386 if (di == NULL)
3387 return NULL;
3388 Py_INCREF(dict);
3389 di->di_dict = dict;
3390 di->di_used = dict->ma_used;
3391 di->di_pos = 0;
3392 di->len = dict->ma_used;
3393 if (itertype == &PyDictIterItem_Type) {
3394 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
3395 if (di->di_result == NULL) {
3396 Py_DECREF(di);
3397 return NULL;
3398 }
3399 }
3400 else
3401 di->di_result = NULL;
3402 _PyObject_GC_TRACK(di);
3403 return (PyObject *)di;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003404}
3405
3406static void
3407dictiter_dealloc(dictiterobject *di)
3408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 Py_XDECREF(di->di_dict);
3410 Py_XDECREF(di->di_result);
3411 PyObject_GC_Del(di);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003412}
3413
3414static int
3415dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
3416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003417 Py_VISIT(di->di_dict);
3418 Py_VISIT(di->di_result);
3419 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003420}
3421
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003422static PyObject *
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003423dictiter_len(dictiterobject *di)
3424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 Py_ssize_t len = 0;
3426 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
3427 len = di->len;
3428 return PyLong_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003429}
3430
Guido van Rossumb90c8482007-02-10 01:11:45 +00003431PyDoc_STRVAR(length_hint_doc,
3432 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003433
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003434static PyObject *
3435dictiter_reduce(dictiterobject *di);
3436
3437PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3438
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003439static PyMethodDef dictiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS,
3441 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003442 {"__reduce__", (PyCFunction)dictiter_reduce, METH_NOARGS,
3443 reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003445};
3446
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003447static PyObject*
3448dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00003449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 PyObject *key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003451 Py_ssize_t i;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003452 PyDictKeysObject *k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 PyDictObject *d = di->di_dict;
Guido van Rossum213c7a62001-04-23 14:08:49 +00003454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 if (d == NULL)
3456 return NULL;
3457 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00003458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003459 if (di->di_used != d->ma_used) {
3460 PyErr_SetString(PyExc_RuntimeError,
3461 "dictionary changed size during iteration");
3462 di->di_used = -1; /* Make this state sticky */
3463 return NULL;
3464 }
Guido van Rossum2147df72002-07-16 20:30:22 +00003465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 i = di->di_pos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003467 k = d->ma_keys;
INADA Naokica2d8be2016-11-04 16:59:10 +09003468 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003469 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003470 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003471 goto fail;
3472 key = DK_ENTRIES(k)[i].me_key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003473 assert(d->ma_values[i] != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003474 }
3475 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003476 Py_ssize_t n = k->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003477 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
3478 while (i < n && entry_ptr->me_value == NULL) {
3479 entry_ptr++;
3480 i++;
3481 }
3482 if (i >= n)
3483 goto fail;
3484 key = entry_ptr->me_key;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003485 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 di->di_pos = i+1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 di->len--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 Py_INCREF(key);
3489 return key;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003490
3491fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003493 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003495}
3496
Raymond Hettinger019a1482004-03-18 02:41:19 +00003497PyTypeObject PyDictIterKey_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3499 "dict_keyiterator", /* tp_name */
3500 sizeof(dictiterobject), /* tp_basicsize */
3501 0, /* tp_itemsize */
3502 /* methods */
3503 (destructor)dictiter_dealloc, /* tp_dealloc */
3504 0, /* tp_print */
3505 0, /* tp_getattr */
3506 0, /* tp_setattr */
3507 0, /* tp_reserved */
3508 0, /* tp_repr */
3509 0, /* tp_as_number */
3510 0, /* tp_as_sequence */
3511 0, /* tp_as_mapping */
3512 0, /* tp_hash */
3513 0, /* tp_call */
3514 0, /* tp_str */
3515 PyObject_GenericGetAttr, /* tp_getattro */
3516 0, /* tp_setattro */
3517 0, /* tp_as_buffer */
3518 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3519 0, /* tp_doc */
3520 (traverseproc)dictiter_traverse, /* tp_traverse */
3521 0, /* tp_clear */
3522 0, /* tp_richcompare */
3523 0, /* tp_weaklistoffset */
3524 PyObject_SelfIter, /* tp_iter */
3525 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
3526 dictiter_methods, /* tp_methods */
3527 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003528};
3529
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003530static PyObject *
3531dictiter_iternextvalue(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003533 PyObject *value;
INADA Naokica2d8be2016-11-04 16:59:10 +09003534 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 if (d == NULL)
3538 return NULL;
3539 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 if (di->di_used != d->ma_used) {
3542 PyErr_SetString(PyExc_RuntimeError,
3543 "dictionary changed size during iteration");
3544 di->di_used = -1; /* Make this state sticky */
3545 return NULL;
3546 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 i = di->di_pos;
INADA Naokica2d8be2016-11-04 16:59:10 +09003549 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003550 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003551 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003552 goto fail;
INADA Naokica2d8be2016-11-04 16:59:10 +09003553 value = d->ma_values[i];
3554 assert(value != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003555 }
3556 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003557 Py_ssize_t n = d->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003558 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3559 while (i < n && entry_ptr->me_value == NULL) {
3560 entry_ptr++;
3561 i++;
3562 }
3563 if (i >= n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 goto fail;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003565 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 }
3567 di->di_pos = i+1;
3568 di->len--;
3569 Py_INCREF(value);
3570 return value;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003571
3572fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003574 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003575 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003576}
3577
3578PyTypeObject PyDictIterValue_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3580 "dict_valueiterator", /* tp_name */
3581 sizeof(dictiterobject), /* tp_basicsize */
3582 0, /* tp_itemsize */
3583 /* methods */
3584 (destructor)dictiter_dealloc, /* tp_dealloc */
3585 0, /* tp_print */
3586 0, /* tp_getattr */
3587 0, /* tp_setattr */
3588 0, /* tp_reserved */
3589 0, /* tp_repr */
3590 0, /* tp_as_number */
3591 0, /* tp_as_sequence */
3592 0, /* tp_as_mapping */
3593 0, /* tp_hash */
3594 0, /* tp_call */
3595 0, /* tp_str */
3596 PyObject_GenericGetAttr, /* tp_getattro */
3597 0, /* tp_setattro */
3598 0, /* tp_as_buffer */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003599 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 0, /* tp_doc */
3601 (traverseproc)dictiter_traverse, /* tp_traverse */
3602 0, /* tp_clear */
3603 0, /* tp_richcompare */
3604 0, /* tp_weaklistoffset */
3605 PyObject_SelfIter, /* tp_iter */
3606 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
3607 dictiter_methods, /* tp_methods */
3608 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003609};
3610
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003611static PyObject *
3612dictiter_iternextitem(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 PyObject *key, *value, *result = di->di_result;
INADA Naokica2d8be2016-11-04 16:59:10 +09003615 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 if (d == NULL)
3619 return NULL;
3620 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 if (di->di_used != d->ma_used) {
3623 PyErr_SetString(PyExc_RuntimeError,
3624 "dictionary changed size during iteration");
3625 di->di_used = -1; /* Make this state sticky */
3626 return NULL;
3627 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003629 i = di->di_pos;
INADA Naokica2d8be2016-11-04 16:59:10 +09003630 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003631 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003632 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003633 goto fail;
3634 key = DK_ENTRIES(d->ma_keys)[i].me_key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003635 value = d->ma_values[i];
3636 assert(value != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003637 }
3638 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003639 Py_ssize_t n = d->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003640 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3641 while (i < n && entry_ptr->me_value == NULL) {
3642 entry_ptr++;
3643 i++;
3644 }
3645 if (i >= n)
3646 goto fail;
3647 key = entry_ptr->me_key;
3648 value = entry_ptr->me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003649 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 di->di_pos = i+1;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003651 di->len--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 if (result->ob_refcnt == 1) {
3653 Py_INCREF(result);
3654 Py_DECREF(PyTuple_GET_ITEM(result, 0));
3655 Py_DECREF(PyTuple_GET_ITEM(result, 1));
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003656 }
3657 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 result = PyTuple_New(2);
3659 if (result == NULL)
3660 return NULL;
3661 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 Py_INCREF(key);
3663 Py_INCREF(value);
Eric Snow96c6af92015-05-29 22:21:39 -06003664 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3665 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003667
3668fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003670 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003672}
3673
3674PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3676 "dict_itemiterator", /* tp_name */
3677 sizeof(dictiterobject), /* tp_basicsize */
3678 0, /* tp_itemsize */
3679 /* methods */
3680 (destructor)dictiter_dealloc, /* tp_dealloc */
3681 0, /* tp_print */
3682 0, /* tp_getattr */
3683 0, /* tp_setattr */
3684 0, /* tp_reserved */
3685 0, /* tp_repr */
3686 0, /* tp_as_number */
3687 0, /* tp_as_sequence */
3688 0, /* tp_as_mapping */
3689 0, /* tp_hash */
3690 0, /* tp_call */
3691 0, /* tp_str */
3692 PyObject_GenericGetAttr, /* tp_getattro */
3693 0, /* tp_setattro */
3694 0, /* tp_as_buffer */
3695 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3696 0, /* tp_doc */
3697 (traverseproc)dictiter_traverse, /* tp_traverse */
3698 0, /* tp_clear */
3699 0, /* tp_richcompare */
3700 0, /* tp_weaklistoffset */
3701 PyObject_SelfIter, /* tp_iter */
3702 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
3703 dictiter_methods, /* tp_methods */
3704 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003705};
Guido van Rossumb90c8482007-02-10 01:11:45 +00003706
3707
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003708static PyObject *
3709dictiter_reduce(dictiterobject *di)
3710{
3711 PyObject *list;
3712 dictiterobject tmp;
3713
3714 list = PyList_New(0);
3715 if (!list)
3716 return NULL;
3717
3718 /* copy the itertor state */
3719 tmp = *di;
3720 Py_XINCREF(tmp.di_dict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003721
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003722 /* iterate the temporary into a list */
3723 for(;;) {
3724 PyObject *element = 0;
3725 if (Py_TYPE(di) == &PyDictIterItem_Type)
3726 element = dictiter_iternextitem(&tmp);
3727 else if (Py_TYPE(di) == &PyDictIterKey_Type)
3728 element = dictiter_iternextkey(&tmp);
3729 else if (Py_TYPE(di) == &PyDictIterValue_Type)
3730 element = dictiter_iternextvalue(&tmp);
3731 else
3732 assert(0);
3733 if (element) {
3734 if (PyList_Append(list, element)) {
3735 Py_DECREF(element);
3736 Py_DECREF(list);
3737 Py_XDECREF(tmp.di_dict);
3738 return NULL;
3739 }
3740 Py_DECREF(element);
3741 } else
3742 break;
3743 }
3744 Py_XDECREF(tmp.di_dict);
3745 /* check for error */
3746 if (tmp.di_dict != NULL) {
3747 /* we have an error */
3748 Py_DECREF(list);
3749 return NULL;
3750 }
Antoine Pitroua7013882012-04-05 00:04:20 +02003751 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003752}
3753
Guido van Rossum3ac67412007-02-10 18:55:06 +00003754/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003755/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00003756/***********************************************/
3757
Guido van Rossumb90c8482007-02-10 01:11:45 +00003758/* The instance lay-out is the same for all three; but the type differs. */
3759
Guido van Rossumb90c8482007-02-10 01:11:45 +00003760static void
Eric Snow96c6af92015-05-29 22:21:39 -06003761dictview_dealloc(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 Py_XDECREF(dv->dv_dict);
3764 PyObject_GC_Del(dv);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003765}
3766
3767static int
Eric Snow96c6af92015-05-29 22:21:39 -06003768dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003770 Py_VISIT(dv->dv_dict);
3771 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003772}
3773
Guido van Rossum83825ac2007-02-10 04:54:19 +00003774static Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003775dictview_len(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 Py_ssize_t len = 0;
3778 if (dv->dv_dict != NULL)
3779 len = dv->dv_dict->ma_used;
3780 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003781}
3782
Eric Snow96c6af92015-05-29 22:21:39 -06003783PyObject *
3784_PyDictView_New(PyObject *dict, PyTypeObject *type)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003785{
Eric Snow96c6af92015-05-29 22:21:39 -06003786 _PyDictViewObject *dv;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003787 if (dict == NULL) {
3788 PyErr_BadInternalCall();
3789 return NULL;
3790 }
3791 if (!PyDict_Check(dict)) {
3792 /* XXX Get rid of this restriction later */
3793 PyErr_Format(PyExc_TypeError,
3794 "%s() requires a dict argument, not '%s'",
3795 type->tp_name, dict->ob_type->tp_name);
3796 return NULL;
3797 }
Eric Snow96c6af92015-05-29 22:21:39 -06003798 dv = PyObject_GC_New(_PyDictViewObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 if (dv == NULL)
3800 return NULL;
3801 Py_INCREF(dict);
3802 dv->dv_dict = (PyDictObject *)dict;
3803 _PyObject_GC_TRACK(dv);
3804 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003805}
3806
Neal Norwitze36f2ba2007-02-26 23:12:28 +00003807/* TODO(guido): The views objects are not complete:
3808
3809 * support more set operations
3810 * support arbitrary mappings?
3811 - either these should be static or exported in dictobject.h
3812 - if public then they should probably be in builtins
3813*/
3814
Guido van Rossumaac530c2007-08-24 22:33:45 +00003815/* Return 1 if self is a subset of other, iterating over self;
3816 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00003817static int
3818all_contained_in(PyObject *self, PyObject *other)
3819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 PyObject *iter = PyObject_GetIter(self);
3821 int ok = 1;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 if (iter == NULL)
3824 return -1;
3825 for (;;) {
3826 PyObject *next = PyIter_Next(iter);
3827 if (next == NULL) {
3828 if (PyErr_Occurred())
3829 ok = -1;
3830 break;
3831 }
3832 ok = PySequence_Contains(other, next);
3833 Py_DECREF(next);
3834 if (ok <= 0)
3835 break;
3836 }
3837 Py_DECREF(iter);
3838 return ok;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003839}
3840
3841static PyObject *
3842dictview_richcompare(PyObject *self, PyObject *other, int op)
3843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 Py_ssize_t len_self, len_other;
3845 int ok;
3846 PyObject *result;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 assert(self != NULL);
3849 assert(PyDictViewSet_Check(self));
3850 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00003851
Brian Curtindfc80e32011-08-10 20:28:54 -05003852 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
3853 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 len_self = PyObject_Size(self);
3856 if (len_self < 0)
3857 return NULL;
3858 len_other = PyObject_Size(other);
3859 if (len_other < 0)
3860 return NULL;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003862 ok = 0;
3863 switch(op) {
Guido van Rossumaac530c2007-08-24 22:33:45 +00003864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 case Py_NE:
3866 case Py_EQ:
3867 if (len_self == len_other)
3868 ok = all_contained_in(self, other);
3869 if (op == Py_NE && ok >= 0)
3870 ok = !ok;
3871 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 case Py_LT:
3874 if (len_self < len_other)
3875 ok = all_contained_in(self, other);
3876 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 case Py_LE:
3879 if (len_self <= len_other)
3880 ok = all_contained_in(self, other);
3881 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 case Py_GT:
3884 if (len_self > len_other)
3885 ok = all_contained_in(other, self);
3886 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 case Py_GE:
3889 if (len_self >= len_other)
3890 ok = all_contained_in(other, self);
3891 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 }
3894 if (ok < 0)
3895 return NULL;
3896 result = ok ? Py_True : Py_False;
3897 Py_INCREF(result);
3898 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003899}
3900
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003901static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003902dictview_repr(_PyDictViewObject *dv)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 PyObject *seq;
3905 PyObject *result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 seq = PySequence_List((PyObject *)dv);
3908 if (seq == NULL)
3909 return NULL;
3910
3911 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
3912 Py_DECREF(seq);
3913 return result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003914}
3915
Guido van Rossum3ac67412007-02-10 18:55:06 +00003916/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003917
3918static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003919dictkeys_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003921 if (dv->dv_dict == NULL) {
3922 Py_RETURN_NONE;
3923 }
3924 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003925}
3926
3927static int
Eric Snow96c6af92015-05-29 22:21:39 -06003928dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00003929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003930 if (dv->dv_dict == NULL)
3931 return 0;
3932 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003933}
3934
Guido van Rossum83825ac2007-02-10 04:54:19 +00003935static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 (lenfunc)dictview_len, /* sq_length */
3937 0, /* sq_concat */
3938 0, /* sq_repeat */
3939 0, /* sq_item */
3940 0, /* sq_slice */
3941 0, /* sq_ass_item */
3942 0, /* sq_ass_slice */
3943 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003944};
3945
Guido van Rossum523259b2007-08-24 23:41:22 +00003946static PyObject*
3947dictviews_sub(PyObject* self, PyObject *other)
3948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 PyObject *result = PySet_New(self);
3950 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003951 _Py_IDENTIFIER(difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003953 if (result == NULL)
3954 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003955
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003956 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003957 if (tmp == NULL) {
3958 Py_DECREF(result);
3959 return NULL;
3960 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 Py_DECREF(tmp);
3963 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003964}
3965
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003966PyObject*
3967_PyDictView_Intersect(PyObject* self, PyObject *other)
Guido van Rossum523259b2007-08-24 23:41:22 +00003968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 PyObject *result = PySet_New(self);
3970 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003971 _Py_IDENTIFIER(intersection_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 if (result == NULL)
3974 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003975
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003976 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_intersection_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003977 if (tmp == NULL) {
3978 Py_DECREF(result);
3979 return NULL;
3980 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 Py_DECREF(tmp);
3983 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003984}
3985
3986static PyObject*
3987dictviews_or(PyObject* self, PyObject *other)
3988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003989 PyObject *result = PySet_New(self);
3990 PyObject *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02003991 _Py_IDENTIFIER(update);
Victor Stinnerd1a9cc22011-10-13 22:51:17 +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_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
4006static PyObject*
4007dictviews_xor(PyObject* self, PyObject *other)
4008{
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(symmetric_difference_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_symmetric_difference_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 PyNumberMethods dictviews_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004027 0, /*nb_add*/
4028 (binaryfunc)dictviews_sub, /*nb_subtract*/
4029 0, /*nb_multiply*/
4030 0, /*nb_remainder*/
4031 0, /*nb_divmod*/
4032 0, /*nb_power*/
4033 0, /*nb_negative*/
4034 0, /*nb_positive*/
4035 0, /*nb_absolute*/
4036 0, /*nb_bool*/
4037 0, /*nb_invert*/
4038 0, /*nb_lshift*/
4039 0, /*nb_rshift*/
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004040 (binaryfunc)_PyDictView_Intersect, /*nb_and*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 (binaryfunc)dictviews_xor, /*nb_xor*/
4042 (binaryfunc)dictviews_or, /*nb_or*/
Guido van Rossum523259b2007-08-24 23:41:22 +00004043};
4044
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004045static PyObject*
4046dictviews_isdisjoint(PyObject *self, PyObject *other)
4047{
4048 PyObject *it;
4049 PyObject *item = NULL;
4050
4051 if (self == other) {
Eric Snow96c6af92015-05-29 22:21:39 -06004052 if (dictview_len((_PyDictViewObject *)self) == 0)
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004053 Py_RETURN_TRUE;
4054 else
4055 Py_RETURN_FALSE;
4056 }
4057
4058 /* Iterate over the shorter object (only if other is a set,
4059 * because PySequence_Contains may be expensive otherwise): */
4060 if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
Eric Snow96c6af92015-05-29 22:21:39 -06004061 Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004062 Py_ssize_t len_other = PyObject_Size(other);
4063 if (len_other == -1)
4064 return NULL;
4065
4066 if ((len_other > len_self)) {
4067 PyObject *tmp = other;
4068 other = self;
4069 self = tmp;
4070 }
4071 }
4072
4073 it = PyObject_GetIter(other);
4074 if (it == NULL)
4075 return NULL;
4076
4077 while ((item = PyIter_Next(it)) != NULL) {
4078 int contains = PySequence_Contains(self, item);
4079 Py_DECREF(item);
4080 if (contains == -1) {
4081 Py_DECREF(it);
4082 return NULL;
4083 }
4084
4085 if (contains) {
4086 Py_DECREF(it);
4087 Py_RETURN_FALSE;
4088 }
4089 }
4090 Py_DECREF(it);
4091 if (PyErr_Occurred())
4092 return NULL; /* PyIter_Next raised an exception. */
4093 Py_RETURN_TRUE;
4094}
4095
4096PyDoc_STRVAR(isdisjoint_doc,
4097"Return True if the view and the given iterable have a null intersection.");
4098
Guido van Rossumb90c8482007-02-10 01:11:45 +00004099static PyMethodDef dictkeys_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004100 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4101 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004103};
4104
4105PyTypeObject PyDictKeys_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4107 "dict_keys", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004108 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 0, /* tp_itemsize */
4110 /* methods */
4111 (destructor)dictview_dealloc, /* tp_dealloc */
4112 0, /* tp_print */
4113 0, /* tp_getattr */
4114 0, /* tp_setattr */
4115 0, /* tp_reserved */
4116 (reprfunc)dictview_repr, /* tp_repr */
4117 &dictviews_as_number, /* tp_as_number */
4118 &dictkeys_as_sequence, /* tp_as_sequence */
4119 0, /* tp_as_mapping */
4120 0, /* tp_hash */
4121 0, /* tp_call */
4122 0, /* tp_str */
4123 PyObject_GenericGetAttr, /* tp_getattro */
4124 0, /* tp_setattro */
4125 0, /* tp_as_buffer */
4126 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4127 0, /* tp_doc */
4128 (traverseproc)dictview_traverse, /* tp_traverse */
4129 0, /* tp_clear */
4130 dictview_richcompare, /* tp_richcompare */
4131 0, /* tp_weaklistoffset */
4132 (getiterfunc)dictkeys_iter, /* tp_iter */
4133 0, /* tp_iternext */
4134 dictkeys_methods, /* tp_methods */
4135 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004136};
4137
4138static PyObject *
4139dictkeys_new(PyObject *dict)
4140{
Eric Snow96c6af92015-05-29 22:21:39 -06004141 return _PyDictView_New(dict, &PyDictKeys_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004142}
4143
Guido van Rossum3ac67412007-02-10 18:55:06 +00004144/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004145
4146static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004147dictitems_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 if (dv->dv_dict == NULL) {
4150 Py_RETURN_NONE;
4151 }
4152 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00004153}
4154
4155static int
Eric Snow96c6af92015-05-29 22:21:39 -06004156dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00004157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004158 PyObject *key, *value, *found;
4159 if (dv->dv_dict == NULL)
4160 return 0;
4161 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
4162 return 0;
4163 key = PyTuple_GET_ITEM(obj, 0);
4164 value = PyTuple_GET_ITEM(obj, 1);
Raymond Hettinger6692f012016-09-18 21:46:08 -07004165 found = PyDict_GetItemWithError((PyObject *)dv->dv_dict, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 if (found == NULL) {
4167 if (PyErr_Occurred())
4168 return -1;
4169 return 0;
4170 }
4171 return PyObject_RichCompareBool(value, found, Py_EQ);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004172}
4173
Guido van Rossum83825ac2007-02-10 04:54:19 +00004174static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004175 (lenfunc)dictview_len, /* sq_length */
4176 0, /* sq_concat */
4177 0, /* sq_repeat */
4178 0, /* sq_item */
4179 0, /* sq_slice */
4180 0, /* sq_ass_item */
4181 0, /* sq_ass_slice */
4182 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004183};
4184
Guido van Rossumb90c8482007-02-10 01:11:45 +00004185static PyMethodDef dictitems_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004186 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4187 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004189};
4190
4191PyTypeObject PyDictItems_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004192 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4193 "dict_items", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004194 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004195 0, /* tp_itemsize */
4196 /* methods */
4197 (destructor)dictview_dealloc, /* tp_dealloc */
4198 0, /* tp_print */
4199 0, /* tp_getattr */
4200 0, /* tp_setattr */
4201 0, /* tp_reserved */
4202 (reprfunc)dictview_repr, /* tp_repr */
4203 &dictviews_as_number, /* tp_as_number */
4204 &dictitems_as_sequence, /* tp_as_sequence */
4205 0, /* tp_as_mapping */
4206 0, /* tp_hash */
4207 0, /* tp_call */
4208 0, /* tp_str */
4209 PyObject_GenericGetAttr, /* tp_getattro */
4210 0, /* tp_setattro */
4211 0, /* tp_as_buffer */
4212 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4213 0, /* tp_doc */
4214 (traverseproc)dictview_traverse, /* tp_traverse */
4215 0, /* tp_clear */
4216 dictview_richcompare, /* tp_richcompare */
4217 0, /* tp_weaklistoffset */
4218 (getiterfunc)dictitems_iter, /* tp_iter */
4219 0, /* tp_iternext */
4220 dictitems_methods, /* tp_methods */
4221 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004222};
4223
4224static PyObject *
4225dictitems_new(PyObject *dict)
4226{
Eric Snow96c6af92015-05-29 22:21:39 -06004227 return _PyDictView_New(dict, &PyDictItems_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004228}
4229
Guido van Rossum3ac67412007-02-10 18:55:06 +00004230/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004231
4232static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004233dictvalues_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004235 if (dv->dv_dict == NULL) {
4236 Py_RETURN_NONE;
4237 }
4238 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004239}
4240
Guido van Rossum83825ac2007-02-10 04:54:19 +00004241static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004242 (lenfunc)dictview_len, /* sq_length */
4243 0, /* sq_concat */
4244 0, /* sq_repeat */
4245 0, /* sq_item */
4246 0, /* sq_slice */
4247 0, /* sq_ass_item */
4248 0, /* sq_ass_slice */
4249 (objobjproc)0, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004250};
4251
Guido van Rossumb90c8482007-02-10 01:11:45 +00004252static PyMethodDef dictvalues_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004253 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004254};
4255
4256PyTypeObject PyDictValues_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4258 "dict_values", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004259 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 0, /* tp_itemsize */
4261 /* methods */
4262 (destructor)dictview_dealloc, /* tp_dealloc */
4263 0, /* tp_print */
4264 0, /* tp_getattr */
4265 0, /* tp_setattr */
4266 0, /* tp_reserved */
4267 (reprfunc)dictview_repr, /* tp_repr */
4268 0, /* tp_as_number */
4269 &dictvalues_as_sequence, /* tp_as_sequence */
4270 0, /* tp_as_mapping */
4271 0, /* tp_hash */
4272 0, /* tp_call */
4273 0, /* tp_str */
4274 PyObject_GenericGetAttr, /* tp_getattro */
4275 0, /* tp_setattro */
4276 0, /* tp_as_buffer */
4277 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4278 0, /* tp_doc */
4279 (traverseproc)dictview_traverse, /* tp_traverse */
4280 0, /* tp_clear */
4281 0, /* tp_richcompare */
4282 0, /* tp_weaklistoffset */
4283 (getiterfunc)dictvalues_iter, /* tp_iter */
4284 0, /* tp_iternext */
4285 dictvalues_methods, /* tp_methods */
4286 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004287};
4288
4289static PyObject *
4290dictvalues_new(PyObject *dict)
4291{
Eric Snow96c6af92015-05-29 22:21:39 -06004292 return _PyDictView_New(dict, &PyDictValues_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004293}
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004294
4295/* Returns NULL if cannot allocate a new PyDictKeysObject,
4296 but does not set an error */
4297PyDictKeysObject *
4298_PyDict_NewKeysForClass(void)
4299{
Victor Stinner742da042016-09-07 17:40:12 -07004300 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004301 if (keys == NULL)
4302 PyErr_Clear();
4303 else
4304 keys->dk_lookup = lookdict_split;
4305 return keys;
4306}
4307
4308#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
4309
4310PyObject *
4311PyObject_GenericGetDict(PyObject *obj, void *context)
4312{
4313 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
4314 if (dictptr == NULL) {
4315 PyErr_SetString(PyExc_AttributeError,
4316 "This object has no __dict__");
4317 return NULL;
4318 }
4319 dict = *dictptr;
4320 if (dict == NULL) {
4321 PyTypeObject *tp = Py_TYPE(obj);
4322 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
4323 DK_INCREF(CACHED_KEYS(tp));
4324 *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
4325 }
4326 else {
4327 *dictptr = dict = PyDict_New();
4328 }
4329 }
4330 Py_XINCREF(dict);
4331 return dict;
4332}
4333
4334int
4335_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
Victor Stinner742da042016-09-07 17:40:12 -07004336 PyObject *key, PyObject *value)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004337{
4338 PyObject *dict;
4339 int res;
4340 PyDictKeysObject *cached;
4341
4342 assert(dictptr != NULL);
4343 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
4344 assert(dictptr != NULL);
4345 dict = *dictptr;
4346 if (dict == NULL) {
4347 DK_INCREF(cached);
4348 dict = new_dict_with_shared_keys(cached);
4349 if (dict == NULL)
4350 return -1;
4351 *dictptr = dict;
4352 }
4353 if (value == NULL) {
4354 res = PyDict_DelItem(dict, key);
4355 if (cached != ((PyDictObject *)dict)->ma_keys) {
4356 CACHED_KEYS(tp) = NULL;
4357 DK_DECREF(cached);
4358 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01004359 }
4360 else {
4361 int was_shared = cached == ((PyDictObject *)dict)->ma_keys;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004362 res = PyDict_SetItem(dict, key, value);
Victor Stinner3d3f2642016-12-15 17:21:23 +01004363 if (was_shared && cached != ((PyDictObject *)dict)->ma_keys) {
4364 /* PyDict_SetItem() may call dictresize and convert split table
4365 * into combined table. In such case, convert it to split
4366 * table again and update type's shared key only when this is
4367 * the only dict sharing key with the type.
4368 *
4369 * This is to allow using shared key in class like this:
4370 *
4371 * class C:
4372 * def __init__(self):
4373 * # one dict resize happens
4374 * self.a, self.b, self.c = 1, 2, 3
4375 * self.d, self.e, self.f = 4, 5, 6
4376 * a = C()
4377 */
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004378 if (cached->dk_refcnt == 1) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004379 CACHED_KEYS(tp) = make_keys_shared(dict);
Victor Stinner742da042016-09-07 17:40:12 -07004380 }
4381 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004382 CACHED_KEYS(tp) = NULL;
4383 }
4384 DK_DECREF(cached);
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004385 if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
4386 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004387 }
4388 }
4389 } else {
4390 dict = *dictptr;
4391 if (dict == NULL) {
4392 dict = PyDict_New();
4393 if (dict == NULL)
4394 return -1;
4395 *dictptr = dict;
4396 }
4397 if (value == NULL) {
4398 res = PyDict_DelItem(dict, key);
4399 } else {
4400 res = PyDict_SetItem(dict, key, value);
4401 }
4402 }
4403 return res;
4404}
4405
4406void
4407_PyDictKeys_DecRef(PyDictKeysObject *keys)
4408{
4409 DK_DECREF(keys);
4410}