blob: 254311869b6f4be25af92f2a46b0ac577851e57d [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
T. Woutersa00c3fd2017-03-31 09:14:41 -0700440#ifndef NDEBUG
Victor Stinner611b0fa2016-09-14 15:02:01 +0200441static 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
INADA Naoki1b8df102017-02-20 22:48:10 +0900680never raise an exception; that function can never return DKIX_ERROR when key
681is string. Otherwise, it falls back to lookdict().
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400682lookdict_unicode_nodummy is further specialized for string keys that cannot be
683the <dummy> value.
Victor Stinner742da042016-09-07 17:40:12 -0700684For both, when the key isn't found a DKIX_EMPTY is returned. hashpos returns
685where the key index should be inserted.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000686*/
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100687static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400688lookdict(PyDictObject *mp, PyObject *key,
INADA Naokiba609772016-12-07 20:41:42 +0900689 Py_hash_t hash, PyObject **value_addr, Py_ssize_t *hashpos)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000690{
INADA Naoki267941c2016-10-06 15:19:07 +0900691 size_t i, mask;
Victor Stinner742da042016-09-07 17:40:12 -0700692 Py_ssize_t ix, freeslot;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200693 int cmp;
Victor Stinner742da042016-09-07 17:40:12 -0700694 PyDictKeysObject *dk;
695 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 PyObject *startkey;
Tim Peterseb28ef22001-06-02 05:27:19 +0000697
Antoine Pitrou9a234902012-05-13 20:48:01 +0200698top:
Victor Stinner742da042016-09-07 17:40:12 -0700699 dk = mp->ma_keys;
700 mask = DK_MASK(dk);
701 ep0 = DK_ENTRIES(dk);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700703
704 ix = dk_get_index(dk, i);
705 if (ix == DKIX_EMPTY) {
706 if (hashpos != NULL)
707 *hashpos = i;
708 *value_addr = NULL;
709 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400710 }
Victor Stinner742da042016-09-07 17:40:12 -0700711 if (ix == DKIX_DUMMY) {
712 freeslot = i;
713 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 else {
Victor Stinner742da042016-09-07 17:40:12 -0700715 ep = &ep0[ix];
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300716 assert(ep->me_key != NULL);
Victor Stinner742da042016-09-07 17:40:12 -0700717 if (ep->me_key == key) {
INADA Naokiba609772016-12-07 20:41:42 +0900718 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700719 if (hashpos != NULL)
720 *hashpos = i;
721 return ix;
722 }
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300723 if (ep->me_hash == hash) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 startkey = ep->me_key;
725 Py_INCREF(startkey);
726 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
727 Py_DECREF(startkey);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +0200728 if (cmp < 0) {
729 *value_addr = NULL;
Victor Stinner742da042016-09-07 17:40:12 -0700730 return DKIX_ERROR;
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +0200731 }
Victor Stinner742da042016-09-07 17:40:12 -0700732 if (dk == mp->ma_keys && ep->me_key == startkey) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400733 if (cmp > 0) {
INADA Naokiba609772016-12-07 20:41:42 +0900734 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700735 if (hashpos != NULL)
736 *hashpos = i;
737 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400738 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 }
740 else {
Antoine Pitrou9a234902012-05-13 20:48:01 +0200741 /* The dict was mutated, restart */
742 goto top;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 }
744 }
Victor Stinner742da042016-09-07 17:40:12 -0700745 freeslot = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 }
Tim Peters15d49292001-05-27 07:39:22 +0000747
INADA Naoki267941c2016-10-06 15:19:07 +0900748 for (size_t perturb = hash;;) {
749 perturb >>= PERTURB_SHIFT;
Victor Stinner742da042016-09-07 17:40:12 -0700750 i = ((i << 2) + i + perturb + 1) & mask;
751 ix = dk_get_index(dk, i);
752 if (ix == DKIX_EMPTY) {
753 if (hashpos != NULL) {
754 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400755 }
Victor Stinner742da042016-09-07 17:40:12 -0700756 *value_addr = NULL;
757 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400758 }
Victor Stinner742da042016-09-07 17:40:12 -0700759 if (ix == DKIX_DUMMY) {
760 if (freeslot == -1)
761 freeslot = i;
762 continue;
763 }
764 ep = &ep0[ix];
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300765 assert(ep->me_key != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400766 if (ep->me_key == key) {
Victor Stinner742da042016-09-07 17:40:12 -0700767 if (hashpos != NULL) {
768 *hashpos = i;
769 }
INADA Naokiba609772016-12-07 20:41:42 +0900770 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700771 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400772 }
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300773 if (ep->me_hash == hash) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 startkey = ep->me_key;
775 Py_INCREF(startkey);
776 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
777 Py_DECREF(startkey);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400778 if (cmp < 0) {
779 *value_addr = NULL;
Victor Stinner742da042016-09-07 17:40:12 -0700780 return DKIX_ERROR;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400781 }
Victor Stinner742da042016-09-07 17:40:12 -0700782 if (dk == mp->ma_keys && ep->me_key == startkey) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400783 if (cmp > 0) {
Victor Stinner742da042016-09-07 17:40:12 -0700784 if (hashpos != NULL) {
785 *hashpos = i;
786 }
INADA Naokiba609772016-12-07 20:41:42 +0900787 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700788 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400789 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 }
791 else {
Antoine Pitrou9a234902012-05-13 20:48:01 +0200792 /* The dict was mutated, restart */
793 goto top;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 }
795 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 }
797 assert(0); /* NOT REACHED */
798 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000799}
800
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400801/* Specialized version for string-only keys */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100802static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400803lookdict_unicode(PyDictObject *mp, PyObject *key,
INADA Naokiba609772016-12-07 20:41:42 +0900804 Py_hash_t hash, PyObject **value_addr, Py_ssize_t *hashpos)
Fred Drake1bff34a2000-08-31 19:31:38 +0000805{
INADA Naoki267941c2016-10-06 15:19:07 +0900806 size_t i;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200807 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700808 Py_ssize_t ix, freeslot;
809 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Fred Drake1bff34a2000-08-31 19:31:38 +0000810
Victor Stinner742da042016-09-07 17:40:12 -0700811 assert(mp->ma_values == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 /* Make sure this function doesn't have to handle non-unicode keys,
813 including subclasses of str; e.g., one reason to subclass
814 unicodes is to override __eq__, and for speed we don't cater to
815 that here. */
816 if (!PyUnicode_CheckExact(key)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400817 mp->ma_keys->dk_lookup = lookdict;
Victor Stinner742da042016-09-07 17:40:12 -0700818 return lookdict(mp, key, hash, value_addr, hashpos);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 }
Mark Dickinson57e683e2011-09-24 18:18:40 +0100820 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700821 ix = dk_get_index(mp->ma_keys, i);
822 if (ix == DKIX_EMPTY) {
823 if (hashpos != NULL)
824 *hashpos = i;
825 *value_addr = NULL;
826 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400827 }
Victor Stinner742da042016-09-07 17:40:12 -0700828 if (ix == DKIX_DUMMY) {
829 freeslot = i;
830 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 else {
Victor Stinner742da042016-09-07 17:40:12 -0700832 ep = &ep0[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700833 assert(ep->me_key != NULL);
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300834 if (ep->me_key == key
835 || (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700836 if (hashpos != NULL)
837 *hashpos = i;
INADA Naokiba609772016-12-07 20:41:42 +0900838 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700839 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400840 }
Victor Stinner742da042016-09-07 17:40:12 -0700841 freeslot = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 }
Tim Peters15d49292001-05-27 07:39:22 +0000843
INADA Naoki267941c2016-10-06 15:19:07 +0900844 for (size_t perturb = hash;;) {
845 perturb >>= PERTURB_SHIFT;
Victor Stinner742da042016-09-07 17:40:12 -0700846 i = mask & ((i << 2) + i + perturb + 1);
847 ix = dk_get_index(mp->ma_keys, i);
848 if (ix == DKIX_EMPTY) {
849 if (hashpos != NULL) {
850 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400851 }
Victor Stinner742da042016-09-07 17:40:12 -0700852 *value_addr = NULL;
853 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400854 }
Victor Stinner742da042016-09-07 17:40:12 -0700855 if (ix == DKIX_DUMMY) {
856 if (freeslot == -1)
857 freeslot = i;
858 continue;
859 }
860 ep = &ep0[ix];
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300861 assert(ep->me_key != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 if (ep->me_key == key
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300863 || (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
INADA Naokiba609772016-12-07 20:41:42 +0900864 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700865 if (hashpos != NULL) {
866 *hashpos = i;
867 }
868 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400869 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 }
871 assert(0); /* NOT REACHED */
872 return 0;
Fred Drake1bff34a2000-08-31 19:31:38 +0000873}
874
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400875/* Faster version of lookdict_unicode when it is known that no <dummy> keys
876 * will be present. */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100877static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400878lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
INADA Naokiba609772016-12-07 20:41:42 +0900879 Py_hash_t hash, PyObject **value_addr,
Victor Stinner742da042016-09-07 17:40:12 -0700880 Py_ssize_t *hashpos)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400881{
INADA Naoki267941c2016-10-06 15:19:07 +0900882 size_t i;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200883 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700884 Py_ssize_t ix;
885 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400886
Victor Stinner742da042016-09-07 17:40:12 -0700887 assert(mp->ma_values == NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400888 /* Make sure this function doesn't have to handle non-unicode keys,
889 including subclasses of str; e.g., one reason to subclass
890 unicodes is to override __eq__, and for speed we don't cater to
891 that here. */
892 if (!PyUnicode_CheckExact(key)) {
893 mp->ma_keys->dk_lookup = lookdict;
Victor Stinner742da042016-09-07 17:40:12 -0700894 return lookdict(mp, key, hash, value_addr, hashpos);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400895 }
896 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700897 ix = dk_get_index(mp->ma_keys, i);
898 assert (ix != DKIX_DUMMY);
899 if (ix == DKIX_EMPTY) {
900 if (hashpos != NULL)
901 *hashpos = i;
902 *value_addr = NULL;
903 return DKIX_EMPTY;
904 }
905 ep = &ep0[ix];
Victor Stinnerdee6e252016-09-08 11:16:07 -0700906 assert(ep->me_key != NULL);
907 assert(PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700908 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400909 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700910 if (hashpos != NULL)
911 *hashpos = i;
INADA Naokiba609772016-12-07 20:41:42 +0900912 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700913 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400914 }
INADA Naoki267941c2016-10-06 15:19:07 +0900915 for (size_t perturb = hash;;) {
916 perturb >>= PERTURB_SHIFT;
Victor Stinner742da042016-09-07 17:40:12 -0700917 i = mask & ((i << 2) + i + perturb + 1);
918 ix = dk_get_index(mp->ma_keys, i);
919 assert (ix != DKIX_DUMMY);
920 if (ix == DKIX_EMPTY) {
921 if (hashpos != NULL)
922 *hashpos = i;
923 *value_addr = NULL;
924 return DKIX_EMPTY;
925 }
926 ep = &ep0[ix];
927 assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
928 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400929 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700930 if (hashpos != NULL)
931 *hashpos = i;
INADA Naokiba609772016-12-07 20:41:42 +0900932 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700933 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400934 }
935 }
936 assert(0); /* NOT REACHED */
937 return 0;
938}
939
940/* Version of lookdict for split tables.
941 * All split tables and only split tables use this lookup function.
942 * Split tables only contain unicode keys and no dummy keys,
943 * so algorithm is the same as lookdict_unicode_nodummy.
944 */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100945static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400946lookdict_split(PyDictObject *mp, PyObject *key,
INADA Naokiba609772016-12-07 20:41:42 +0900947 Py_hash_t hash, PyObject **value_addr, Py_ssize_t *hashpos)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400948{
INADA Naoki267941c2016-10-06 15:19:07 +0900949 size_t i;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200950 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700951 Py_ssize_t ix;
952 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400953
Victor Stinner742da042016-09-07 17:40:12 -0700954 /* mp must split table */
955 assert(mp->ma_values != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400956 if (!PyUnicode_CheckExact(key)) {
Victor Stinner742da042016-09-07 17:40:12 -0700957 ix = lookdict(mp, key, hash, value_addr, hashpos);
958 if (ix >= 0) {
INADA Naokiba609772016-12-07 20:41:42 +0900959 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700960 }
961 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400962 }
Victor Stinner742da042016-09-07 17:40:12 -0700963
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400964 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700965 ix = dk_get_index(mp->ma_keys, i);
966 if (ix == DKIX_EMPTY) {
967 if (hashpos != NULL)
968 *hashpos = i;
969 *value_addr = NULL;
970 return DKIX_EMPTY;
971 }
972 assert(ix >= 0);
973 ep = &ep0[ix];
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300974 assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700975 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400976 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700977 if (hashpos != NULL)
978 *hashpos = i;
INADA Naokiba609772016-12-07 20:41:42 +0900979 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700980 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400981 }
INADA Naoki267941c2016-10-06 15:19:07 +0900982 for (size_t perturb = hash;;) {
983 perturb >>= PERTURB_SHIFT;
Victor Stinner742da042016-09-07 17:40:12 -0700984 i = mask & ((i << 2) + i + perturb + 1);
985 ix = dk_get_index(mp->ma_keys, i);
986 if (ix == DKIX_EMPTY) {
987 if (hashpos != NULL)
988 *hashpos = i;
989 *value_addr = NULL;
990 return DKIX_EMPTY;
991 }
992 assert(ix >= 0);
993 ep = &ep0[ix];
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300994 assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700995 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400996 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700997 if (hashpos != NULL)
998 *hashpos = i;
INADA Naokiba609772016-12-07 20:41:42 +0900999 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -07001000 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001001 }
1002 }
1003 assert(0); /* NOT REACHED */
1004 return 0;
1005}
1006
Benjamin Petersonfb886362010-04-24 18:21:17 +00001007int
1008_PyDict_HasOnlyStringKeys(PyObject *dict)
1009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 Py_ssize_t pos = 0;
1011 PyObject *key, *value;
Benjamin Petersonf6096542010-11-17 22:33:12 +00001012 assert(PyDict_Check(dict));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 /* Shortcut */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001014 if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 return 1;
1016 while (PyDict_Next(dict, &pos, &key, &value))
1017 if (!PyUnicode_Check(key))
1018 return 0;
1019 return 1;
Benjamin Petersonfb886362010-04-24 18:21:17 +00001020}
1021
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001022#define MAINTAIN_TRACKING(mp, key, value) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 do { \
1024 if (!_PyObject_GC_IS_TRACKED(mp)) { \
1025 if (_PyObject_GC_MAY_BE_TRACKED(key) || \
1026 _PyObject_GC_MAY_BE_TRACKED(value)) { \
1027 _PyObject_GC_TRACK(mp); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 } \
1029 } \
1030 } while(0)
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001031
1032void
1033_PyDict_MaybeUntrack(PyObject *op)
1034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 PyDictObject *mp;
1036 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -07001037 Py_ssize_t i, numentries;
1038 PyDictKeyEntry *ep0;
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
1041 return;
1042
1043 mp = (PyDictObject *) op;
Victor Stinner742da042016-09-07 17:40:12 -07001044 ep0 = DK_ENTRIES(mp->ma_keys);
1045 numentries = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001046 if (_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -07001047 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001048 if ((value = mp->ma_values[i]) == NULL)
1049 continue;
1050 if (_PyObject_GC_MAY_BE_TRACKED(value)) {
Victor Stinner742da042016-09-07 17:40:12 -07001051 assert(!_PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001052 return;
1053 }
1054 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001056 else {
Victor Stinner742da042016-09-07 17:40:12 -07001057 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001058 if ((value = ep0[i].me_value) == NULL)
1059 continue;
1060 if (_PyObject_GC_MAY_BE_TRACKED(value) ||
1061 _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
1062 return;
1063 }
1064 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 _PyObject_GC_UNTRACK(op);
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001066}
1067
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001068/* Internal function to find slot for an item from its hash
Victor Stinner3c336c52016-09-12 14:17:40 +02001069 when it is known that the key is not present in the dict.
1070
1071 The dict must be combined. */
INADA Naokiba609772016-12-07 20:41:42 +09001072static Py_ssize_t
1073find_empty_slot(PyDictKeysObject *keys, PyObject *key, Py_hash_t hash)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001074{
INADA Naoki267941c2016-10-06 15:19:07 +09001075 size_t i;
INADA Naokiba609772016-12-07 20:41:42 +09001076 size_t mask = DK_MASK(keys);
Victor Stinner742da042016-09-07 17:40:12 -07001077 Py_ssize_t ix;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001078
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001079 assert(key != NULL);
Victor Stinner3c336c52016-09-12 14:17:40 +02001080
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001081 i = hash & mask;
INADA Naokiba609772016-12-07 20:41:42 +09001082 ix = dk_get_index(keys, i);
INADA Naoki267941c2016-10-06 15:19:07 +09001083 for (size_t perturb = hash; ix != DKIX_EMPTY;) {
1084 perturb >>= PERTURB_SHIFT;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001085 i = (i << 2) + i + perturb + 1;
INADA Naokiba609772016-12-07 20:41:42 +09001086 ix = dk_get_index(keys, i & mask);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 }
INADA Naokiba609772016-12-07 20:41:42 +09001088 assert(DK_ENTRIES(keys)[keys->dk_nentries].me_value == NULL);
1089 return i & mask;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001090}
1091
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001092static int
1093insertion_resize(PyDictObject *mp)
1094{
Raymond Hettinger36f74aa2013-05-17 03:01:13 -07001095 return dictresize(mp, GROWTH_RATE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001096}
Antoine Pitroue965d972012-02-27 00:45:12 +01001097
1098/*
1099Internal routine to insert a new item into the table.
1100Used both by the internal resize routine and by the public insert routine.
Antoine Pitroue965d972012-02-27 00:45:12 +01001101Returns -1 if an error occurred, or 0 on success.
1102*/
1103static int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001104insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001105{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001106 PyObject *old_value;
INADA Naokiba609772016-12-07 20:41:42 +09001107 PyDictKeyEntry *ep;
Victor Stinner742da042016-09-07 17:40:12 -07001108 Py_ssize_t hashpos, ix;
Antoine Pitroue965d972012-02-27 00:45:12 +01001109
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001110 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
1111 if (insertion_resize(mp) < 0)
1112 return -1;
1113 }
1114
INADA Naokiba609772016-12-07 20:41:42 +09001115 ix = mp->ma_keys->dk_lookup(mp, key, hash, &old_value, &hashpos);
Victor Stinner742da042016-09-07 17:40:12 -07001116 if (ix == DKIX_ERROR) {
Antoine Pitroue965d972012-02-27 00:45:12 +01001117 return -1;
1118 }
Victor Stinner742da042016-09-07 17:40:12 -07001119
Antoine Pitroud6967322014-10-18 00:35:00 +02001120 assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
Benjamin Petersona6f195e2012-04-30 10:23:40 -04001121 Py_INCREF(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001122 MAINTAIN_TRACKING(mp, key, value);
Victor Stinner742da042016-09-07 17:40:12 -07001123
1124 /* When insertion order is different from shared key, we can't share
1125 * the key anymore. Convert this instance to combine table.
1126 */
1127 if (_PyDict_HasSplitTable(mp) &&
INADA Naokiba609772016-12-07 20:41:42 +09001128 ((ix >= 0 && old_value == NULL && mp->ma_used != ix) ||
Victor Stinner742da042016-09-07 17:40:12 -07001129 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
1130 if (insertion_resize(mp) < 0) {
1131 Py_DECREF(value);
1132 return -1;
1133 }
INADA Naokiba609772016-12-07 20:41:42 +09001134 hashpos = find_empty_slot(mp->ma_keys, key, hash);
Victor Stinner742da042016-09-07 17:40:12 -07001135 ix = DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001136 }
Victor Stinner742da042016-09-07 17:40:12 -07001137
1138 if (ix == DKIX_EMPTY) {
1139 /* Insert into new slot. */
INADA Naokiba609772016-12-07 20:41:42 +09001140 assert(old_value == NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001141 if (mp->ma_keys->dk_usable <= 0) {
1142 /* Need to resize. */
1143 if (insertion_resize(mp) < 0) {
1144 Py_DECREF(value);
1145 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001146 }
INADA Naokiba609772016-12-07 20:41:42 +09001147 hashpos = find_empty_slot(mp->ma_keys, key, hash);
Victor Stinner742da042016-09-07 17:40:12 -07001148 }
INADA Naokiba609772016-12-07 20:41:42 +09001149 ep = &DK_ENTRIES(mp->ma_keys)[mp->ma_keys->dk_nentries];
Victor Stinner742da042016-09-07 17:40:12 -07001150 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
1151 Py_INCREF(key);
1152 ep->me_key = key;
1153 ep->me_hash = hash;
1154 if (mp->ma_values) {
1155 assert (mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
1156 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001157 }
1158 else {
Victor Stinner742da042016-09-07 17:40:12 -07001159 ep->me_value = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001160 }
1161 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001162 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07001163 mp->ma_keys->dk_usable--;
1164 mp->ma_keys->dk_nentries++;
1165 assert(mp->ma_keys->dk_usable >= 0);
Victor Stinner611b0fa2016-09-14 15:02:01 +02001166 assert(_PyDict_CheckConsistency(mp));
Victor Stinner742da042016-09-07 17:40:12 -07001167 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001168 }
Victor Stinner742da042016-09-07 17:40:12 -07001169
INADA Naokiba609772016-12-07 20:41:42 +09001170 if (_PyDict_HasSplitTable(mp)) {
1171 mp->ma_values[ix] = value;
1172 if (old_value == NULL) {
1173 /* pending state */
1174 assert(ix == mp->ma_used);
1175 mp->ma_used++;
1176 }
1177 }
1178 else {
1179 assert(old_value != NULL);
1180 DK_ENTRIES(mp->ma_keys)[ix].me_value = value;
Victor Stinner742da042016-09-07 17:40:12 -07001181 }
1182
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001183 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naokiba609772016-12-07 20:41:42 +09001184 Py_XDECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
Victor Stinner611b0fa2016-09-14 15:02:01 +02001185 assert(_PyDict_CheckConsistency(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001186 return 0;
Antoine Pitroue965d972012-02-27 00:45:12 +01001187}
1188
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001189/*
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001190Internal routine used by dictresize() to buid a hashtable of entries.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001191*/
1192static void
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001193build_indices(PyDictKeysObject *keys, PyDictKeyEntry *ep, Py_ssize_t n)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001194{
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001195 size_t mask = (size_t)DK_SIZE(keys) - 1;
1196 for (Py_ssize_t ix = 0; ix != n; ix++, ep++) {
1197 Py_hash_t hash = ep->me_hash;
1198 size_t i = hash & mask;
1199 for (size_t perturb = hash; dk_get_index(keys, i) != DKIX_EMPTY;) {
1200 perturb >>= PERTURB_SHIFT;
1201 i = mask & ((i << 2) + i + perturb + 1);
1202 }
1203 dk_set_index(keys, i, ix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001205}
1206
1207/*
1208Restructure the table by allocating a new table and reinserting all
1209items again. When entries have been deleted, the new table may
1210actually be smaller than the old one.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001211If a table is split (its keys and hashes are shared, its values are not),
1212then the values are temporarily copied into the table, it is resized as
1213a combined table, then the me_value slots in the old table are NULLed out.
1214After resizing a table is always combined,
1215but can be resplit by make_keys_shared().
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001216*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001217static int
Victor Stinner3d3f2642016-12-15 17:21:23 +01001218dictresize(PyDictObject *mp, Py_ssize_t minsize)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001219{
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001220 Py_ssize_t newsize, numentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001221 PyDictKeysObject *oldkeys;
1222 PyObject **oldvalues;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001223 PyDictKeyEntry *oldentries, *newentries;
Tim Peters91a364d2001-05-19 07:04:38 +00001224
Victor Stinner742da042016-09-07 17:40:12 -07001225 /* Find the smallest table size > minused. */
1226 for (newsize = PyDict_MINSIZE;
Victor Stinner3d3f2642016-12-15 17:21:23 +01001227 newsize < minsize && newsize > 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 newsize <<= 1)
1229 ;
1230 if (newsize <= 0) {
1231 PyErr_NoMemory();
1232 return -1;
1233 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001234
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001235 oldkeys = mp->ma_keys;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001236
1237 /* NOTE: Current odict checks mp->ma_keys to detect resize happen.
1238 * So we can't reuse oldkeys even if oldkeys->dk_size == newsize.
1239 * TODO: Try reusing oldkeys when reimplement odict.
1240 */
1241
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001242 /* Allocate a new table. */
1243 mp->ma_keys = new_keys_object(newsize);
1244 if (mp->ma_keys == NULL) {
1245 mp->ma_keys = oldkeys;
1246 return -1;
1247 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01001248 // New table must be large enough.
1249 assert(mp->ma_keys->dk_usable >= mp->ma_used);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001250 if (oldkeys->dk_lookup == lookdict)
1251 mp->ma_keys->dk_lookup = lookdict;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001252
1253 numentries = mp->ma_used;
1254 oldentries = DK_ENTRIES(oldkeys);
1255 newentries = DK_ENTRIES(mp->ma_keys);
1256 oldvalues = mp->ma_values;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001257 if (oldvalues != NULL) {
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001258 /* Convert split table into new combined table.
1259 * We must incref keys; we can transfer values.
1260 * Note that values of split table is always dense.
1261 */
1262 for (Py_ssize_t i = 0; i < numentries; i++) {
1263 assert(oldvalues[i] != NULL);
1264 PyDictKeyEntry *ep = &oldentries[i];
1265 PyObject *key = ep->me_key;
1266 Py_INCREF(key);
1267 newentries[i].me_key = key;
1268 newentries[i].me_hash = ep->me_hash;
1269 newentries[i].me_value = oldvalues[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001271
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001272 DK_DECREF(oldkeys);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001273 mp->ma_values = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001274 if (oldvalues != empty_values) {
1275 free_values(oldvalues);
1276 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001277 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001278 else { // combined table.
1279 if (oldkeys->dk_nentries == numentries) {
1280 memcpy(newentries, oldentries, numentries * sizeof(PyDictKeyEntry));
1281 }
1282 else {
1283 PyDictKeyEntry *ep = oldentries;
1284 for (Py_ssize_t i = 0; i < numentries; i++) {
1285 while (ep->me_value == NULL)
1286 ep++;
1287 newentries[i] = *ep++;
1288 }
1289 }
1290
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001291 assert(oldkeys->dk_lookup != lookdict_split);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001292 assert(oldkeys->dk_refcnt == 1);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001293 if (oldkeys->dk_size == PyDict_MINSIZE &&
1294 numfreekeys < PyDict_MAXFREELIST) {
1295 DK_DEBUG_DECREF keys_free_list[numfreekeys++] = oldkeys;
1296 }
1297 else {
1298 DK_DEBUG_DECREF PyObject_FREE(oldkeys);
1299 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001300 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001301
1302 build_indices(mp->ma_keys, newentries, numentries);
1303 mp->ma_keys->dk_usable -= numentries;
1304 mp->ma_keys->dk_nentries = numentries;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001306}
1307
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001308/* Returns NULL if unable to split table.
1309 * A NULL return does not necessarily indicate an error */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001310static PyDictKeysObject *
1311make_keys_shared(PyObject *op)
1312{
1313 Py_ssize_t i;
1314 Py_ssize_t size;
1315 PyDictObject *mp = (PyDictObject *)op;
1316
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001317 if (!PyDict_CheckExact(op))
1318 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001319 if (!_PyDict_HasSplitTable(mp)) {
1320 PyDictKeyEntry *ep0;
1321 PyObject **values;
1322 assert(mp->ma_keys->dk_refcnt == 1);
1323 if (mp->ma_keys->dk_lookup == lookdict) {
1324 return NULL;
1325 }
1326 else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
1327 /* Remove dummy keys */
1328 if (dictresize(mp, DK_SIZE(mp->ma_keys)))
1329 return NULL;
1330 }
1331 assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
1332 /* Copy values into a new array */
Victor Stinner742da042016-09-07 17:40:12 -07001333 ep0 = DK_ENTRIES(mp->ma_keys);
1334 size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001335 values = new_values(size);
1336 if (values == NULL) {
1337 PyErr_SetString(PyExc_MemoryError,
1338 "Not enough memory to allocate new values array");
1339 return NULL;
1340 }
1341 for (i = 0; i < size; i++) {
1342 values[i] = ep0[i].me_value;
1343 ep0[i].me_value = NULL;
1344 }
1345 mp->ma_keys->dk_lookup = lookdict_split;
1346 mp->ma_values = values;
1347 }
1348 DK_INCREF(mp->ma_keys);
1349 return mp->ma_keys;
1350}
Christian Heimes99170a52007-12-19 02:07:34 +00001351
1352PyObject *
1353_PyDict_NewPresized(Py_ssize_t minused)
1354{
INADA Naoki92c50ee2016-11-22 00:57:02 +09001355 const Py_ssize_t max_presize = 128 * 1024;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001356 Py_ssize_t newsize;
1357 PyDictKeysObject *new_keys;
INADA Naoki92c50ee2016-11-22 00:57:02 +09001358
1359 /* There are no strict guarantee that returned dict can contain minused
1360 * items without resize. So we create medium size dict instead of very
1361 * large dict or MemoryError.
1362 */
1363 if (minused > USABLE_FRACTION(max_presize)) {
1364 newsize = max_presize;
1365 }
1366 else {
1367 Py_ssize_t minsize = ESTIMATE_SIZE(minused);
1368 newsize = PyDict_MINSIZE;
1369 while (newsize < minsize) {
1370 newsize <<= 1;
1371 }
1372 }
1373 assert(IS_POWER_OF_2(newsize));
1374
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001375 new_keys = new_keys_object(newsize);
1376 if (new_keys == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001378 return new_dict(new_keys, NULL);
Christian Heimes99170a52007-12-19 02:07:34 +00001379}
1380
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001381/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
1382 * that may occur (originally dicts supported only string keys, and exceptions
1383 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001384 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001385 * (suppressed) occurred while computing the key's hash, or that some error
1386 * (suppressed) occurred when comparing keys in the dict's internal probe
1387 * sequence. A nasty example of the latter is when a Python-coded comparison
1388 * function hits a stack-depth error, which can cause this to return NULL
1389 * even if the key is present.
1390 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001391PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001392PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001393{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001394 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001395 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 PyDictObject *mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 PyThreadState *tstate;
INADA Naokiba609772016-12-07 20:41:42 +09001398 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 if (!PyDict_Check(op))
1401 return NULL;
1402 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001403 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 {
1405 hash = PyObject_Hash(key);
1406 if (hash == -1) {
1407 PyErr_Clear();
1408 return NULL;
1409 }
1410 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 /* We can arrive here with a NULL tstate during initialization: try
1413 running "python -Wi" for an example related to string interning.
1414 Let's just hope that no exception occurs then... This must be
1415 _PyThreadState_Current and not PyThreadState_GET() because in debug
1416 mode, the latter complains if tstate is NULL. */
Victor Stinner0cae6092016-11-11 01:43:56 +01001417 tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (tstate != NULL && tstate->curexc_type != NULL) {
1419 /* preserve the existing exception */
1420 PyObject *err_type, *err_value, *err_tb;
1421 PyErr_Fetch(&err_type, &err_value, &err_tb);
INADA Naokiba609772016-12-07 20:41:42 +09001422 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 /* ignore errors */
1424 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001425 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 return NULL;
1427 }
1428 else {
INADA Naokiba609772016-12-07 20:41:42 +09001429 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001430 if (ix < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 PyErr_Clear();
1432 return NULL;
1433 }
1434 }
INADA Naokiba609772016-12-07 20:41:42 +09001435 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001436}
1437
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001438/* Same as PyDict_GetItemWithError() but with hash supplied by caller.
1439 This returns NULL *with* an exception set if an exception occurred.
1440 It returns NULL *without* an exception set if the key wasn't present.
1441*/
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001442PyObject *
1443_PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1444{
Victor Stinner742da042016-09-07 17:40:12 -07001445 Py_ssize_t ix;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001446 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001447 PyObject *value;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001448
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001449 if (!PyDict_Check(op)) {
1450 PyErr_BadInternalCall();
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001451 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001452 }
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001453
INADA Naokiba609772016-12-07 20:41:42 +09001454 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001455 if (ix < 0) {
1456 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001457 }
INADA Naokiba609772016-12-07 20:41:42 +09001458 return value;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001459}
1460
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001461/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
1462 This returns NULL *with* an exception set if an exception occurred.
1463 It returns NULL *without* an exception set if the key wasn't present.
1464*/
1465PyObject *
1466PyDict_GetItemWithError(PyObject *op, PyObject *key)
1467{
Victor Stinner742da042016-09-07 17:40:12 -07001468 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001469 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 PyDictObject*mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001471 PyObject *value;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 if (!PyDict_Check(op)) {
1474 PyErr_BadInternalCall();
1475 return NULL;
1476 }
1477 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001478 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 {
1480 hash = PyObject_Hash(key);
1481 if (hash == -1) {
1482 return NULL;
1483 }
1484 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001485
INADA Naokiba609772016-12-07 20:41:42 +09001486 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001487 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001489 return value;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001490}
1491
Brett Cannonfd074152012-04-14 14:10:13 -04001492PyObject *
1493_PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
1494{
1495 PyObject *kv;
1496 kv = _PyUnicode_FromId(key); /* borrowed */
1497 if (kv == NULL)
1498 return NULL;
1499 return PyDict_GetItemWithError(dp, kv);
1500}
1501
Victor Stinnerb4efc962015-11-20 09:24:02 +01001502/* Fast version of global value lookup (LOAD_GLOBAL).
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001503 * Lookup in globals, then builtins.
Victor Stinnerb4efc962015-11-20 09:24:02 +01001504 *
1505 * Raise an exception and return NULL if an error occurred (ex: computing the
1506 * key hash failed, key comparison failed, ...). Return NULL if the key doesn't
1507 * exist. Return the value if the key exists.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001508 */
1509PyObject *
1510_PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001511{
Victor Stinner742da042016-09-07 17:40:12 -07001512 Py_ssize_t ix;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001513 Py_hash_t hash;
INADA Naokiba609772016-12-07 20:41:42 +09001514 PyObject *value;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001515
1516 if (!PyUnicode_CheckExact(key) ||
1517 (hash = ((PyASCIIObject *) key)->hash) == -1)
1518 {
1519 hash = PyObject_Hash(key);
1520 if (hash == -1)
1521 return NULL;
Antoine Pitroue965d972012-02-27 00:45:12 +01001522 }
Victor Stinnerb4efc962015-11-20 09:24:02 +01001523
1524 /* namespace 1: globals */
INADA Naokiba609772016-12-07 20:41:42 +09001525 ix = globals->ma_keys->dk_lookup(globals, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001526 if (ix == DKIX_ERROR)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001527 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001528 if (ix != DKIX_EMPTY && value != NULL)
1529 return value;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001530
1531 /* namespace 2: builtins */
INADA Naokiba609772016-12-07 20:41:42 +09001532 ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001533 if (ix < 0)
Victor Stinnerb4efc962015-11-20 09:24:02 +01001534 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001535 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001536}
1537
Antoine Pitroue965d972012-02-27 00:45:12 +01001538/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
1539 * dictionary if it's merely replacing the value for an existing key.
1540 * This means that it's safe to loop over a dictionary with PyDict_Next()
1541 * and occasionally replace a value -- but you can't insert new keys or
1542 * remove them.
1543 */
1544int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001545PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001546{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001547 PyDictObject *mp;
1548 Py_hash_t hash;
Antoine Pitroue965d972012-02-27 00:45:12 +01001549 if (!PyDict_Check(op)) {
1550 PyErr_BadInternalCall();
1551 return -1;
1552 }
1553 assert(key);
1554 assert(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001555 mp = (PyDictObject *)op;
1556 if (!PyUnicode_CheckExact(key) ||
1557 (hash = ((PyASCIIObject *) key)->hash) == -1)
1558 {
Antoine Pitroue965d972012-02-27 00:45:12 +01001559 hash = PyObject_Hash(key);
1560 if (hash == -1)
1561 return -1;
1562 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001563
1564 /* insertdict() handles any resizing that might be necessary */
1565 return insertdict(mp, key, hash, value);
Antoine Pitroue965d972012-02-27 00:45:12 +01001566}
1567
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001568int
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001569_PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
1570 Py_hash_t hash)
1571{
1572 PyDictObject *mp;
1573
1574 if (!PyDict_Check(op)) {
1575 PyErr_BadInternalCall();
1576 return -1;
1577 }
1578 assert(key);
1579 assert(value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001580 assert(hash != -1);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001581 mp = (PyDictObject *)op;
1582
1583 /* insertdict() handles any resizing that might be necessary */
1584 return insertdict(mp, key, hash, value);
1585}
1586
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001587static int
Antoine Pitroud741ed42016-12-27 14:23:43 +01001588delitem_common(PyDictObject *mp, Py_ssize_t hashpos, Py_ssize_t ix,
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001589 PyObject *old_value)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001590{
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001591 PyObject *old_key;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001592 PyDictKeyEntry *ep;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001593
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001594 mp->ma_used--;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001595 mp->ma_version_tag = DICT_NEXT_VERSION();
1596 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1597 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1598 ENSURE_ALLOWS_DELETIONS(mp);
1599 old_key = ep->me_key;
1600 ep->me_key = NULL;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001601 ep->me_value = NULL;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001602 Py_DECREF(old_key);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001603 Py_DECREF(old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001604
1605 assert(_PyDict_CheckConsistency(mp));
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001606 return 0;
1607}
1608
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001609int
Tim Peters1f5871e2000-07-04 17:44:48 +00001610PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001611{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001612 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 assert(key);
1614 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001615 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 hash = PyObject_Hash(key);
1617 if (hash == -1)
1618 return -1;
1619 }
Victor Stinner742da042016-09-07 17:40:12 -07001620
1621 return _PyDict_DelItem_KnownHash(op, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001622}
1623
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001624int
1625_PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1626{
Victor Stinner742da042016-09-07 17:40:12 -07001627 Py_ssize_t hashpos, ix;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001628 PyDictObject *mp;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001629 PyObject *old_value;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001630
1631 if (!PyDict_Check(op)) {
1632 PyErr_BadInternalCall();
1633 return -1;
1634 }
1635 assert(key);
1636 assert(hash != -1);
1637 mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001638 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value, &hashpos);
Victor Stinner742da042016-09-07 17:40:12 -07001639 if (ix == DKIX_ERROR)
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001640 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09001641 if (ix == DKIX_EMPTY || old_value == NULL) {
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001642 _PyErr_SetKeyError(key);
1643 return -1;
1644 }
Victor Stinner742da042016-09-07 17:40:12 -07001645 assert(dk_get_index(mp->ma_keys, hashpos) == ix);
Victor Stinner78601a32016-09-09 19:28:36 -07001646
1647 // Split table doesn't allow deletion. Combine it.
1648 if (_PyDict_HasSplitTable(mp)) {
1649 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1650 return -1;
1651 }
INADA Naokiba609772016-12-07 20:41:42 +09001652 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value, &hashpos);
Victor Stinner78601a32016-09-09 19:28:36 -07001653 assert(ix >= 0);
1654 }
1655
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001656 return delitem_common(mp, hashpos, ix, old_value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001657}
1658
Antoine Pitroud741ed42016-12-27 14:23:43 +01001659/* This function promises that the predicate -> deletion sequence is atomic
1660 * (i.e. protected by the GIL), assuming the predicate itself doesn't
1661 * release the GIL.
1662 */
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001663int
1664_PyDict_DelItemIf(PyObject *op, PyObject *key,
1665 int (*predicate)(PyObject *value))
1666{
Antoine Pitroud741ed42016-12-27 14:23:43 +01001667 Py_ssize_t hashpos, ix;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001668 PyDictObject *mp;
1669 Py_hash_t hash;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001670 PyObject *old_value;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001671 int res;
1672
1673 if (!PyDict_Check(op)) {
1674 PyErr_BadInternalCall();
1675 return -1;
1676 }
1677 assert(key);
1678 hash = PyObject_Hash(key);
1679 if (hash == -1)
1680 return -1;
1681 mp = (PyDictObject *)op;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001682 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value, &hashpos);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001683 if (ix == DKIX_ERROR)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001684 return -1;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001685 if (ix == DKIX_EMPTY || old_value == NULL) {
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001686 _PyErr_SetKeyError(key);
1687 return -1;
1688 }
Antoine Pitroud741ed42016-12-27 14:23:43 +01001689 assert(dk_get_index(mp->ma_keys, hashpos) == ix);
1690
1691 // Split table doesn't allow deletion. Combine it.
1692 if (_PyDict_HasSplitTable(mp)) {
1693 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1694 return -1;
1695 }
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001696 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value, &hashpos);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001697 assert(ix >= 0);
1698 }
1699
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001700 res = predicate(old_value);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001701 if (res == -1)
1702 return -1;
1703 if (res > 0)
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001704 return delitem_common(mp, hashpos, ix, old_value);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001705 else
1706 return 0;
1707}
1708
1709
Guido van Rossum25831651993-05-19 14:50:45 +00001710void
Tim Peters1f5871e2000-07-04 17:44:48 +00001711PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 PyDictObject *mp;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001714 PyDictKeysObject *oldkeys;
1715 PyObject **oldvalues;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +00001717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 if (!PyDict_Check(op))
1719 return;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001720 mp = ((PyDictObject *)op);
1721 oldkeys = mp->ma_keys;
1722 oldvalues = mp->ma_values;
1723 if (oldvalues == empty_values)
1724 return;
1725 /* Empty the dict... */
1726 DK_INCREF(Py_EMPTY_KEYS);
1727 mp->ma_keys = Py_EMPTY_KEYS;
1728 mp->ma_values = empty_values;
1729 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001730 mp->ma_version_tag = DICT_NEXT_VERSION();
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001731 /* ...then clear the keys and values */
1732 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001733 n = oldkeys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001734 for (i = 0; i < n; i++)
1735 Py_CLEAR(oldvalues[i]);
1736 free_values(oldvalues);
1737 DK_DECREF(oldkeys);
1738 }
1739 else {
1740 assert(oldkeys->dk_refcnt == 1);
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001741 DK_DECREF(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001742 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02001743 assert(_PyDict_CheckConsistency(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001744}
1745
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001746/* Internal version of PyDict_Next that returns a hash value in addition
1747 * to the key and value.
1748 * Return 1 on success, return 0 when the reached the end of the dictionary
1749 * (or if op is not a dictionary)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001750 */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001751int
1752_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
1753 PyObject **pvalue, Py_hash_t *phash)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001754{
INADA Naokica2d8be2016-11-04 16:59:10 +09001755 Py_ssize_t i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001756 PyDictObject *mp;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001757 PyDictKeyEntry *entry_ptr;
1758 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001759
1760 if (!PyDict_Check(op))
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001761 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 mp = (PyDictObject *)op;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001763 i = *ppos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001764 if (mp->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09001765 if (i < 0 || i >= mp->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001766 return 0;
INADA Naokica2d8be2016-11-04 16:59:10 +09001767 /* values of split table is always dense */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001768 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
INADA Naokica2d8be2016-11-04 16:59:10 +09001769 value = mp->ma_values[i];
1770 assert(value != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001772 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09001773 Py_ssize_t n = mp->ma_keys->dk_nentries;
1774 if (i < 0 || i >= n)
1775 return 0;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001776 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
1777 while (i < n && entry_ptr->me_value == NULL) {
1778 entry_ptr++;
1779 i++;
Victor Stinner742da042016-09-07 17:40:12 -07001780 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001781 if (i >= n)
1782 return 0;
1783 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001785 *ppos = i+1;
1786 if (pkey)
1787 *pkey = entry_ptr->me_key;
1788 if (phash)
1789 *phash = entry_ptr->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001790 if (pvalue)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001791 *pvalue = value;
1792 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001793}
1794
Tim Peters080c88b2003-02-15 03:01:11 +00001795/*
1796 * Iterate over a dict. Use like so:
1797 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001798 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +00001799 * PyObject *key, *value;
1800 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +00001801 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001802 * Refer to borrowed references in key and value.
Tim Peters080c88b2003-02-15 03:01:11 +00001803 * }
1804 *
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001805 * Return 1 on success, return 0 when the reached the end of the dictionary
1806 * (or if op is not a dictionary)
1807 *
Tim Peters080c88b2003-02-15 03:01:11 +00001808 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +00001809 * mutates the dict. One exception: it is safe if the loop merely changes
1810 * the values associated with the keys (but doesn't insert new keys or
1811 * delete keys), via PyDict_SetItem().
1812 */
Guido van Rossum25831651993-05-19 14:50:45 +00001813int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001814PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001815{
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001816 return _PyDict_Next(op, ppos, pkey, pvalue, NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00001817}
1818
Eric Snow96c6af92015-05-29 22:21:39 -06001819/* Internal version of dict.pop(). */
1820PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001821_PyDict_Pop_KnownHash(PyObject *dict, PyObject *key, Py_hash_t hash, PyObject *deflt)
Eric Snow96c6af92015-05-29 22:21:39 -06001822{
Victor Stinner742da042016-09-07 17:40:12 -07001823 Py_ssize_t ix, hashpos;
Eric Snow96c6af92015-05-29 22:21:39 -06001824 PyObject *old_value, *old_key;
1825 PyDictKeyEntry *ep;
Yury Selivanov684ef2c2016-10-28 19:01:21 -04001826 PyDictObject *mp;
1827
1828 assert(PyDict_Check(dict));
1829 mp = (PyDictObject *)dict;
Eric Snow96c6af92015-05-29 22:21:39 -06001830
1831 if (mp->ma_used == 0) {
1832 if (deflt) {
1833 Py_INCREF(deflt);
1834 return deflt;
1835 }
1836 _PyErr_SetKeyError(key);
1837 return NULL;
1838 }
INADA Naokiba609772016-12-07 20:41:42 +09001839 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value, &hashpos);
Victor Stinner742da042016-09-07 17:40:12 -07001840 if (ix == DKIX_ERROR)
Eric Snow96c6af92015-05-29 22:21:39 -06001841 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001842 if (ix == DKIX_EMPTY || old_value == NULL) {
Eric Snow96c6af92015-05-29 22:21:39 -06001843 if (deflt) {
1844 Py_INCREF(deflt);
1845 return deflt;
1846 }
1847 _PyErr_SetKeyError(key);
1848 return NULL;
1849 }
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001850
Victor Stinner78601a32016-09-09 19:28:36 -07001851 // Split table doesn't allow deletion. Combine it.
1852 if (_PyDict_HasSplitTable(mp)) {
1853 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1854 return NULL;
1855 }
INADA Naokiba609772016-12-07 20:41:42 +09001856 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value, &hashpos);
Victor Stinner78601a32016-09-09 19:28:36 -07001857 assert(ix >= 0);
1858 }
1859
Victor Stinner78601a32016-09-09 19:28:36 -07001860 assert(old_value != NULL);
Eric Snow96c6af92015-05-29 22:21:39 -06001861 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001862 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner78601a32016-09-09 19:28:36 -07001863 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1864 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1865 ENSURE_ALLOWS_DELETIONS(mp);
1866 old_key = ep->me_key;
1867 ep->me_key = NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001868 ep->me_value = NULL;
Victor Stinner78601a32016-09-09 19:28:36 -07001869 Py_DECREF(old_key);
Victor Stinner611b0fa2016-09-14 15:02:01 +02001870
1871 assert(_PyDict_CheckConsistency(mp));
Eric Snow96c6af92015-05-29 22:21:39 -06001872 return old_value;
1873}
1874
Serhiy Storchaka67796522017-01-12 18:34:33 +02001875PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001876_PyDict_Pop(PyObject *dict, PyObject *key, PyObject *deflt)
Serhiy Storchaka67796522017-01-12 18:34:33 +02001877{
1878 Py_hash_t hash;
1879
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001880 if (((PyDictObject *)dict)->ma_used == 0) {
Serhiy Storchaka67796522017-01-12 18:34:33 +02001881 if (deflt) {
1882 Py_INCREF(deflt);
1883 return deflt;
1884 }
1885 _PyErr_SetKeyError(key);
1886 return NULL;
1887 }
1888 if (!PyUnicode_CheckExact(key) ||
1889 (hash = ((PyASCIIObject *) key)->hash) == -1) {
1890 hash = PyObject_Hash(key);
1891 if (hash == -1)
1892 return NULL;
1893 }
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001894 return _PyDict_Pop_KnownHash(dict, key, hash, deflt);
Serhiy Storchaka67796522017-01-12 18:34:33 +02001895}
1896
Eric Snow96c6af92015-05-29 22:21:39 -06001897/* Internal version of dict.from_keys(). It is subclass-friendly. */
1898PyObject *
1899_PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
1900{
1901 PyObject *it; /* iter(iterable) */
1902 PyObject *key;
1903 PyObject *d;
1904 int status;
1905
Victor Stinnera5ed5f02016-12-06 18:45:50 +01001906 d = _PyObject_CallNoArg(cls);
Eric Snow96c6af92015-05-29 22:21:39 -06001907 if (d == NULL)
1908 return NULL;
1909
1910 if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
1911 if (PyDict_CheckExact(iterable)) {
1912 PyDictObject *mp = (PyDictObject *)d;
1913 PyObject *oldvalue;
1914 Py_ssize_t pos = 0;
1915 PyObject *key;
1916 Py_hash_t hash;
1917
Serhiy Storchakac61ac162017-03-21 08:52:38 +02001918 if (dictresize(mp, ESTIMATE_SIZE(PyDict_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001919 Py_DECREF(d);
1920 return NULL;
1921 }
1922
1923 while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
1924 if (insertdict(mp, key, hash, value)) {
1925 Py_DECREF(d);
1926 return NULL;
1927 }
1928 }
1929 return d;
1930 }
1931 if (PyAnySet_CheckExact(iterable)) {
1932 PyDictObject *mp = (PyDictObject *)d;
1933 Py_ssize_t pos = 0;
1934 PyObject *key;
1935 Py_hash_t hash;
1936
Victor Stinner742da042016-09-07 17:40:12 -07001937 if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001938 Py_DECREF(d);
1939 return NULL;
1940 }
1941
1942 while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
1943 if (insertdict(mp, key, hash, value)) {
1944 Py_DECREF(d);
1945 return NULL;
1946 }
1947 }
1948 return d;
1949 }
1950 }
1951
1952 it = PyObject_GetIter(iterable);
1953 if (it == NULL){
1954 Py_DECREF(d);
1955 return NULL;
1956 }
1957
1958 if (PyDict_CheckExact(d)) {
1959 while ((key = PyIter_Next(it)) != NULL) {
1960 status = PyDict_SetItem(d, key, value);
1961 Py_DECREF(key);
1962 if (status < 0)
1963 goto Fail;
1964 }
1965 } else {
1966 while ((key = PyIter_Next(it)) != NULL) {
1967 status = PyObject_SetItem(d, key, value);
1968 Py_DECREF(key);
1969 if (status < 0)
1970 goto Fail;
1971 }
1972 }
1973
1974 if (PyErr_Occurred())
1975 goto Fail;
1976 Py_DECREF(it);
1977 return d;
1978
1979Fail:
1980 Py_DECREF(it);
1981 Py_DECREF(d);
1982 return NULL;
1983}
1984
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001985/* Methods */
1986
1987static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001988dict_dealloc(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001989{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001990 PyObject **values = mp->ma_values;
1991 PyDictKeysObject *keys = mp->ma_keys;
1992 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 PyObject_GC_UnTrack(mp);
1994 Py_TRASHCAN_SAFE_BEGIN(mp)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001995 if (values != NULL) {
1996 if (values != empty_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001997 for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001998 Py_XDECREF(values[i]);
1999 }
2000 free_values(values);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002002 DK_DECREF(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 }
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02002004 else if (keys != NULL) {
Antoine Pitrou2d169b22012-05-12 23:43:44 +02002005 assert(keys->dk_refcnt == 1);
2006 DK_DECREF(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002007 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
2009 free_list[numfree++] = mp;
2010 else
2011 Py_TYPE(mp)->tp_free((PyObject *)mp);
2012 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002013}
2014
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002015
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002016static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002017dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 Py_ssize_t i;
Victor Stinnerf91929b2013-11-19 13:07:38 +01002020 PyObject *key = NULL, *value = NULL;
2021 _PyUnicodeWriter writer;
2022 int first;
Guido van Rossum255443b1998-04-10 22:47:14 +00002023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 i = Py_ReprEnter((PyObject *)mp);
2025 if (i != 0) {
2026 return i > 0 ? PyUnicode_FromString("{...}") : NULL;
2027 }
Guido van Rossum255443b1998-04-10 22:47:14 +00002028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 if (mp->ma_used == 0) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01002030 Py_ReprLeave((PyObject *)mp);
2031 return PyUnicode_FromString("{}");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 }
Tim Petersa7259592001-06-16 05:11:17 +00002033
Victor Stinnerf91929b2013-11-19 13:07:38 +01002034 _PyUnicodeWriter_Init(&writer);
2035 writer.overallocate = 1;
2036 /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
2037 writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +00002038
Victor Stinnerf91929b2013-11-19 13:07:38 +01002039 if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
2040 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00002041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 /* Do repr() on each key+value pair, and insert ": " between them.
2043 Note that repr may mutate the dict. */
2044 i = 0;
Victor Stinnerf91929b2013-11-19 13:07:38 +01002045 first = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01002047 PyObject *s;
2048 int res;
2049
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002050 /* Prevent repr from deleting key or value during key format. */
2051 Py_INCREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 Py_INCREF(value);
Victor Stinnerf97dfd72013-07-18 01:00:45 +02002053
Victor Stinnerf91929b2013-11-19 13:07:38 +01002054 if (!first) {
2055 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
2056 goto error;
2057 }
2058 first = 0;
2059
2060 s = PyObject_Repr(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 if (s == NULL)
Victor Stinnerf91929b2013-11-19 13:07:38 +01002062 goto error;
2063 res = _PyUnicodeWriter_WriteStr(&writer, s);
2064 Py_DECREF(s);
2065 if (res < 0)
2066 goto error;
2067
2068 if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
2069 goto error;
2070
2071 s = PyObject_Repr(value);
2072 if (s == NULL)
2073 goto error;
2074 res = _PyUnicodeWriter_WriteStr(&writer, s);
2075 Py_DECREF(s);
2076 if (res < 0)
2077 goto error;
2078
2079 Py_CLEAR(key);
2080 Py_CLEAR(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 }
Tim Petersa7259592001-06-16 05:11:17 +00002082
Victor Stinnerf91929b2013-11-19 13:07:38 +01002083 writer.overallocate = 0;
2084 if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
2085 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00002086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 Py_ReprLeave((PyObject *)mp);
Victor Stinnerf91929b2013-11-19 13:07:38 +01002088
2089 return _PyUnicodeWriter_Finish(&writer);
2090
2091error:
2092 Py_ReprLeave((PyObject *)mp);
2093 _PyUnicodeWriter_Dealloc(&writer);
2094 Py_XDECREF(key);
2095 Py_XDECREF(value);
2096 return NULL;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002097}
2098
Martin v. Löwis18e16552006-02-15 17:27:45 +00002099static Py_ssize_t
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002100dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 return mp->ma_used;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002103}
2104
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002105static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002106dict_subscript(PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002107{
Victor Stinner742da042016-09-07 17:40:12 -07002108 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002109 Py_hash_t hash;
INADA Naokiba609772016-12-07 20:41:42 +09002110 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002113 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 hash = PyObject_Hash(key);
2115 if (hash == -1)
2116 return NULL;
2117 }
INADA Naokiba609772016-12-07 20:41:42 +09002118 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07002119 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002121 if (ix == DKIX_EMPTY || value == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 if (!PyDict_CheckExact(mp)) {
2123 /* Look up __missing__ method if we're a subclass. */
2124 PyObject *missing, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05002125 _Py_IDENTIFIER(__missing__);
2126 missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 if (missing != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002128 res = PyObject_CallFunctionObjArgs(missing,
2129 key, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 Py_DECREF(missing);
2131 return res;
2132 }
2133 else if (PyErr_Occurred())
2134 return NULL;
2135 }
Raymond Hettinger69492da2013-09-02 15:59:26 -07002136 _PyErr_SetKeyError(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 return NULL;
2138 }
INADA Naokiba609772016-12-07 20:41:42 +09002139 Py_INCREF(value);
2140 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002141}
2142
2143static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002144dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 if (w == NULL)
2147 return PyDict_DelItem((PyObject *)mp, v);
2148 else
2149 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002150}
2151
Guido van Rossuma9e7a811997-05-13 21:02:11 +00002152static PyMappingMethods dict_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 (lenfunc)dict_length, /*mp_length*/
2154 (binaryfunc)dict_subscript, /*mp_subscript*/
2155 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002156};
2157
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002158static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002159dict_keys(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002160{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002161 PyObject *v;
2162 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002163 PyDictKeyEntry *ep;
2164 Py_ssize_t size, n, offset;
2165 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002166
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002167 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 n = mp->ma_used;
2169 v = PyList_New(n);
2170 if (v == NULL)
2171 return NULL;
2172 if (n != mp->ma_used) {
2173 /* Durnit. The allocations caused the dict to resize.
2174 * Just start over, this shouldn't normally happen.
2175 */
2176 Py_DECREF(v);
2177 goto again;
2178 }
Victor Stinner742da042016-09-07 17:40:12 -07002179 ep = DK_ENTRIES(mp->ma_keys);
2180 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002181 if (mp->ma_values) {
2182 value_ptr = mp->ma_values;
2183 offset = sizeof(PyObject *);
2184 }
2185 else {
2186 value_ptr = &ep[0].me_value;
2187 offset = sizeof(PyDictKeyEntry);
2188 }
2189 for (i = 0, j = 0; i < size; i++) {
2190 if (*value_ptr != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 PyObject *key = ep[i].me_key;
2192 Py_INCREF(key);
2193 PyList_SET_ITEM(v, j, key);
2194 j++;
2195 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002196 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 }
2198 assert(j == n);
2199 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002200}
2201
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002202static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002203dict_values(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002204{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002205 PyObject *v;
2206 Py_ssize_t i, j;
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002207 PyDictKeyEntry *ep;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002208 Py_ssize_t size, n, offset;
2209 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002210
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002211 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 n = mp->ma_used;
2213 v = PyList_New(n);
2214 if (v == NULL)
2215 return NULL;
2216 if (n != mp->ma_used) {
2217 /* Durnit. The allocations caused the dict to resize.
2218 * Just start over, this shouldn't normally happen.
2219 */
2220 Py_DECREF(v);
2221 goto again;
2222 }
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002223 ep = DK_ENTRIES(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002224 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002225 if (mp->ma_values) {
2226 value_ptr = mp->ma_values;
2227 offset = sizeof(PyObject *);
2228 }
2229 else {
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002230 value_ptr = &ep[0].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002231 offset = sizeof(PyDictKeyEntry);
2232 }
2233 for (i = 0, j = 0; i < size; i++) {
2234 PyObject *value = *value_ptr;
2235 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2236 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 Py_INCREF(value);
2238 PyList_SET_ITEM(v, j, value);
2239 j++;
2240 }
2241 }
2242 assert(j == n);
2243 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002244}
2245
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002246static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002247dict_items(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002248{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002249 PyObject *v;
2250 Py_ssize_t i, j, n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002251 Py_ssize_t size, offset;
2252 PyObject *item, *key;
2253 PyDictKeyEntry *ep;
2254 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 /* Preallocate the list of tuples, to avoid allocations during
2257 * the loop over the items, which could trigger GC, which
2258 * could resize the dict. :-(
2259 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002260 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 n = mp->ma_used;
2262 v = PyList_New(n);
2263 if (v == NULL)
2264 return NULL;
2265 for (i = 0; i < n; i++) {
2266 item = PyTuple_New(2);
2267 if (item == NULL) {
2268 Py_DECREF(v);
2269 return NULL;
2270 }
2271 PyList_SET_ITEM(v, i, item);
2272 }
2273 if (n != mp->ma_used) {
2274 /* Durnit. The allocations caused the dict to resize.
2275 * Just start over, this shouldn't normally happen.
2276 */
2277 Py_DECREF(v);
2278 goto again;
2279 }
2280 /* Nothing we do below makes any function calls. */
Victor Stinner742da042016-09-07 17:40:12 -07002281 ep = DK_ENTRIES(mp->ma_keys);
2282 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002283 if (mp->ma_values) {
2284 value_ptr = mp->ma_values;
2285 offset = sizeof(PyObject *);
2286 }
2287 else {
2288 value_ptr = &ep[0].me_value;
2289 offset = sizeof(PyDictKeyEntry);
2290 }
2291 for (i = 0, j = 0; i < size; i++) {
2292 PyObject *value = *value_ptr;
2293 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2294 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 key = ep[i].me_key;
2296 item = PyList_GET_ITEM(v, j);
2297 Py_INCREF(key);
2298 PyTuple_SET_ITEM(item, 0, key);
2299 Py_INCREF(value);
2300 PyTuple_SET_ITEM(item, 1, value);
2301 j++;
2302 }
2303 }
2304 assert(j == n);
2305 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002306}
2307
Larry Hastings5c661892014-01-24 06:17:25 -08002308/*[clinic input]
2309@classmethod
2310dict.fromkeys
Larry Hastings5c661892014-01-24 06:17:25 -08002311 iterable: object
2312 value: object=None
2313 /
2314
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002315Create a new dictionary with keys from iterable and values set to value.
Larry Hastings5c661892014-01-24 06:17:25 -08002316[clinic start generated code]*/
2317
Larry Hastings5c661892014-01-24 06:17:25 -08002318static PyObject *
2319dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002320/*[clinic end generated code: output=8fb98e4b10384999 input=382ba4855d0f74c3]*/
Larry Hastings5c661892014-01-24 06:17:25 -08002321{
Eric Snow96c6af92015-05-29 22:21:39 -06002322 return _PyDict_FromKeys((PyObject *)type, iterable, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002323}
2324
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002325static int
Victor Stinner742da042016-09-07 17:40:12 -07002326dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
2327 const char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 PyObject *arg = NULL;
2330 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
2333 result = -1;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 else if (arg != NULL) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02002336 _Py_IDENTIFIER(keys);
2337 if (_PyObject_HasAttrId(arg, &PyId_keys))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 result = PyDict_Merge(self, arg, 1);
2339 else
2340 result = PyDict_MergeFromSeq2(self, arg, 1);
2341 }
2342 if (result == 0 && kwds != NULL) {
2343 if (PyArg_ValidateKeywordArguments(kwds))
2344 result = PyDict_Merge(self, kwds, 1);
2345 else
2346 result = -1;
2347 }
2348 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002349}
2350
Victor Stinner91f0d4a2017-01-19 12:45:06 +01002351/* Note: dict.update() uses the METH_VARARGS|METH_KEYWORDS calling convention.
2352 Using METH_FASTCALL would make dict.update(**dict2) calls slower, see the
2353 issue #29312. */
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002354static PyObject *
2355dict_update(PyObject *self, PyObject *args, PyObject *kwds)
2356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 if (dict_update_common(self, args, kwds, "update") != -1)
2358 Py_RETURN_NONE;
2359 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002360}
2361
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002362/* Update unconditionally replaces existing items.
2363 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00002364 otherwise it leaves existing items unchanged.
2365
2366 PyDict_{Update,Merge} update/merge from a mapping object.
2367
Tim Petersf582b822001-12-11 18:51:08 +00002368 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00002369 producing iterable objects of length 2.
2370*/
2371
Tim Petersf582b822001-12-11 18:51:08 +00002372int
Tim Peters1fc240e2001-10-26 05:06:50 +00002373PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
2374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 PyObject *it; /* iter(seq2) */
2376 Py_ssize_t i; /* index into seq2 of current element */
2377 PyObject *item; /* seq2[i] */
2378 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 assert(d != NULL);
2381 assert(PyDict_Check(d));
2382 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 it = PyObject_GetIter(seq2);
2385 if (it == NULL)
2386 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 for (i = 0; ; ++i) {
2389 PyObject *key, *value;
2390 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 fast = NULL;
2393 item = PyIter_Next(it);
2394 if (item == NULL) {
2395 if (PyErr_Occurred())
2396 goto Fail;
2397 break;
2398 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 /* Convert item to sequence, and verify length 2. */
2401 fast = PySequence_Fast(item, "");
2402 if (fast == NULL) {
2403 if (PyErr_ExceptionMatches(PyExc_TypeError))
2404 PyErr_Format(PyExc_TypeError,
2405 "cannot convert dictionary update "
2406 "sequence element #%zd to a sequence",
2407 i);
2408 goto Fail;
2409 }
2410 n = PySequence_Fast_GET_SIZE(fast);
2411 if (n != 2) {
2412 PyErr_Format(PyExc_ValueError,
2413 "dictionary update sequence element #%zd "
2414 "has length %zd; 2 is required",
2415 i, n);
2416 goto Fail;
2417 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 /* Update/merge with this (key, value) pair. */
2420 key = PySequence_Fast_GET_ITEM(fast, 0);
2421 value = PySequence_Fast_GET_ITEM(fast, 1);
2422 if (override || PyDict_GetItem(d, key) == NULL) {
2423 int status = PyDict_SetItem(d, key, value);
2424 if (status < 0)
2425 goto Fail;
2426 }
2427 Py_DECREF(fast);
2428 Py_DECREF(item);
2429 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 i = 0;
Victor Stinner611b0fa2016-09-14 15:02:01 +02002432 assert(_PyDict_CheckConsistency((PyDictObject *)d));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00002434Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 Py_XDECREF(item);
2436 Py_XDECREF(fast);
2437 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002438Return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 Py_DECREF(it);
2440 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00002441}
2442
doko@ubuntu.comc96df682016-10-11 08:04:02 +02002443static int
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002444dict_merge(PyObject *a, PyObject *b, int override)
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002445{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002446 PyDictObject *mp, *other;
2447 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -07002448 PyDictKeyEntry *entry, *ep0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002449
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002450 assert(0 <= override && override <= 2);
2451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 /* We accept for the argument either a concrete dictionary object,
2453 * or an abstract "mapping" object. For the former, we can do
2454 * things quite efficiently. For the latter, we only require that
2455 * PyMapping_Keys() and PyObject_GetItem() be supported.
2456 */
2457 if (a == NULL || !PyDict_Check(a) || b == NULL) {
2458 PyErr_BadInternalCall();
2459 return -1;
2460 }
2461 mp = (PyDictObject*)a;
2462 if (PyDict_Check(b)) {
2463 other = (PyDictObject*)b;
2464 if (other == mp || other->ma_used == 0)
2465 /* a.update(a) or a.update({}); nothing to do */
2466 return 0;
2467 if (mp->ma_used == 0)
2468 /* Since the target dict is empty, PyDict_GetItem()
2469 * always returns NULL. Setting override to 1
2470 * skips the unnecessary test.
2471 */
2472 override = 1;
2473 /* Do one big resize at the start, rather than
2474 * incrementally resizing as we insert new items. Expect
2475 * that there will be no (or few) overlapping keys.
2476 */
INADA Naokib1152be2016-10-27 19:26:50 +09002477 if (USABLE_FRACTION(mp->ma_keys->dk_size) < other->ma_used) {
2478 if (dictresize(mp, ESTIMATE_SIZE(mp->ma_used + other->ma_used))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 return -1;
INADA Naokib1152be2016-10-27 19:26:50 +09002480 }
2481 }
Victor Stinner742da042016-09-07 17:40:12 -07002482 ep0 = DK_ENTRIES(other->ma_keys);
2483 for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002484 PyObject *key, *value;
2485 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002486 entry = &ep0[i];
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002487 key = entry->me_key;
2488 hash = entry->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002489 if (other->ma_values)
2490 value = other->ma_values[i];
2491 else
2492 value = entry->me_value;
2493
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002494 if (value != NULL) {
2495 int err = 0;
2496 Py_INCREF(key);
2497 Py_INCREF(value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002498 if (override == 1)
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002499 err = insertdict(mp, key, hash, value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002500 else if (_PyDict_GetItem_KnownHash(a, key, hash) == NULL) {
2501 if (PyErr_Occurred()) {
2502 Py_DECREF(value);
2503 Py_DECREF(key);
2504 return -1;
2505 }
2506 err = insertdict(mp, key, hash, value);
2507 }
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002508 else if (override != 0) {
2509 _PyErr_SetKeyError(key);
2510 Py_DECREF(value);
2511 Py_DECREF(key);
2512 return -1;
2513 }
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002514 Py_DECREF(value);
2515 Py_DECREF(key);
2516 if (err != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 return -1;
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002518
Victor Stinner742da042016-09-07 17:40:12 -07002519 if (n != other->ma_keys->dk_nentries) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002520 PyErr_SetString(PyExc_RuntimeError,
2521 "dict mutated during update");
2522 return -1;
2523 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 }
2525 }
2526 }
2527 else {
2528 /* Do it the generic, slower way */
2529 PyObject *keys = PyMapping_Keys(b);
2530 PyObject *iter;
2531 PyObject *key, *value;
2532 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 if (keys == NULL)
2535 /* Docstring says this is equivalent to E.keys() so
2536 * if E doesn't have a .keys() method we want
2537 * AttributeError to percolate up. Might as well
2538 * do the same for any other error.
2539 */
2540 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 iter = PyObject_GetIter(keys);
2543 Py_DECREF(keys);
2544 if (iter == NULL)
2545 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002548 if (override != 1 && PyDict_GetItem(a, key) != NULL) {
2549 if (override != 0) {
2550 _PyErr_SetKeyError(key);
2551 Py_DECREF(key);
2552 Py_DECREF(iter);
2553 return -1;
2554 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 Py_DECREF(key);
2556 continue;
2557 }
2558 value = PyObject_GetItem(b, key);
2559 if (value == NULL) {
2560 Py_DECREF(iter);
2561 Py_DECREF(key);
2562 return -1;
2563 }
2564 status = PyDict_SetItem(a, key, value);
2565 Py_DECREF(key);
2566 Py_DECREF(value);
2567 if (status < 0) {
2568 Py_DECREF(iter);
2569 return -1;
2570 }
2571 }
2572 Py_DECREF(iter);
2573 if (PyErr_Occurred())
2574 /* Iterator completed, via error */
2575 return -1;
2576 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02002577 assert(_PyDict_CheckConsistency((PyDictObject *)a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002579}
2580
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002581int
2582PyDict_Update(PyObject *a, PyObject *b)
2583{
2584 return dict_merge(a, b, 1);
2585}
2586
2587int
2588PyDict_Merge(PyObject *a, PyObject *b, int override)
2589{
2590 /* XXX Deprecate override not in (0, 1). */
2591 return dict_merge(a, b, override != 0);
2592}
2593
2594int
2595_PyDict_MergeEx(PyObject *a, PyObject *b, int override)
2596{
2597 return dict_merge(a, b, override);
2598}
2599
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002600static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002601dict_copy(PyDictObject *mp)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002604}
2605
2606PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002607PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 PyObject *copy;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002610 PyDictObject *mp;
2611 Py_ssize_t i, n;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 if (o == NULL || !PyDict_Check(o)) {
2614 PyErr_BadInternalCall();
2615 return NULL;
2616 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002617 mp = (PyDictObject *)o;
2618 if (_PyDict_HasSplitTable(mp)) {
2619 PyDictObject *split_copy;
Victor Stinner742da042016-09-07 17:40:12 -07002620 Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
2621 PyObject **newvalues;
2622 newvalues = new_values(size);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002623 if (newvalues == NULL)
2624 return PyErr_NoMemory();
2625 split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
2626 if (split_copy == NULL) {
2627 free_values(newvalues);
2628 return NULL;
2629 }
2630 split_copy->ma_values = newvalues;
2631 split_copy->ma_keys = mp->ma_keys;
2632 split_copy->ma_used = mp->ma_used;
2633 DK_INCREF(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002634 for (i = 0, n = size; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002635 PyObject *value = mp->ma_values[i];
2636 Py_XINCREF(value);
2637 split_copy->ma_values[i] = value;
2638 }
Benjamin Peterson7ce67e42012-04-24 10:32:57 -04002639 if (_PyObject_GC_IS_TRACKED(mp))
2640 _PyObject_GC_TRACK(split_copy);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002641 return (PyObject *)split_copy;
2642 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 copy = PyDict_New();
2644 if (copy == NULL)
2645 return NULL;
2646 if (PyDict_Merge(copy, o, 1) == 0)
2647 return copy;
2648 Py_DECREF(copy);
2649 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002650}
2651
Martin v. Löwis18e16552006-02-15 17:27:45 +00002652Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00002653PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00002654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 if (mp == NULL || !PyDict_Check(mp)) {
2656 PyErr_BadInternalCall();
2657 return -1;
2658 }
2659 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00002660}
2661
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002662PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002663PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 if (mp == NULL || !PyDict_Check(mp)) {
2666 PyErr_BadInternalCall();
2667 return NULL;
2668 }
2669 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002670}
2671
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002672PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002673PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 if (mp == NULL || !PyDict_Check(mp)) {
2676 PyErr_BadInternalCall();
2677 return NULL;
2678 }
2679 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002680}
2681
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002682PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002683PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 if (mp == NULL || !PyDict_Check(mp)) {
2686 PyErr_BadInternalCall();
2687 return NULL;
2688 }
2689 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002690}
2691
Tim Peterse63415e2001-05-08 04:38:29 +00002692/* Return 1 if dicts equal, 0 if not, -1 if error.
2693 * Gets out as soon as any difference is detected.
2694 * Uses only Py_EQ comparison.
2695 */
2696static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002697dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00002698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00002700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 if (a->ma_used != b->ma_used)
2702 /* can't be equal if # of entries differ */
2703 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Victor Stinner742da042016-09-07 17:40:12 -07002705 for (i = 0; i < a->ma_keys->dk_nentries; i++) {
2706 PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002707 PyObject *aval;
2708 if (a->ma_values)
2709 aval = a->ma_values[i];
2710 else
2711 aval = ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 if (aval != NULL) {
2713 int cmp;
2714 PyObject *bval;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002715 PyObject *key = ep->me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 /* temporarily bump aval's refcount to ensure it stays
2717 alive until we're done with it */
2718 Py_INCREF(aval);
2719 /* ditto for key */
2720 Py_INCREF(key);
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002721 /* reuse the known hash value */
INADA Naokiba609772016-12-07 20:41:42 +09002722 b->ma_keys->dk_lookup(b, key, ep->me_hash, &bval, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 Py_DECREF(key);
2724 if (bval == NULL) {
2725 Py_DECREF(aval);
2726 if (PyErr_Occurred())
2727 return -1;
2728 return 0;
2729 }
2730 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
2731 Py_DECREF(aval);
2732 if (cmp <= 0) /* error or not equal */
2733 return cmp;
2734 }
2735 }
2736 return 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002737}
Tim Peterse63415e2001-05-08 04:38:29 +00002738
2739static PyObject *
2740dict_richcompare(PyObject *v, PyObject *w, int op)
2741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 int cmp;
2743 PyObject *res;
Tim Peterse63415e2001-05-08 04:38:29 +00002744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 if (!PyDict_Check(v) || !PyDict_Check(w)) {
2746 res = Py_NotImplemented;
2747 }
2748 else if (op == Py_EQ || op == Py_NE) {
2749 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
2750 if (cmp < 0)
2751 return NULL;
2752 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
2753 }
2754 else
2755 res = Py_NotImplemented;
2756 Py_INCREF(res);
2757 return res;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002758}
Tim Peterse63415e2001-05-08 04:38:29 +00002759
Larry Hastings61272b72014-01-07 12:41:53 -08002760/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002761
2762@coexist
2763dict.__contains__
2764
2765 key: object
2766 /
2767
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002768True if the dictionary has the specified key, else False.
Larry Hastings61272b72014-01-07 12:41:53 -08002769[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002770
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002771static PyObject *
Larry Hastingsc2047262014-01-25 20:43:29 -08002772dict___contains__(PyDictObject *self, PyObject *key)
Serhiy Storchaka19d25972017-02-04 08:05:07 +02002773/*[clinic end generated code: output=a3d03db709ed6e6b input=fe1cb42ad831e820]*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002774{
Larry Hastingsc2047262014-01-25 20:43:29 -08002775 register PyDictObject *mp = self;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002776 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002777 Py_ssize_t ix;
INADA Naokiba609772016-12-07 20:41:42 +09002778 PyObject *value;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002781 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 hash = PyObject_Hash(key);
2783 if (hash == -1)
2784 return NULL;
2785 }
INADA Naokiba609772016-12-07 20:41:42 +09002786 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07002787 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002789 if (ix == DKIX_EMPTY || value == NULL)
Victor Stinner742da042016-09-07 17:40:12 -07002790 Py_RETURN_FALSE;
2791 Py_RETURN_TRUE;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002792}
2793
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002794/*[clinic input]
2795dict.get
2796
2797 key: object
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002798 default: object = None
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002799 /
2800
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002801Return the value for key if key is in the dictionary, else default.
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002802[clinic start generated code]*/
2803
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002804static PyObject *
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002805dict_get_impl(PyDictObject *self, PyObject *key, PyObject *default_value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002806/*[clinic end generated code: output=bba707729dee05bf input=279ddb5790b6b107]*/
Barry Warsawc38c5da1997-10-06 17:49:20 +00002807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002809 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002810 Py_ssize_t ix;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002813 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 hash = PyObject_Hash(key);
2815 if (hash == -1)
2816 return NULL;
2817 }
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002818 ix = (self->ma_keys->dk_lookup) (self, key, hash, &val, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07002819 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002821 if (ix == DKIX_EMPTY || val == NULL) {
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002822 val = default_value;
INADA Naokiba609772016-12-07 20:41:42 +09002823 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 Py_INCREF(val);
2825 return val;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002826}
2827
Benjamin Peterson00e98862013-03-07 22:16:29 -05002828PyObject *
2829PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
Guido van Rossum164452c2000-08-08 16:12:54 +00002830{
Benjamin Peterson00e98862013-03-07 22:16:29 -05002831 PyDictObject *mp = (PyDictObject *)d;
INADA Naoki93f26f72016-11-02 18:45:16 +09002832 PyObject *value;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002833 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002834 Py_ssize_t hashpos, ix;
Guido van Rossum164452c2000-08-08 16:12:54 +00002835
Benjamin Peterson00e98862013-03-07 22:16:29 -05002836 if (!PyDict_Check(d)) {
2837 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 return NULL;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002839 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002842 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 hash = PyObject_Hash(key);
2844 if (hash == -1)
2845 return NULL;
2846 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002847
2848 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
2849 if (insertion_resize(mp) < 0)
2850 return NULL;
2851 }
2852
INADA Naokiba609772016-12-07 20:41:42 +09002853 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, &hashpos);
Victor Stinner742da042016-09-07 17:40:12 -07002854 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 return NULL;
INADA Naoki93f26f72016-11-02 18:45:16 +09002856
2857 if (_PyDict_HasSplitTable(mp) &&
INADA Naokiba609772016-12-07 20:41:42 +09002858 ((ix >= 0 && value == NULL && mp->ma_used != ix) ||
INADA Naoki93f26f72016-11-02 18:45:16 +09002859 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
2860 if (insertion_resize(mp) < 0) {
2861 return NULL;
2862 }
INADA Naokiba609772016-12-07 20:41:42 +09002863 hashpos = find_empty_slot(mp->ma_keys, key, hash);
INADA Naoki93f26f72016-11-02 18:45:16 +09002864 ix = DKIX_EMPTY;
2865 }
2866
2867 if (ix == DKIX_EMPTY) {
2868 PyDictKeyEntry *ep, *ep0;
2869 value = defaultobj;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002870 if (mp->ma_keys->dk_usable <= 0) {
Victor Stinner3c336c52016-09-12 14:17:40 +02002871 if (insertion_resize(mp) < 0) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002872 return NULL;
Victor Stinner3c336c52016-09-12 14:17:40 +02002873 }
INADA Naokiba609772016-12-07 20:41:42 +09002874 hashpos = find_empty_slot(mp->ma_keys, key, hash);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002875 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002876 ep0 = DK_ENTRIES(mp->ma_keys);
2877 ep = &ep0[mp->ma_keys->dk_nentries];
2878 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
Benjamin Petersonb1efa532013-03-04 09:47:50 -05002879 Py_INCREF(key);
INADA Naoki93f26f72016-11-02 18:45:16 +09002880 Py_INCREF(value);
2881 MAINTAIN_TRACKING(mp, key, value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002882 ep->me_key = key;
2883 ep->me_hash = hash;
INADA Naokiba609772016-12-07 20:41:42 +09002884 if (_PyDict_HasSplitTable(mp)) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002885 assert(mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
2886 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Victor Stinner742da042016-09-07 17:40:12 -07002887 }
2888 else {
INADA Naoki93f26f72016-11-02 18:45:16 +09002889 ep->me_value = value;
Victor Stinner742da042016-09-07 17:40:12 -07002890 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002891 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07002892 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naoki93f26f72016-11-02 18:45:16 +09002893 mp->ma_keys->dk_usable--;
2894 mp->ma_keys->dk_nentries++;
2895 assert(mp->ma_keys->dk_usable >= 0);
2896 }
INADA Naokiba609772016-12-07 20:41:42 +09002897 else if (value == NULL) {
INADA Naoki93f26f72016-11-02 18:45:16 +09002898 value = defaultobj;
2899 assert(_PyDict_HasSplitTable(mp));
2900 assert(ix == mp->ma_used);
2901 Py_INCREF(value);
2902 MAINTAIN_TRACKING(mp, key, value);
INADA Naokiba609772016-12-07 20:41:42 +09002903 mp->ma_values[ix] = value;
INADA Naoki93f26f72016-11-02 18:45:16 +09002904 mp->ma_used++;
2905 mp->ma_version_tag = DICT_NEXT_VERSION();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 }
INADA Naoki93f26f72016-11-02 18:45:16 +09002907
2908 assert(_PyDict_CheckConsistency(mp));
2909 return value;
Guido van Rossum164452c2000-08-08 16:12:54 +00002910}
2911
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002912/*[clinic input]
2913dict.setdefault
2914
2915 key: object
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002916 default: object = None
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002917 /
2918
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002919Insert key with a value of default if key is not in the dictionary.
2920
2921Return the value for key if key is in the dictionary, else default.
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002922[clinic start generated code]*/
2923
Benjamin Peterson00e98862013-03-07 22:16:29 -05002924static PyObject *
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002925dict_setdefault_impl(PyDictObject *self, PyObject *key,
2926 PyObject *default_value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002927/*[clinic end generated code: output=f8c1101ebf69e220 input=0f063756e815fd9d]*/
Benjamin Peterson00e98862013-03-07 22:16:29 -05002928{
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01002929 PyObject *val;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002930
Serhiy Storchaka48088ee2017-01-19 19:00:30 +02002931 val = PyDict_SetDefault((PyObject *)self, key, default_value);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002932 Py_XINCREF(val);
2933 return val;
2934}
Guido van Rossum164452c2000-08-08 16:12:54 +00002935
2936static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002937dict_clear(PyDictObject *mp)
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 PyDict_Clear((PyObject *)mp);
2940 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002941}
2942
Guido van Rossumba6ab842000-12-12 22:02:18 +00002943static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002944dict_pop(PyDictObject *mp, PyObject *args)
Guido van Rossume027d982002-04-12 15:11:59 +00002945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 PyObject *key, *deflt = NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00002947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
2949 return NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06002950
Yury Selivanov684ef2c2016-10-28 19:01:21 -04002951 return _PyDict_Pop((PyObject*)mp, key, deflt);
Guido van Rossume027d982002-04-12 15:11:59 +00002952}
2953
2954static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002955dict_popitem(PyDictObject *mp)
Guido van Rossumba6ab842000-12-12 22:02:18 +00002956{
Victor Stinner742da042016-09-07 17:40:12 -07002957 Py_ssize_t i, j;
2958 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 PyObject *res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 /* Allocate the result tuple before checking the size. Believe it
2962 * or not, this allocation could trigger a garbage collection which
2963 * could empty the dict, so if we checked the size first and that
2964 * happened, the result would be an infinite loop (searching for an
2965 * entry that no longer exists). Note that the usual popitem()
2966 * idiom is "while d: k, v = d.popitem()". so needing to throw the
2967 * tuple away if the dict *is* empty isn't a significant
2968 * inefficiency -- possible, but unlikely in practice.
2969 */
2970 res = PyTuple_New(2);
2971 if (res == NULL)
2972 return NULL;
2973 if (mp->ma_used == 0) {
2974 Py_DECREF(res);
2975 PyErr_SetString(PyExc_KeyError,
2976 "popitem(): dictionary is empty");
2977 return NULL;
2978 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002979 /* Convert split table to combined table */
2980 if (mp->ma_keys->dk_lookup == lookdict_split) {
2981 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
2982 Py_DECREF(res);
2983 return NULL;
2984 }
2985 }
2986 ENSURE_ALLOWS_DELETIONS(mp);
Victor Stinner742da042016-09-07 17:40:12 -07002987
2988 /* Pop last item */
2989 ep0 = DK_ENTRIES(mp->ma_keys);
2990 i = mp->ma_keys->dk_nentries - 1;
2991 while (i >= 0 && ep0[i].me_value == NULL) {
2992 i--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 }
Victor Stinner742da042016-09-07 17:40:12 -07002994 assert(i >= 0);
2995
2996 ep = &ep0[i];
2997 j = lookdict_index(mp->ma_keys, ep->me_hash, i);
2998 assert(j >= 0);
2999 assert(dk_get_index(mp->ma_keys, j) == i);
3000 dk_set_index(mp->ma_keys, j, DKIX_DUMMY);
3001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 PyTuple_SET_ITEM(res, 0, ep->me_key);
3003 PyTuple_SET_ITEM(res, 1, ep->me_value);
Victor Stinner742da042016-09-07 17:40:12 -07003004 ep->me_key = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 ep->me_value = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07003006 /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
3007 mp->ma_keys->dk_nentries = i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07003009 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner611b0fa2016-09-14 15:02:01 +02003010 assert(_PyDict_CheckConsistency(mp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 return res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00003012}
3013
Jeremy Hylton8caad492000-06-23 14:18:11 +00003014static int
3015dict_traverse(PyObject *op, visitproc visit, void *arg)
3016{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003017 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson55f44522016-09-05 12:12:59 -07003018 PyDictKeysObject *keys = mp->ma_keys;
Serhiy Storchaka46825d22016-09-26 21:29:34 +03003019 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Victor Stinner742da042016-09-07 17:40:12 -07003020 Py_ssize_t i, n = keys->dk_nentries;
3021
Benjamin Peterson55f44522016-09-05 12:12:59 -07003022 if (keys->dk_lookup == lookdict) {
3023 for (i = 0; i < n; i++) {
3024 if (entries[i].me_value != NULL) {
3025 Py_VISIT(entries[i].me_value);
3026 Py_VISIT(entries[i].me_key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003027 }
3028 }
Victor Stinner742da042016-09-07 17:40:12 -07003029 }
3030 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003031 if (mp->ma_values != NULL) {
Benjamin Peterson55f44522016-09-05 12:12:59 -07003032 for (i = 0; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003033 Py_VISIT(mp->ma_values[i]);
3034 }
3035 }
3036 else {
Benjamin Peterson55f44522016-09-05 12:12:59 -07003037 for (i = 0; i < n; i++) {
3038 Py_VISIT(entries[i].me_value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003039 }
3040 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 }
3042 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00003043}
3044
3045static int
3046dict_tp_clear(PyObject *op)
3047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 PyDict_Clear(op);
3049 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00003050}
3051
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003052static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003053
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003054Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003055_PyDict_SizeOf(PyDictObject *mp)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003056{
Victor Stinner742da042016-09-07 17:40:12 -07003057 Py_ssize_t size, usable, res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003058
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003059 size = DK_SIZE(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07003060 usable = USABLE_FRACTION(size);
3061
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02003062 res = _PyObject_SIZE(Py_TYPE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003063 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07003064 res += usable * sizeof(PyObject*);
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003065 /* If the dictionary is split, the keys portion is accounted-for
3066 in the type object. */
3067 if (mp->ma_keys->dk_refcnt == 1)
Victor Stinner98ee9d52016-09-08 09:33:56 -07003068 res += (sizeof(PyDictKeysObject)
3069 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
3070 + DK_IXSIZE(mp->ma_keys) * size
3071 + sizeof(PyDictKeyEntry) * usable);
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003072 return res;
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02003073}
3074
3075Py_ssize_t
3076_PyDict_KeysSize(PyDictKeysObject *keys)
3077{
Victor Stinner98ee9d52016-09-08 09:33:56 -07003078 return (sizeof(PyDictKeysObject)
3079 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
3080 + DK_IXSIZE(keys) * DK_SIZE(keys)
3081 + USABLE_FRACTION(DK_SIZE(keys)) * sizeof(PyDictKeyEntry));
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003082}
3083
doko@ubuntu.com17210f52016-01-14 14:04:59 +01003084static PyObject *
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003085dict_sizeof(PyDictObject *mp)
3086{
3087 return PyLong_FromSsize_t(_PyDict_SizeOf(mp));
3088}
3089
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003090PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
3091
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003092PyDoc_STRVAR(sizeof__doc__,
3093"D.__sizeof__() -> size of D in memory, in bytes");
3094
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003095PyDoc_STRVAR(pop__doc__,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00003096"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00003097If key is not found, d is returned if given, otherwise KeyError is raised");
Guido van Rossume027d982002-04-12 15:11:59 +00003098
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003099PyDoc_STRVAR(popitem__doc__,
Tim Petersf7f88b12000-12-13 23:18:45 +00003100"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000031012-tuple; but raise KeyError if D is empty.");
Tim Petersf7f88b12000-12-13 23:18:45 +00003102
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003103PyDoc_STRVAR(update__doc__,
Brett Cannonf2754162013-05-11 14:46:48 -04003104"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n\
3105If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]\n\
3106If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n\
3107In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00003108
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003109PyDoc_STRVAR(clear__doc__,
3110"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00003111
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003112PyDoc_STRVAR(copy__doc__,
3113"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00003114
Guido van Rossumb90c8482007-02-10 01:11:45 +00003115/* Forward */
3116static PyObject *dictkeys_new(PyObject *);
3117static PyObject *dictitems_new(PyObject *);
3118static PyObject *dictvalues_new(PyObject *);
3119
Guido van Rossum45c85d12007-07-27 16:31:40 +00003120PyDoc_STRVAR(keys__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 "D.keys() -> a set-like object providing a view on D's keys");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003122PyDoc_STRVAR(items__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 "D.items() -> a set-like object providing a view on D's items");
Guido van Rossum45c85d12007-07-27 16:31:40 +00003124PyDoc_STRVAR(values__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 "D.values() -> an object providing a view on D's values");
Guido van Rossumb90c8482007-02-10 01:11:45 +00003126
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003127static PyMethodDef mapp_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -07003128 DICT___CONTAINS___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
3130 getitem__doc__},
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02003131 {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 sizeof__doc__},
Victor Stinner7dc6a5f2017-01-19 12:37:13 +01003133 DICT_GET_METHODDEF
3134 DICT_SETDEFAULT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 {"pop", (PyCFunction)dict_pop, METH_VARARGS,
3136 pop__doc__},
3137 {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
3138 popitem__doc__},
3139 {"keys", (PyCFunction)dictkeys_new, METH_NOARGS,
3140 keys__doc__},
3141 {"items", (PyCFunction)dictitems_new, METH_NOARGS,
3142 items__doc__},
3143 {"values", (PyCFunction)dictvalues_new, METH_NOARGS,
3144 values__doc__},
3145 {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
3146 update__doc__},
Larry Hastings5c661892014-01-24 06:17:25 -08003147 DICT_FROMKEYS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
3149 clear__doc__},
3150 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
3151 copy__doc__},
3152 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003153};
3154
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00003155/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00003156int
3157PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003158{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003159 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07003160 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09003162 PyObject *value;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003165 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 hash = PyObject_Hash(key);
3167 if (hash == -1)
3168 return -1;
3169 }
INADA Naokiba609772016-12-07 20:41:42 +09003170 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07003171 if (ix == DKIX_ERROR)
3172 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09003173 return (ix != DKIX_EMPTY && value != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003174}
3175
Thomas Wouterscf297e42007-02-23 15:07:44 +00003176/* Internal version of PyDict_Contains used when the hash value is already known */
3177int
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003178_PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00003179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09003181 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -07003182 Py_ssize_t ix;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003183
INADA Naokiba609772016-12-07 20:41:42 +09003184 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07003185 if (ix == DKIX_ERROR)
3186 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09003187 return (ix != DKIX_EMPTY && value != NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00003188}
3189
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003190/* Hack to implement "key in dict" */
3191static PySequenceMethods dict_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 0, /* sq_length */
3193 0, /* sq_concat */
3194 0, /* sq_repeat */
3195 0, /* sq_item */
3196 0, /* sq_slice */
3197 0, /* sq_ass_item */
3198 0, /* sq_ass_slice */
3199 PyDict_Contains, /* sq_contains */
3200 0, /* sq_inplace_concat */
3201 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00003202};
3203
Guido van Rossum09e563a2001-05-01 12:10:21 +00003204static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003205dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 PyObject *self;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003208 PyDictObject *d;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 assert(type != NULL && type->tp_alloc != NULL);
3211 self = type->tp_alloc(type, 0);
Victor Stinnera9f61a52013-07-16 22:17:26 +02003212 if (self == NULL)
3213 return NULL;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003214 d = (PyDictObject *)self;
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003215
Victor Stinnera9f61a52013-07-16 22:17:26 +02003216 /* The object has been implicitly tracked by tp_alloc */
3217 if (type == &PyDict_Type)
3218 _PyObject_GC_UNTRACK(d);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003219
3220 d->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07003221 d->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07003222 d->ma_keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003223 if (d->ma_keys == NULL) {
3224 Py_DECREF(self);
3225 return NULL;
3226 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02003227 assert(_PyDict_CheckConsistency(d));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 return self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003229}
3230
Tim Peters25786c02001-09-02 08:22:48 +00003231static int
3232dict_init(PyObject *self, PyObject *args, PyObject *kwds)
3233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00003235}
3236
Tim Peters6d6c1a32001-08-02 04:15:00 +00003237static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003238dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00003239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003241}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003242
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003243PyDoc_STRVAR(dictionary_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00003244"dict() -> new empty dictionary\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00003245"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003246" (key, value) pairs\n"
3247"dict(iterable) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00003248" d = {}\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003249" for k, v in iterable:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00003250" d[k] = v\n"
3251"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
3252" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00003253
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003254PyTypeObject PyDict_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3256 "dict",
3257 sizeof(PyDictObject),
3258 0,
3259 (destructor)dict_dealloc, /* tp_dealloc */
3260 0, /* tp_print */
3261 0, /* tp_getattr */
3262 0, /* tp_setattr */
3263 0, /* tp_reserved */
3264 (reprfunc)dict_repr, /* tp_repr */
3265 0, /* tp_as_number */
3266 &dict_as_sequence, /* tp_as_sequence */
3267 &dict_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003268 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 0, /* tp_call */
3270 0, /* tp_str */
3271 PyObject_GenericGetAttr, /* tp_getattro */
3272 0, /* tp_setattro */
3273 0, /* tp_as_buffer */
3274 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3275 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
3276 dictionary_doc, /* tp_doc */
3277 dict_traverse, /* tp_traverse */
3278 dict_tp_clear, /* tp_clear */
3279 dict_richcompare, /* tp_richcompare */
3280 0, /* tp_weaklistoffset */
3281 (getiterfunc)dict_iter, /* tp_iter */
3282 0, /* tp_iternext */
3283 mapp_methods, /* tp_methods */
3284 0, /* tp_members */
3285 0, /* tp_getset */
3286 0, /* tp_base */
3287 0, /* tp_dict */
3288 0, /* tp_descr_get */
3289 0, /* tp_descr_set */
3290 0, /* tp_dictoffset */
3291 dict_init, /* tp_init */
3292 PyType_GenericAlloc, /* tp_alloc */
3293 dict_new, /* tp_new */
3294 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003295};
3296
Victor Stinner3c1e4812012-03-26 22:10:51 +02003297PyObject *
3298_PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
3299{
3300 PyObject *kv;
3301 kv = _PyUnicode_FromId(key); /* borrowed */
Victor Stinner5b3b1002013-07-22 23:50:57 +02003302 if (kv == NULL) {
3303 PyErr_Clear();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003304 return NULL;
Victor Stinner5b3b1002013-07-22 23:50:57 +02003305 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003306 return PyDict_GetItem(dp, kv);
3307}
3308
Guido van Rossum3cca2451997-05-16 14:23:33 +00003309/* For backward compatibility with old dictionary interface */
3310
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003311PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003312PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 PyObject *kv, *rv;
3315 kv = PyUnicode_FromString(key);
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003316 if (kv == NULL) {
3317 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 return NULL;
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003319 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 rv = PyDict_GetItem(v, kv);
3321 Py_DECREF(kv);
3322 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003323}
3324
3325int
Victor Stinner3c1e4812012-03-26 22:10:51 +02003326_PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
3327{
3328 PyObject *kv;
3329 kv = _PyUnicode_FromId(key); /* borrowed */
3330 if (kv == NULL)
3331 return -1;
3332 return PyDict_SetItem(v, kv, item);
3333}
3334
3335int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003336PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 PyObject *kv;
3339 int err;
3340 kv = PyUnicode_FromString(key);
3341 if (kv == NULL)
3342 return -1;
3343 PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
3344 err = PyDict_SetItem(v, kv, item);
3345 Py_DECREF(kv);
3346 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003347}
3348
3349int
Victor Stinner5fd2e5a2013-11-06 18:58:22 +01003350_PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
3351{
3352 PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
3353 if (kv == NULL)
3354 return -1;
3355 return PyDict_DelItem(v, kv);
3356}
3357
3358int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003359PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003361 PyObject *kv;
3362 int err;
3363 kv = PyUnicode_FromString(key);
3364 if (kv == NULL)
3365 return -1;
3366 err = PyDict_DelItem(v, kv);
3367 Py_DECREF(kv);
3368 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003369}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003370
Raymond Hettinger019a1482004-03-18 02:41:19 +00003371/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003372
3373typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 PyObject_HEAD
3375 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
3376 Py_ssize_t di_used;
3377 Py_ssize_t di_pos;
3378 PyObject* di_result; /* reusable result tuple for iteritems */
3379 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003380} dictiterobject;
3381
3382static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003383dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 dictiterobject *di;
3386 di = PyObject_GC_New(dictiterobject, itertype);
3387 if (di == NULL)
3388 return NULL;
3389 Py_INCREF(dict);
3390 di->di_dict = dict;
3391 di->di_used = dict->ma_used;
3392 di->di_pos = 0;
3393 di->len = dict->ma_used;
3394 if (itertype == &PyDictIterItem_Type) {
3395 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
3396 if (di->di_result == NULL) {
3397 Py_DECREF(di);
3398 return NULL;
3399 }
3400 }
3401 else
3402 di->di_result = NULL;
3403 _PyObject_GC_TRACK(di);
3404 return (PyObject *)di;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003405}
3406
3407static void
3408dictiter_dealloc(dictiterobject *di)
3409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 Py_XDECREF(di->di_dict);
3411 Py_XDECREF(di->di_result);
3412 PyObject_GC_Del(di);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003413}
3414
3415static int
3416dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
3417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 Py_VISIT(di->di_dict);
3419 Py_VISIT(di->di_result);
3420 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003421}
3422
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003423static PyObject *
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003424dictiter_len(dictiterobject *di)
3425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 Py_ssize_t len = 0;
3427 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
3428 len = di->len;
3429 return PyLong_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003430}
3431
Guido van Rossumb90c8482007-02-10 01:11:45 +00003432PyDoc_STRVAR(length_hint_doc,
3433 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003434
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003435static PyObject *
3436dictiter_reduce(dictiterobject *di);
3437
3438PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3439
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003440static PyMethodDef dictiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS,
3442 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003443 {"__reduce__", (PyCFunction)dictiter_reduce, METH_NOARGS,
3444 reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003445 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003446};
3447
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003448static PyObject*
3449dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00003450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 PyObject *key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003452 Py_ssize_t i;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003453 PyDictKeysObject *k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 PyDictObject *d = di->di_dict;
Guido van Rossum213c7a62001-04-23 14:08:49 +00003455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 if (d == NULL)
3457 return NULL;
3458 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00003459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 if (di->di_used != d->ma_used) {
3461 PyErr_SetString(PyExc_RuntimeError,
3462 "dictionary changed size during iteration");
3463 di->di_used = -1; /* Make this state sticky */
3464 return NULL;
3465 }
Guido van Rossum2147df72002-07-16 20:30:22 +00003466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 i = di->di_pos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003468 k = d->ma_keys;
INADA Naokica2d8be2016-11-04 16:59:10 +09003469 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003470 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003471 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003472 goto fail;
3473 key = DK_ENTRIES(k)[i].me_key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003474 assert(d->ma_values[i] != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003475 }
3476 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003477 Py_ssize_t n = k->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003478 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
3479 while (i < n && entry_ptr->me_value == NULL) {
3480 entry_ptr++;
3481 i++;
3482 }
3483 if (i >= n)
3484 goto fail;
3485 key = entry_ptr->me_key;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003486 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 di->di_pos = i+1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 di->len--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 Py_INCREF(key);
3490 return key;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003491
3492fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003494 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003496}
3497
Raymond Hettinger019a1482004-03-18 02:41:19 +00003498PyTypeObject PyDictIterKey_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3500 "dict_keyiterator", /* tp_name */
3501 sizeof(dictiterobject), /* tp_basicsize */
3502 0, /* tp_itemsize */
3503 /* methods */
3504 (destructor)dictiter_dealloc, /* tp_dealloc */
3505 0, /* tp_print */
3506 0, /* tp_getattr */
3507 0, /* tp_setattr */
3508 0, /* tp_reserved */
3509 0, /* tp_repr */
3510 0, /* tp_as_number */
3511 0, /* tp_as_sequence */
3512 0, /* tp_as_mapping */
3513 0, /* tp_hash */
3514 0, /* tp_call */
3515 0, /* tp_str */
3516 PyObject_GenericGetAttr, /* tp_getattro */
3517 0, /* tp_setattro */
3518 0, /* tp_as_buffer */
3519 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3520 0, /* tp_doc */
3521 (traverseproc)dictiter_traverse, /* tp_traverse */
3522 0, /* tp_clear */
3523 0, /* tp_richcompare */
3524 0, /* tp_weaklistoffset */
3525 PyObject_SelfIter, /* tp_iter */
3526 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
3527 dictiter_methods, /* tp_methods */
3528 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003529};
3530
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003531static PyObject *
3532dictiter_iternextvalue(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 PyObject *value;
INADA Naokica2d8be2016-11-04 16:59:10 +09003535 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 if (d == NULL)
3539 return NULL;
3540 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003542 if (di->di_used != d->ma_used) {
3543 PyErr_SetString(PyExc_RuntimeError,
3544 "dictionary changed size during iteration");
3545 di->di_used = -1; /* Make this state sticky */
3546 return NULL;
3547 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 i = di->di_pos;
INADA Naokica2d8be2016-11-04 16:59:10 +09003550 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003551 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003552 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003553 goto fail;
INADA Naokica2d8be2016-11-04 16:59:10 +09003554 value = d->ma_values[i];
3555 assert(value != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003556 }
3557 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003558 Py_ssize_t n = d->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003559 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3560 while (i < n && entry_ptr->me_value == NULL) {
3561 entry_ptr++;
3562 i++;
3563 }
3564 if (i >= n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 goto fail;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003566 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 }
3568 di->di_pos = i+1;
3569 di->len--;
3570 Py_INCREF(value);
3571 return value;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003572
3573fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003575 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003577}
3578
3579PyTypeObject PyDictIterValue_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3581 "dict_valueiterator", /* tp_name */
3582 sizeof(dictiterobject), /* tp_basicsize */
3583 0, /* tp_itemsize */
3584 /* methods */
3585 (destructor)dictiter_dealloc, /* tp_dealloc */
3586 0, /* tp_print */
3587 0, /* tp_getattr */
3588 0, /* tp_setattr */
3589 0, /* tp_reserved */
3590 0, /* tp_repr */
3591 0, /* tp_as_number */
3592 0, /* tp_as_sequence */
3593 0, /* tp_as_mapping */
3594 0, /* tp_hash */
3595 0, /* tp_call */
3596 0, /* tp_str */
3597 PyObject_GenericGetAttr, /* tp_getattro */
3598 0, /* tp_setattro */
3599 0, /* tp_as_buffer */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003600 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 0, /* tp_doc */
3602 (traverseproc)dictiter_traverse, /* tp_traverse */
3603 0, /* tp_clear */
3604 0, /* tp_richcompare */
3605 0, /* tp_weaklistoffset */
3606 PyObject_SelfIter, /* tp_iter */
3607 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
3608 dictiter_methods, /* tp_methods */
3609 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003610};
3611
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003612static PyObject *
3613dictiter_iternextitem(dictiterobject *di)
Raymond Hettinger019a1482004-03-18 02:41:19 +00003614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 PyObject *key, *value, *result = di->di_result;
INADA Naokica2d8be2016-11-04 16:59:10 +09003616 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 if (d == NULL)
3620 return NULL;
3621 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003623 if (di->di_used != d->ma_used) {
3624 PyErr_SetString(PyExc_RuntimeError,
3625 "dictionary changed size during iteration");
3626 di->di_used = -1; /* Make this state sticky */
3627 return NULL;
3628 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 i = di->di_pos;
INADA Naokica2d8be2016-11-04 16:59:10 +09003631 assert(i >= 0);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003632 if (d->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09003633 if (i >= d->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003634 goto fail;
3635 key = DK_ENTRIES(d->ma_keys)[i].me_key;
INADA Naokica2d8be2016-11-04 16:59:10 +09003636 value = d->ma_values[i];
3637 assert(value != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003638 }
3639 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09003640 Py_ssize_t n = d->ma_keys->dk_nentries;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003641 PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
3642 while (i < n && entry_ptr->me_value == NULL) {
3643 entry_ptr++;
3644 i++;
3645 }
3646 if (i >= n)
3647 goto fail;
3648 key = entry_ptr->me_key;
3649 value = entry_ptr->me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003650 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 di->di_pos = i+1;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003652 di->len--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 if (result->ob_refcnt == 1) {
3654 Py_INCREF(result);
3655 Py_DECREF(PyTuple_GET_ITEM(result, 0));
3656 Py_DECREF(PyTuple_GET_ITEM(result, 1));
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003657 }
3658 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 result = PyTuple_New(2);
3660 if (result == NULL)
3661 return NULL;
3662 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 Py_INCREF(key);
3664 Py_INCREF(value);
Eric Snow96c6af92015-05-29 22:21:39 -06003665 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3666 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003668
3669fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003671 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003672 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003673}
3674
3675PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3677 "dict_itemiterator", /* tp_name */
3678 sizeof(dictiterobject), /* tp_basicsize */
3679 0, /* tp_itemsize */
3680 /* methods */
3681 (destructor)dictiter_dealloc, /* tp_dealloc */
3682 0, /* tp_print */
3683 0, /* tp_getattr */
3684 0, /* tp_setattr */
3685 0, /* tp_reserved */
3686 0, /* tp_repr */
3687 0, /* tp_as_number */
3688 0, /* tp_as_sequence */
3689 0, /* tp_as_mapping */
3690 0, /* tp_hash */
3691 0, /* tp_call */
3692 0, /* tp_str */
3693 PyObject_GenericGetAttr, /* tp_getattro */
3694 0, /* tp_setattro */
3695 0, /* tp_as_buffer */
3696 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3697 0, /* tp_doc */
3698 (traverseproc)dictiter_traverse, /* tp_traverse */
3699 0, /* tp_clear */
3700 0, /* tp_richcompare */
3701 0, /* tp_weaklistoffset */
3702 PyObject_SelfIter, /* tp_iter */
3703 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
3704 dictiter_methods, /* tp_methods */
3705 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003706};
Guido van Rossumb90c8482007-02-10 01:11:45 +00003707
3708
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003709static PyObject *
3710dictiter_reduce(dictiterobject *di)
3711{
3712 PyObject *list;
3713 dictiterobject tmp;
3714
3715 list = PyList_New(0);
3716 if (!list)
3717 return NULL;
3718
3719 /* copy the itertor state */
3720 tmp = *di;
3721 Py_XINCREF(tmp.di_dict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003722
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003723 /* iterate the temporary into a list */
3724 for(;;) {
3725 PyObject *element = 0;
3726 if (Py_TYPE(di) == &PyDictIterItem_Type)
3727 element = dictiter_iternextitem(&tmp);
3728 else if (Py_TYPE(di) == &PyDictIterKey_Type)
3729 element = dictiter_iternextkey(&tmp);
3730 else if (Py_TYPE(di) == &PyDictIterValue_Type)
3731 element = dictiter_iternextvalue(&tmp);
3732 else
3733 assert(0);
3734 if (element) {
3735 if (PyList_Append(list, element)) {
3736 Py_DECREF(element);
3737 Py_DECREF(list);
3738 Py_XDECREF(tmp.di_dict);
3739 return NULL;
3740 }
3741 Py_DECREF(element);
3742 } else
3743 break;
3744 }
3745 Py_XDECREF(tmp.di_dict);
3746 /* check for error */
3747 if (tmp.di_dict != NULL) {
3748 /* we have an error */
3749 Py_DECREF(list);
3750 return NULL;
3751 }
Antoine Pitroua7013882012-04-05 00:04:20 +02003752 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003753}
3754
Guido van Rossum3ac67412007-02-10 18:55:06 +00003755/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003756/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00003757/***********************************************/
3758
Guido van Rossumb90c8482007-02-10 01:11:45 +00003759/* The instance lay-out is the same for all three; but the type differs. */
3760
Guido van Rossumb90c8482007-02-10 01:11:45 +00003761static void
Eric Snow96c6af92015-05-29 22:21:39 -06003762dictview_dealloc(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 Py_XDECREF(dv->dv_dict);
3765 PyObject_GC_Del(dv);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003766}
3767
3768static int
Eric Snow96c6af92015-05-29 22:21:39 -06003769dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 Py_VISIT(dv->dv_dict);
3772 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003773}
3774
Guido van Rossum83825ac2007-02-10 04:54:19 +00003775static Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003776dictview_len(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 Py_ssize_t len = 0;
3779 if (dv->dv_dict != NULL)
3780 len = dv->dv_dict->ma_used;
3781 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003782}
3783
Eric Snow96c6af92015-05-29 22:21:39 -06003784PyObject *
3785_PyDictView_New(PyObject *dict, PyTypeObject *type)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003786{
Eric Snow96c6af92015-05-29 22:21:39 -06003787 _PyDictViewObject *dv;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 if (dict == NULL) {
3789 PyErr_BadInternalCall();
3790 return NULL;
3791 }
3792 if (!PyDict_Check(dict)) {
3793 /* XXX Get rid of this restriction later */
3794 PyErr_Format(PyExc_TypeError,
3795 "%s() requires a dict argument, not '%s'",
3796 type->tp_name, dict->ob_type->tp_name);
3797 return NULL;
3798 }
Eric Snow96c6af92015-05-29 22:21:39 -06003799 dv = PyObject_GC_New(_PyDictViewObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 if (dv == NULL)
3801 return NULL;
3802 Py_INCREF(dict);
3803 dv->dv_dict = (PyDictObject *)dict;
3804 _PyObject_GC_TRACK(dv);
3805 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003806}
3807
Neal Norwitze36f2ba2007-02-26 23:12:28 +00003808/* TODO(guido): The views objects are not complete:
3809
3810 * support more set operations
3811 * support arbitrary mappings?
3812 - either these should be static or exported in dictobject.h
3813 - if public then they should probably be in builtins
3814*/
3815
Guido van Rossumaac530c2007-08-24 22:33:45 +00003816/* Return 1 if self is a subset of other, iterating over self;
3817 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00003818static int
3819all_contained_in(PyObject *self, PyObject *other)
3820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003821 PyObject *iter = PyObject_GetIter(self);
3822 int ok = 1;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 if (iter == NULL)
3825 return -1;
3826 for (;;) {
3827 PyObject *next = PyIter_Next(iter);
3828 if (next == NULL) {
3829 if (PyErr_Occurred())
3830 ok = -1;
3831 break;
3832 }
3833 ok = PySequence_Contains(other, next);
3834 Py_DECREF(next);
3835 if (ok <= 0)
3836 break;
3837 }
3838 Py_DECREF(iter);
3839 return ok;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003840}
3841
3842static PyObject *
3843dictview_richcompare(PyObject *self, PyObject *other, int op)
3844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003845 Py_ssize_t len_self, len_other;
3846 int ok;
3847 PyObject *result;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 assert(self != NULL);
3850 assert(PyDictViewSet_Check(self));
3851 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00003852
Brian Curtindfc80e32011-08-10 20:28:54 -05003853 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
3854 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003856 len_self = PyObject_Size(self);
3857 if (len_self < 0)
3858 return NULL;
3859 len_other = PyObject_Size(other);
3860 if (len_other < 0)
3861 return NULL;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003863 ok = 0;
3864 switch(op) {
Guido van Rossumaac530c2007-08-24 22:33:45 +00003865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 case Py_NE:
3867 case Py_EQ:
3868 if (len_self == len_other)
3869 ok = all_contained_in(self, other);
3870 if (op == Py_NE && ok >= 0)
3871 ok = !ok;
3872 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 case Py_LT:
3875 if (len_self < len_other)
3876 ok = all_contained_in(self, other);
3877 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 case Py_LE:
3880 if (len_self <= len_other)
3881 ok = all_contained_in(self, other);
3882 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 case Py_GT:
3885 if (len_self > len_other)
3886 ok = all_contained_in(other, self);
3887 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 case Py_GE:
3890 if (len_self >= len_other)
3891 ok = all_contained_in(other, self);
3892 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 }
3895 if (ok < 0)
3896 return NULL;
3897 result = ok ? Py_True : Py_False;
3898 Py_INCREF(result);
3899 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003900}
3901
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003902static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003903dictview_repr(_PyDictViewObject *dv)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 PyObject *seq;
3906 PyObject *result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 seq = PySequence_List((PyObject *)dv);
3909 if (seq == NULL)
3910 return NULL;
3911
3912 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
3913 Py_DECREF(seq);
3914 return result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003915}
3916
Guido van Rossum3ac67412007-02-10 18:55:06 +00003917/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003918
3919static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003920dictkeys_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 if (dv->dv_dict == NULL) {
3923 Py_RETURN_NONE;
3924 }
3925 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003926}
3927
3928static int
Eric Snow96c6af92015-05-29 22:21:39 -06003929dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00003930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 if (dv->dv_dict == NULL)
3932 return 0;
3933 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003934}
3935
Guido van Rossum83825ac2007-02-10 04:54:19 +00003936static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 (lenfunc)dictview_len, /* sq_length */
3938 0, /* sq_concat */
3939 0, /* sq_repeat */
3940 0, /* sq_item */
3941 0, /* sq_slice */
3942 0, /* sq_ass_item */
3943 0, /* sq_ass_slice */
3944 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003945};
3946
Guido van Rossum523259b2007-08-24 23:41:22 +00003947static PyObject*
3948dictviews_sub(PyObject* self, PyObject *other)
3949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 PyObject *result = PySet_New(self);
3951 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003952 _Py_IDENTIFIER(difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 if (result == NULL)
3955 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003956
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003957 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 if (tmp == NULL) {
3959 Py_DECREF(result);
3960 return NULL;
3961 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 Py_DECREF(tmp);
3964 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003965}
3966
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003967PyObject*
3968_PyDictView_Intersect(PyObject* self, PyObject *other)
Guido van Rossum523259b2007-08-24 23:41:22 +00003969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 PyObject *result = PySet_New(self);
3971 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003972 _Py_IDENTIFIER(intersection_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 if (result == NULL)
3975 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003976
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003977 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_intersection_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003978 if (tmp == NULL) {
3979 Py_DECREF(result);
3980 return NULL;
3981 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003983 Py_DECREF(tmp);
3984 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003985}
3986
3987static PyObject*
3988dictviews_or(PyObject* self, PyObject *other)
3989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003990 PyObject *result = PySet_New(self);
3991 PyObject *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02003992 _Py_IDENTIFIER(update);
Victor Stinnerd1a9cc22011-10-13 22:51:17 +02003993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003994 if (result == NULL)
3995 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003996
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003997 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003998 if (tmp == NULL) {
3999 Py_DECREF(result);
4000 return NULL;
4001 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004003 Py_DECREF(tmp);
4004 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004005}
4006
4007static PyObject*
4008dictviews_xor(PyObject* self, PyObject *other)
4009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004010 PyObject *result = PySet_New(self);
4011 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004012 _Py_IDENTIFIER(symmetric_difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004014 if (result == NULL)
4015 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004016
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08004017 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_symmetric_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 if (tmp == NULL) {
4019 Py_DECREF(result);
4020 return NULL;
4021 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 Py_DECREF(tmp);
4024 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004025}
4026
4027static PyNumberMethods dictviews_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 0, /*nb_add*/
4029 (binaryfunc)dictviews_sub, /*nb_subtract*/
4030 0, /*nb_multiply*/
4031 0, /*nb_remainder*/
4032 0, /*nb_divmod*/
4033 0, /*nb_power*/
4034 0, /*nb_negative*/
4035 0, /*nb_positive*/
4036 0, /*nb_absolute*/
4037 0, /*nb_bool*/
4038 0, /*nb_invert*/
4039 0, /*nb_lshift*/
4040 0, /*nb_rshift*/
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004041 (binaryfunc)_PyDictView_Intersect, /*nb_and*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004042 (binaryfunc)dictviews_xor, /*nb_xor*/
4043 (binaryfunc)dictviews_or, /*nb_or*/
Guido van Rossum523259b2007-08-24 23:41:22 +00004044};
4045
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004046static PyObject*
4047dictviews_isdisjoint(PyObject *self, PyObject *other)
4048{
4049 PyObject *it;
4050 PyObject *item = NULL;
4051
4052 if (self == other) {
Eric Snow96c6af92015-05-29 22:21:39 -06004053 if (dictview_len((_PyDictViewObject *)self) == 0)
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004054 Py_RETURN_TRUE;
4055 else
4056 Py_RETURN_FALSE;
4057 }
4058
4059 /* Iterate over the shorter object (only if other is a set,
4060 * because PySequence_Contains may be expensive otherwise): */
4061 if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
Eric Snow96c6af92015-05-29 22:21:39 -06004062 Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004063 Py_ssize_t len_other = PyObject_Size(other);
4064 if (len_other == -1)
4065 return NULL;
4066
4067 if ((len_other > len_self)) {
4068 PyObject *tmp = other;
4069 other = self;
4070 self = tmp;
4071 }
4072 }
4073
4074 it = PyObject_GetIter(other);
4075 if (it == NULL)
4076 return NULL;
4077
4078 while ((item = PyIter_Next(it)) != NULL) {
4079 int contains = PySequence_Contains(self, item);
4080 Py_DECREF(item);
4081 if (contains == -1) {
4082 Py_DECREF(it);
4083 return NULL;
4084 }
4085
4086 if (contains) {
4087 Py_DECREF(it);
4088 Py_RETURN_FALSE;
4089 }
4090 }
4091 Py_DECREF(it);
4092 if (PyErr_Occurred())
4093 return NULL; /* PyIter_Next raised an exception. */
4094 Py_RETURN_TRUE;
4095}
4096
4097PyDoc_STRVAR(isdisjoint_doc,
4098"Return True if the view and the given iterable have a null intersection.");
4099
Guido van Rossumb90c8482007-02-10 01:11:45 +00004100static PyMethodDef dictkeys_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004101 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4102 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004104};
4105
4106PyTypeObject PyDictKeys_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4108 "dict_keys", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004109 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 0, /* tp_itemsize */
4111 /* methods */
4112 (destructor)dictview_dealloc, /* tp_dealloc */
4113 0, /* tp_print */
4114 0, /* tp_getattr */
4115 0, /* tp_setattr */
4116 0, /* tp_reserved */
4117 (reprfunc)dictview_repr, /* tp_repr */
4118 &dictviews_as_number, /* tp_as_number */
4119 &dictkeys_as_sequence, /* tp_as_sequence */
4120 0, /* tp_as_mapping */
4121 0, /* tp_hash */
4122 0, /* tp_call */
4123 0, /* tp_str */
4124 PyObject_GenericGetAttr, /* tp_getattro */
4125 0, /* tp_setattro */
4126 0, /* tp_as_buffer */
4127 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4128 0, /* tp_doc */
4129 (traverseproc)dictview_traverse, /* tp_traverse */
4130 0, /* tp_clear */
4131 dictview_richcompare, /* tp_richcompare */
4132 0, /* tp_weaklistoffset */
4133 (getiterfunc)dictkeys_iter, /* tp_iter */
4134 0, /* tp_iternext */
4135 dictkeys_methods, /* tp_methods */
4136 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004137};
4138
4139static PyObject *
4140dictkeys_new(PyObject *dict)
4141{
Eric Snow96c6af92015-05-29 22:21:39 -06004142 return _PyDictView_New(dict, &PyDictKeys_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004143}
4144
Guido van Rossum3ac67412007-02-10 18:55:06 +00004145/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004146
4147static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004148dictitems_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004150 if (dv->dv_dict == NULL) {
4151 Py_RETURN_NONE;
4152 }
4153 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00004154}
4155
4156static int
Eric Snow96c6af92015-05-29 22:21:39 -06004157dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00004158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 PyObject *key, *value, *found;
4160 if (dv->dv_dict == NULL)
4161 return 0;
4162 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
4163 return 0;
4164 key = PyTuple_GET_ITEM(obj, 0);
4165 value = PyTuple_GET_ITEM(obj, 1);
Raymond Hettinger6692f012016-09-18 21:46:08 -07004166 found = PyDict_GetItemWithError((PyObject *)dv->dv_dict, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004167 if (found == NULL) {
4168 if (PyErr_Occurred())
4169 return -1;
4170 return 0;
4171 }
4172 return PyObject_RichCompareBool(value, found, Py_EQ);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004173}
4174
Guido van Rossum83825ac2007-02-10 04:54:19 +00004175static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 (lenfunc)dictview_len, /* sq_length */
4177 0, /* sq_concat */
4178 0, /* sq_repeat */
4179 0, /* sq_item */
4180 0, /* sq_slice */
4181 0, /* sq_ass_item */
4182 0, /* sq_ass_slice */
4183 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004184};
4185
Guido van Rossumb90c8482007-02-10 01:11:45 +00004186static PyMethodDef dictitems_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004187 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4188 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004190};
4191
4192PyTypeObject PyDictItems_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004193 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4194 "dict_items", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004195 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004196 0, /* tp_itemsize */
4197 /* methods */
4198 (destructor)dictview_dealloc, /* tp_dealloc */
4199 0, /* tp_print */
4200 0, /* tp_getattr */
4201 0, /* tp_setattr */
4202 0, /* tp_reserved */
4203 (reprfunc)dictview_repr, /* tp_repr */
4204 &dictviews_as_number, /* tp_as_number */
4205 &dictitems_as_sequence, /* tp_as_sequence */
4206 0, /* tp_as_mapping */
4207 0, /* tp_hash */
4208 0, /* tp_call */
4209 0, /* tp_str */
4210 PyObject_GenericGetAttr, /* tp_getattro */
4211 0, /* tp_setattro */
4212 0, /* tp_as_buffer */
4213 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4214 0, /* tp_doc */
4215 (traverseproc)dictview_traverse, /* tp_traverse */
4216 0, /* tp_clear */
4217 dictview_richcompare, /* tp_richcompare */
4218 0, /* tp_weaklistoffset */
4219 (getiterfunc)dictitems_iter, /* tp_iter */
4220 0, /* tp_iternext */
4221 dictitems_methods, /* tp_methods */
4222 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004223};
4224
4225static PyObject *
4226dictitems_new(PyObject *dict)
4227{
Eric Snow96c6af92015-05-29 22:21:39 -06004228 return _PyDictView_New(dict, &PyDictItems_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004229}
4230
Guido van Rossum3ac67412007-02-10 18:55:06 +00004231/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004232
4233static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004234dictvalues_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 if (dv->dv_dict == NULL) {
4237 Py_RETURN_NONE;
4238 }
4239 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004240}
4241
Guido van Rossum83825ac2007-02-10 04:54:19 +00004242static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243 (lenfunc)dictview_len, /* sq_length */
4244 0, /* sq_concat */
4245 0, /* sq_repeat */
4246 0, /* sq_item */
4247 0, /* sq_slice */
4248 0, /* sq_ass_item */
4249 0, /* sq_ass_slice */
4250 (objobjproc)0, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004251};
4252
Guido van Rossumb90c8482007-02-10 01:11:45 +00004253static PyMethodDef dictvalues_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004254 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004255};
4256
4257PyTypeObject PyDictValues_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004258 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4259 "dict_values", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004260 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004261 0, /* tp_itemsize */
4262 /* methods */
4263 (destructor)dictview_dealloc, /* tp_dealloc */
4264 0, /* tp_print */
4265 0, /* tp_getattr */
4266 0, /* tp_setattr */
4267 0, /* tp_reserved */
4268 (reprfunc)dictview_repr, /* tp_repr */
4269 0, /* tp_as_number */
4270 &dictvalues_as_sequence, /* tp_as_sequence */
4271 0, /* tp_as_mapping */
4272 0, /* tp_hash */
4273 0, /* tp_call */
4274 0, /* tp_str */
4275 PyObject_GenericGetAttr, /* tp_getattro */
4276 0, /* tp_setattro */
4277 0, /* tp_as_buffer */
4278 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4279 0, /* tp_doc */
4280 (traverseproc)dictview_traverse, /* tp_traverse */
4281 0, /* tp_clear */
4282 0, /* tp_richcompare */
4283 0, /* tp_weaklistoffset */
4284 (getiterfunc)dictvalues_iter, /* tp_iter */
4285 0, /* tp_iternext */
4286 dictvalues_methods, /* tp_methods */
4287 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004288};
4289
4290static PyObject *
4291dictvalues_new(PyObject *dict)
4292{
Eric Snow96c6af92015-05-29 22:21:39 -06004293 return _PyDictView_New(dict, &PyDictValues_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004294}
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004295
4296/* Returns NULL if cannot allocate a new PyDictKeysObject,
4297 but does not set an error */
4298PyDictKeysObject *
4299_PyDict_NewKeysForClass(void)
4300{
Victor Stinner742da042016-09-07 17:40:12 -07004301 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004302 if (keys == NULL)
4303 PyErr_Clear();
4304 else
4305 keys->dk_lookup = lookdict_split;
4306 return keys;
4307}
4308
4309#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
4310
4311PyObject *
4312PyObject_GenericGetDict(PyObject *obj, void *context)
4313{
4314 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
4315 if (dictptr == NULL) {
4316 PyErr_SetString(PyExc_AttributeError,
4317 "This object has no __dict__");
4318 return NULL;
4319 }
4320 dict = *dictptr;
4321 if (dict == NULL) {
4322 PyTypeObject *tp = Py_TYPE(obj);
4323 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
4324 DK_INCREF(CACHED_KEYS(tp));
4325 *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
4326 }
4327 else {
4328 *dictptr = dict = PyDict_New();
4329 }
4330 }
4331 Py_XINCREF(dict);
4332 return dict;
4333}
4334
4335int
4336_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
Victor Stinner742da042016-09-07 17:40:12 -07004337 PyObject *key, PyObject *value)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004338{
4339 PyObject *dict;
4340 int res;
4341 PyDictKeysObject *cached;
4342
4343 assert(dictptr != NULL);
4344 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
4345 assert(dictptr != NULL);
4346 dict = *dictptr;
4347 if (dict == NULL) {
4348 DK_INCREF(cached);
4349 dict = new_dict_with_shared_keys(cached);
4350 if (dict == NULL)
4351 return -1;
4352 *dictptr = dict;
4353 }
4354 if (value == NULL) {
4355 res = PyDict_DelItem(dict, key);
INADA Naoki2294f3a2017-02-12 13:51:30 +09004356 // Since key sharing dict doesn't allow deletion, PyDict_DelItem()
4357 // always converts dict to combined form.
4358 if ((cached = CACHED_KEYS(tp)) != NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004359 CACHED_KEYS(tp) = NULL;
4360 DK_DECREF(cached);
4361 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01004362 }
4363 else {
INADA Naoki2294f3a2017-02-12 13:51:30 +09004364 int was_shared = (cached == ((PyDictObject *)dict)->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004365 res = PyDict_SetItem(dict, key, value);
INADA Naoki2294f3a2017-02-12 13:51:30 +09004366 if (was_shared &&
4367 (cached = CACHED_KEYS(tp)) != NULL &&
4368 cached != ((PyDictObject *)dict)->ma_keys) {
Victor Stinner3d3f2642016-12-15 17:21:23 +01004369 /* PyDict_SetItem() may call dictresize and convert split table
4370 * into combined table. In such case, convert it to split
4371 * table again and update type's shared key only when this is
4372 * the only dict sharing key with the type.
4373 *
4374 * This is to allow using shared key in class like this:
4375 *
4376 * class C:
4377 * def __init__(self):
4378 * # one dict resize happens
4379 * self.a, self.b, self.c = 1, 2, 3
4380 * self.d, self.e, self.f = 4, 5, 6
4381 * a = C()
4382 */
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004383 if (cached->dk_refcnt == 1) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004384 CACHED_KEYS(tp) = make_keys_shared(dict);
Victor Stinner742da042016-09-07 17:40:12 -07004385 }
4386 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004387 CACHED_KEYS(tp) = NULL;
4388 }
4389 DK_DECREF(cached);
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004390 if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
4391 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004392 }
4393 }
4394 } else {
4395 dict = *dictptr;
4396 if (dict == NULL) {
4397 dict = PyDict_New();
4398 if (dict == NULL)
4399 return -1;
4400 *dictptr = dict;
4401 }
4402 if (value == NULL) {
4403 res = PyDict_DelItem(dict, key);
4404 } else {
4405 res = PyDict_SetItem(dict, key, value);
4406 }
4407 }
4408 return res;
4409}
4410
4411void
4412_PyDictKeys_DecRef(PyDictKeysObject *keys)
4413{
4414 DK_DECREF(keys);
4415}