blob: c44ff47f8b33cdc53f763fbee5d4dd5bd34e09b6 [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{
Victor Stinner742da042016-09-07 17:40:12 -0700634 size_t mask = DK_MASK(k);
INADA Naoki073ae482017-06-23 15:22:50 +0900635 size_t perturb = (size_t)hash;
636 size_t i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700637
INADA Naoki073ae482017-06-23 15:22:50 +0900638 for (;;) {
639 Py_ssize_t ix = dk_get_index(k, i);
Victor Stinner742da042016-09-07 17:40:12 -0700640 if (ix == index) {
641 return i;
642 }
643 if (ix == DKIX_EMPTY) {
644 return DKIX_EMPTY;
645 }
INADA Naoki073ae482017-06-23 15:22:50 +0900646 perturb >>= PERTURB_SHIFT;
647 i = mask & (i*5 + perturb + 1);
Victor Stinner742da042016-09-07 17:40:12 -0700648 }
649 assert(0); /* NOT REACHED */
650 return DKIX_ERROR;
651}
652
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000653/*
654The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000655This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000656Open addressing is preferred over chaining since the link overhead for
657chaining would be substantial (100% with typical malloc overhead).
658
Tim Peterseb28ef22001-06-02 05:27:19 +0000659The initial probe index is computed as hash mod the table size. Subsequent
660probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000661
662All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000663
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000664The details in this version are due to Tim Peters, building on many past
Tim Peterseb28ef22001-06-02 05:27:19 +0000665contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000666Christian Tismer.
Fred Drake1bff34a2000-08-31 19:31:38 +0000667
Victor Stinner742da042016-09-07 17:40:12 -0700668lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a
Victor Stinnera4348cc2016-09-08 12:01:25 -0700669comparison raises an exception.
Guido van Rossum89d8c602007-09-18 17:26:56 +0000670lookdict_unicode() below is specialized to string keys, comparison of which can
INADA Naoki1b8df102017-02-20 22:48:10 +0900671never raise an exception; that function can never return DKIX_ERROR when key
672is string. Otherwise, it falls back to lookdict().
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400673lookdict_unicode_nodummy is further specialized for string keys that cannot be
674the <dummy> value.
Victor Stinner742da042016-09-07 17:40:12 -0700675For both, when the key isn't found a DKIX_EMPTY is returned. hashpos returns
676where the key index should be inserted.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000677*/
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100678static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400679lookdict(PyDictObject *mp, PyObject *key,
INADA Naokiba609772016-12-07 20:41:42 +0900680 Py_hash_t hash, PyObject **value_addr, Py_ssize_t *hashpos)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000681{
INADA Naoki267941c2016-10-06 15:19:07 +0900682 size_t i, mask;
Victor Stinner742da042016-09-07 17:40:12 -0700683 Py_ssize_t ix, freeslot;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200684 int cmp;
Victor Stinner742da042016-09-07 17:40:12 -0700685 PyDictKeysObject *dk;
686 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 PyObject *startkey;
Tim Peterseb28ef22001-06-02 05:27:19 +0000688
Antoine Pitrou9a234902012-05-13 20:48:01 +0200689top:
Victor Stinner742da042016-09-07 17:40:12 -0700690 dk = mp->ma_keys;
691 mask = DK_MASK(dk);
692 ep0 = DK_ENTRIES(dk);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700694
695 ix = dk_get_index(dk, i);
696 if (ix == DKIX_EMPTY) {
697 if (hashpos != NULL)
698 *hashpos = i;
699 *value_addr = NULL;
700 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400701 }
Victor Stinner742da042016-09-07 17:40:12 -0700702 if (ix == DKIX_DUMMY) {
703 freeslot = i;
704 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 else {
Victor Stinner742da042016-09-07 17:40:12 -0700706 ep = &ep0[ix];
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300707 assert(ep->me_key != NULL);
Victor Stinner742da042016-09-07 17:40:12 -0700708 if (ep->me_key == key) {
INADA Naokiba609772016-12-07 20:41:42 +0900709 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700710 if (hashpos != NULL)
711 *hashpos = i;
712 return ix;
713 }
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300714 if (ep->me_hash == hash) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 startkey = ep->me_key;
716 Py_INCREF(startkey);
717 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
718 Py_DECREF(startkey);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +0200719 if (cmp < 0) {
720 *value_addr = NULL;
Victor Stinner742da042016-09-07 17:40:12 -0700721 return DKIX_ERROR;
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +0200722 }
Victor Stinner742da042016-09-07 17:40:12 -0700723 if (dk == mp->ma_keys && ep->me_key == startkey) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400724 if (cmp > 0) {
INADA Naokiba609772016-12-07 20:41:42 +0900725 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700726 if (hashpos != NULL)
727 *hashpos = i;
728 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400729 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 }
731 else {
Antoine Pitrou9a234902012-05-13 20:48:01 +0200732 /* The dict was mutated, restart */
733 goto top;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 }
735 }
Victor Stinner742da042016-09-07 17:40:12 -0700736 freeslot = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 }
Tim Peters15d49292001-05-27 07:39:22 +0000738
INADA Naoki267941c2016-10-06 15:19:07 +0900739 for (size_t perturb = hash;;) {
740 perturb >>= PERTURB_SHIFT;
INADA Naoki870c2862017-06-24 09:03:19 +0900741 i = (i*5 + perturb + 1) & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700742 ix = dk_get_index(dk, i);
743 if (ix == DKIX_EMPTY) {
744 if (hashpos != NULL) {
745 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400746 }
Victor Stinner742da042016-09-07 17:40:12 -0700747 *value_addr = NULL;
748 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400749 }
Victor Stinner742da042016-09-07 17:40:12 -0700750 if (ix == DKIX_DUMMY) {
751 if (freeslot == -1)
752 freeslot = i;
753 continue;
754 }
755 ep = &ep0[ix];
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300756 assert(ep->me_key != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400757 if (ep->me_key == key) {
Victor Stinner742da042016-09-07 17:40:12 -0700758 if (hashpos != NULL) {
759 *hashpos = i;
760 }
INADA Naokiba609772016-12-07 20:41:42 +0900761 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700762 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400763 }
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300764 if (ep->me_hash == hash) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 startkey = ep->me_key;
766 Py_INCREF(startkey);
767 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
768 Py_DECREF(startkey);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400769 if (cmp < 0) {
770 *value_addr = NULL;
Victor Stinner742da042016-09-07 17:40:12 -0700771 return DKIX_ERROR;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400772 }
Victor Stinner742da042016-09-07 17:40:12 -0700773 if (dk == mp->ma_keys && ep->me_key == startkey) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400774 if (cmp > 0) {
Victor Stinner742da042016-09-07 17:40:12 -0700775 if (hashpos != NULL) {
776 *hashpos = i;
777 }
INADA Naokiba609772016-12-07 20:41:42 +0900778 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700779 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400780 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 }
782 else {
Antoine Pitrou9a234902012-05-13 20:48:01 +0200783 /* The dict was mutated, restart */
784 goto top;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 }
786 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 }
788 assert(0); /* NOT REACHED */
789 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000790}
791
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400792/* Specialized version for string-only keys */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100793static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400794lookdict_unicode(PyDictObject *mp, PyObject *key,
INADA Naokiba609772016-12-07 20:41:42 +0900795 Py_hash_t hash, PyObject **value_addr, Py_ssize_t *hashpos)
Fred Drake1bff34a2000-08-31 19:31:38 +0000796{
INADA Naoki267941c2016-10-06 15:19:07 +0900797 size_t i;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200798 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700799 Py_ssize_t ix, freeslot;
800 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Fred Drake1bff34a2000-08-31 19:31:38 +0000801
Victor Stinner742da042016-09-07 17:40:12 -0700802 assert(mp->ma_values == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 /* Make sure this function doesn't have to handle non-unicode keys,
804 including subclasses of str; e.g., one reason to subclass
805 unicodes is to override __eq__, and for speed we don't cater to
806 that here. */
807 if (!PyUnicode_CheckExact(key)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400808 mp->ma_keys->dk_lookup = lookdict;
Victor Stinner742da042016-09-07 17:40:12 -0700809 return lookdict(mp, key, hash, value_addr, hashpos);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 }
Mark Dickinson57e683e2011-09-24 18:18:40 +0100811 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700812 ix = dk_get_index(mp->ma_keys, i);
813 if (ix == DKIX_EMPTY) {
814 if (hashpos != NULL)
815 *hashpos = i;
816 *value_addr = NULL;
817 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400818 }
Victor Stinner742da042016-09-07 17:40:12 -0700819 if (ix == DKIX_DUMMY) {
820 freeslot = i;
821 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 else {
Victor Stinner742da042016-09-07 17:40:12 -0700823 ep = &ep0[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700824 assert(ep->me_key != NULL);
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300825 if (ep->me_key == key
826 || (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700827 if (hashpos != NULL)
828 *hashpos = i;
INADA Naokiba609772016-12-07 20:41:42 +0900829 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700830 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400831 }
Victor Stinner742da042016-09-07 17:40:12 -0700832 freeslot = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 }
Tim Peters15d49292001-05-27 07:39:22 +0000834
INADA Naoki267941c2016-10-06 15:19:07 +0900835 for (size_t perturb = hash;;) {
836 perturb >>= PERTURB_SHIFT;
INADA Naoki870c2862017-06-24 09:03:19 +0900837 i = mask & (i*5 + perturb + 1);
Victor Stinner742da042016-09-07 17:40:12 -0700838 ix = dk_get_index(mp->ma_keys, i);
839 if (ix == DKIX_EMPTY) {
840 if (hashpos != NULL) {
841 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400842 }
Victor Stinner742da042016-09-07 17:40:12 -0700843 *value_addr = NULL;
844 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400845 }
Victor Stinner742da042016-09-07 17:40:12 -0700846 if (ix == DKIX_DUMMY) {
847 if (freeslot == -1)
848 freeslot = i;
849 continue;
850 }
851 ep = &ep0[ix];
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300852 assert(ep->me_key != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 if (ep->me_key == key
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300854 || (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
INADA Naokiba609772016-12-07 20:41:42 +0900855 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700856 if (hashpos != NULL) {
857 *hashpos = i;
858 }
859 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400860 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 }
862 assert(0); /* NOT REACHED */
863 return 0;
Fred Drake1bff34a2000-08-31 19:31:38 +0000864}
865
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400866/* Faster version of lookdict_unicode when it is known that no <dummy> keys
867 * will be present. */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100868static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400869lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
INADA Naokiba609772016-12-07 20:41:42 +0900870 Py_hash_t hash, PyObject **value_addr,
Victor Stinner742da042016-09-07 17:40:12 -0700871 Py_ssize_t *hashpos)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400872{
INADA Naoki267941c2016-10-06 15:19:07 +0900873 size_t i;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200874 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700875 Py_ssize_t ix;
876 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400877
Victor Stinner742da042016-09-07 17:40:12 -0700878 assert(mp->ma_values == NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400879 /* Make sure this function doesn't have to handle non-unicode keys,
880 including subclasses of str; e.g., one reason to subclass
881 unicodes is to override __eq__, and for speed we don't cater to
882 that here. */
883 if (!PyUnicode_CheckExact(key)) {
884 mp->ma_keys->dk_lookup = lookdict;
Victor Stinner742da042016-09-07 17:40:12 -0700885 return lookdict(mp, key, hash, value_addr, hashpos);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400886 }
887 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700888 ix = dk_get_index(mp->ma_keys, i);
889 assert (ix != DKIX_DUMMY);
890 if (ix == DKIX_EMPTY) {
891 if (hashpos != NULL)
892 *hashpos = i;
893 *value_addr = NULL;
894 return DKIX_EMPTY;
895 }
896 ep = &ep0[ix];
Victor Stinnerdee6e252016-09-08 11:16:07 -0700897 assert(ep->me_key != NULL);
898 assert(PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700899 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400900 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700901 if (hashpos != NULL)
902 *hashpos = i;
INADA Naokiba609772016-12-07 20:41:42 +0900903 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700904 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400905 }
INADA Naoki267941c2016-10-06 15:19:07 +0900906 for (size_t perturb = hash;;) {
907 perturb >>= PERTURB_SHIFT;
INADA Naoki870c2862017-06-24 09:03:19 +0900908 i = mask & (i*5 + perturb + 1);
Victor Stinner742da042016-09-07 17:40:12 -0700909 ix = dk_get_index(mp->ma_keys, i);
910 assert (ix != DKIX_DUMMY);
911 if (ix == DKIX_EMPTY) {
912 if (hashpos != NULL)
913 *hashpos = i;
914 *value_addr = NULL;
915 return DKIX_EMPTY;
916 }
917 ep = &ep0[ix];
918 assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
919 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400920 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700921 if (hashpos != NULL)
922 *hashpos = i;
INADA Naokiba609772016-12-07 20:41:42 +0900923 *value_addr = ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700924 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400925 }
926 }
927 assert(0); /* NOT REACHED */
928 return 0;
929}
930
931/* Version of lookdict for split tables.
932 * All split tables and only split tables use this lookup function.
933 * Split tables only contain unicode keys and no dummy keys,
934 * so algorithm is the same as lookdict_unicode_nodummy.
935 */
Victor Stinnerc7a8f672016-11-15 15:13:40 +0100936static Py_ssize_t _Py_HOT_FUNCTION
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400937lookdict_split(PyDictObject *mp, PyObject *key,
INADA Naokiba609772016-12-07 20:41:42 +0900938 Py_hash_t hash, PyObject **value_addr, Py_ssize_t *hashpos)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400939{
INADA Naoki267941c2016-10-06 15:19:07 +0900940 size_t i;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200941 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700942 Py_ssize_t ix;
943 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400944
Victor Stinner742da042016-09-07 17:40:12 -0700945 /* mp must split table */
946 assert(mp->ma_values != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400947 if (!PyUnicode_CheckExact(key)) {
Victor Stinner742da042016-09-07 17:40:12 -0700948 ix = lookdict(mp, key, hash, value_addr, hashpos);
949 if (ix >= 0) {
INADA Naokiba609772016-12-07 20:41:42 +0900950 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700951 }
952 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400953 }
Victor Stinner742da042016-09-07 17:40:12 -0700954
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400955 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700956 ix = dk_get_index(mp->ma_keys, i);
957 if (ix == DKIX_EMPTY) {
958 if (hashpos != NULL)
959 *hashpos = i;
960 *value_addr = NULL;
961 return DKIX_EMPTY;
962 }
963 assert(ix >= 0);
964 ep = &ep0[ix];
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300965 assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700966 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400967 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700968 if (hashpos != NULL)
969 *hashpos = i;
INADA Naokiba609772016-12-07 20:41:42 +0900970 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700971 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400972 }
INADA Naoki267941c2016-10-06 15:19:07 +0900973 for (size_t perturb = hash;;) {
974 perturb >>= PERTURB_SHIFT;
INADA Naoki870c2862017-06-24 09:03:19 +0900975 i = mask & (i*5 + perturb + 1);
Victor Stinner742da042016-09-07 17:40:12 -0700976 ix = dk_get_index(mp->ma_keys, i);
977 if (ix == DKIX_EMPTY) {
978 if (hashpos != NULL)
979 *hashpos = i;
980 *value_addr = NULL;
981 return DKIX_EMPTY;
982 }
983 assert(ix >= 0);
984 ep = &ep0[ix];
Serhiy Storchaka46825d22016-09-26 21:29:34 +0300985 assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700986 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400987 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700988 if (hashpos != NULL)
989 *hashpos = i;
INADA Naokiba609772016-12-07 20:41:42 +0900990 *value_addr = mp->ma_values[ix];
Victor Stinner742da042016-09-07 17:40:12 -0700991 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400992 }
993 }
994 assert(0); /* NOT REACHED */
995 return 0;
996}
997
Benjamin Petersonfb886362010-04-24 18:21:17 +0000998int
999_PyDict_HasOnlyStringKeys(PyObject *dict)
1000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 Py_ssize_t pos = 0;
1002 PyObject *key, *value;
Benjamin Petersonf6096542010-11-17 22:33:12 +00001003 assert(PyDict_Check(dict));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 /* Shortcut */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001005 if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 return 1;
1007 while (PyDict_Next(dict, &pos, &key, &value))
1008 if (!PyUnicode_Check(key))
1009 return 0;
1010 return 1;
Benjamin Petersonfb886362010-04-24 18:21:17 +00001011}
1012
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001013#define MAINTAIN_TRACKING(mp, key, value) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 do { \
1015 if (!_PyObject_GC_IS_TRACKED(mp)) { \
1016 if (_PyObject_GC_MAY_BE_TRACKED(key) || \
1017 _PyObject_GC_MAY_BE_TRACKED(value)) { \
1018 _PyObject_GC_TRACK(mp); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 } \
1020 } \
1021 } while(0)
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001022
1023void
1024_PyDict_MaybeUntrack(PyObject *op)
1025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 PyDictObject *mp;
1027 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -07001028 Py_ssize_t i, numentries;
1029 PyDictKeyEntry *ep0;
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
1032 return;
1033
1034 mp = (PyDictObject *) op;
Victor Stinner742da042016-09-07 17:40:12 -07001035 ep0 = DK_ENTRIES(mp->ma_keys);
1036 numentries = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001037 if (_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -07001038 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001039 if ((value = mp->ma_values[i]) == NULL)
1040 continue;
1041 if (_PyObject_GC_MAY_BE_TRACKED(value)) {
Victor Stinner742da042016-09-07 17:40:12 -07001042 assert(!_PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001043 return;
1044 }
1045 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001047 else {
Victor Stinner742da042016-09-07 17:40:12 -07001048 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001049 if ((value = ep0[i].me_value) == NULL)
1050 continue;
1051 if (_PyObject_GC_MAY_BE_TRACKED(value) ||
1052 _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
1053 return;
1054 }
1055 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 _PyObject_GC_UNTRACK(op);
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001057}
1058
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001059/* Internal function to find slot for an item from its hash
Victor Stinner3c336c52016-09-12 14:17:40 +02001060 when it is known that the key is not present in the dict.
1061
1062 The dict must be combined. */
INADA Naokiba609772016-12-07 20:41:42 +09001063static Py_ssize_t
1064find_empty_slot(PyDictKeysObject *keys, PyObject *key, Py_hash_t hash)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001065{
INADA Naoki267941c2016-10-06 15:19:07 +09001066 size_t i;
INADA Naokiba609772016-12-07 20:41:42 +09001067 size_t mask = DK_MASK(keys);
Victor Stinner742da042016-09-07 17:40:12 -07001068 Py_ssize_t ix;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001069
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001070 assert(key != NULL);
Victor Stinner3c336c52016-09-12 14:17:40 +02001071
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001072 i = hash & mask;
INADA Naokiba609772016-12-07 20:41:42 +09001073 ix = dk_get_index(keys, i);
INADA Naoki267941c2016-10-06 15:19:07 +09001074 for (size_t perturb = hash; ix != DKIX_EMPTY;) {
1075 perturb >>= PERTURB_SHIFT;
INADA Naoki870c2862017-06-24 09:03:19 +09001076 i = i*5 + perturb + 1;
INADA Naokiba609772016-12-07 20:41:42 +09001077 ix = dk_get_index(keys, i & mask);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 }
INADA Naokiba609772016-12-07 20:41:42 +09001079 assert(DK_ENTRIES(keys)[keys->dk_nentries].me_value == NULL);
1080 return i & mask;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001081}
1082
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001083static int
1084insertion_resize(PyDictObject *mp)
1085{
Raymond Hettinger36f74aa2013-05-17 03:01:13 -07001086 return dictresize(mp, GROWTH_RATE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001087}
Antoine Pitroue965d972012-02-27 00:45:12 +01001088
1089/*
1090Internal routine to insert a new item into the table.
1091Used both by the internal resize routine and by the public insert routine.
Antoine Pitroue965d972012-02-27 00:45:12 +01001092Returns -1 if an error occurred, or 0 on success.
1093*/
1094static int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001095insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001096{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001097 PyObject *old_value;
INADA Naokiba609772016-12-07 20:41:42 +09001098 PyDictKeyEntry *ep;
Victor Stinner742da042016-09-07 17:40:12 -07001099 Py_ssize_t hashpos, ix;
Antoine Pitroue965d972012-02-27 00:45:12 +01001100
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001101 Py_INCREF(key);
1102 Py_INCREF(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001103 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
1104 if (insertion_resize(mp) < 0)
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001105 goto Fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001106 }
1107
INADA Naokiba609772016-12-07 20:41:42 +09001108 ix = mp->ma_keys->dk_lookup(mp, key, hash, &old_value, &hashpos);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001109 if (ix == DKIX_ERROR)
1110 goto Fail;
Victor Stinner742da042016-09-07 17:40:12 -07001111
Antoine Pitroud6967322014-10-18 00:35:00 +02001112 assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001113 MAINTAIN_TRACKING(mp, key, value);
Victor Stinner742da042016-09-07 17:40:12 -07001114
1115 /* When insertion order is different from shared key, we can't share
1116 * the key anymore. Convert this instance to combine table.
1117 */
1118 if (_PyDict_HasSplitTable(mp) &&
INADA Naokiba609772016-12-07 20:41:42 +09001119 ((ix >= 0 && old_value == NULL && mp->ma_used != ix) ||
Victor Stinner742da042016-09-07 17:40:12 -07001120 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001121 if (insertion_resize(mp) < 0)
1122 goto Fail;
INADA Naokiba609772016-12-07 20:41:42 +09001123 hashpos = find_empty_slot(mp->ma_keys, key, hash);
Victor Stinner742da042016-09-07 17:40:12 -07001124 ix = DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001125 }
Victor Stinner742da042016-09-07 17:40:12 -07001126
1127 if (ix == DKIX_EMPTY) {
1128 /* Insert into new slot. */
INADA Naokiba609772016-12-07 20:41:42 +09001129 assert(old_value == NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001130 if (mp->ma_keys->dk_usable <= 0) {
1131 /* Need to resize. */
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001132 if (insertion_resize(mp) < 0)
1133 goto Fail;
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 }
INADA Naokiba609772016-12-07 20:41:42 +09001136 ep = &DK_ENTRIES(mp->ma_keys)[mp->ma_keys->dk_nentries];
Victor Stinner742da042016-09-07 17:40:12 -07001137 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
Victor Stinner742da042016-09-07 17:40:12 -07001138 ep->me_key = key;
1139 ep->me_hash = hash;
1140 if (mp->ma_values) {
1141 assert (mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
1142 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001143 }
1144 else {
Victor Stinner742da042016-09-07 17:40:12 -07001145 ep->me_value = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001146 }
1147 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001148 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07001149 mp->ma_keys->dk_usable--;
1150 mp->ma_keys->dk_nentries++;
1151 assert(mp->ma_keys->dk_usable >= 0);
Victor Stinner611b0fa2016-09-14 15:02:01 +02001152 assert(_PyDict_CheckConsistency(mp));
Victor Stinner742da042016-09-07 17:40:12 -07001153 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001154 }
Victor Stinner742da042016-09-07 17:40:12 -07001155
INADA Naokiba609772016-12-07 20:41:42 +09001156 if (_PyDict_HasSplitTable(mp)) {
1157 mp->ma_values[ix] = value;
1158 if (old_value == NULL) {
1159 /* pending state */
1160 assert(ix == mp->ma_used);
1161 mp->ma_used++;
1162 }
1163 }
1164 else {
1165 assert(old_value != NULL);
1166 DK_ENTRIES(mp->ma_keys)[ix].me_value = value;
Victor Stinner742da042016-09-07 17:40:12 -07001167 }
1168
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001169 mp->ma_version_tag = DICT_NEXT_VERSION();
INADA Naokiba609772016-12-07 20:41:42 +09001170 Py_XDECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
Victor Stinner611b0fa2016-09-14 15:02:01 +02001171 assert(_PyDict_CheckConsistency(mp));
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001172 Py_DECREF(key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001173 return 0;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03001174
1175Fail:
1176 Py_DECREF(value);
1177 Py_DECREF(key);
1178 return -1;
Antoine Pitroue965d972012-02-27 00:45:12 +01001179}
1180
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001181/*
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001182Internal routine used by dictresize() to buid a hashtable of entries.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001183*/
1184static void
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001185build_indices(PyDictKeysObject *keys, PyDictKeyEntry *ep, Py_ssize_t n)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001186{
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001187 size_t mask = (size_t)DK_SIZE(keys) - 1;
1188 for (Py_ssize_t ix = 0; ix != n; ix++, ep++) {
1189 Py_hash_t hash = ep->me_hash;
1190 size_t i = hash & mask;
1191 for (size_t perturb = hash; dk_get_index(keys, i) != DKIX_EMPTY;) {
1192 perturb >>= PERTURB_SHIFT;
INADA Naoki870c2862017-06-24 09:03:19 +09001193 i = mask & (i*5 + perturb + 1);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001194 }
1195 dk_set_index(keys, i, ix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001197}
1198
1199/*
1200Restructure the table by allocating a new table and reinserting all
1201items again. When entries have been deleted, the new table may
1202actually be smaller than the old one.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001203If a table is split (its keys and hashes are shared, its values are not),
1204then the values are temporarily copied into the table, it is resized as
1205a combined table, then the me_value slots in the old table are NULLed out.
1206After resizing a table is always combined,
1207but can be resplit by make_keys_shared().
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001208*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001209static int
Victor Stinner3d3f2642016-12-15 17:21:23 +01001210dictresize(PyDictObject *mp, Py_ssize_t minsize)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001211{
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001212 Py_ssize_t newsize, numentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001213 PyDictKeysObject *oldkeys;
1214 PyObject **oldvalues;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001215 PyDictKeyEntry *oldentries, *newentries;
Tim Peters91a364d2001-05-19 07:04:38 +00001216
Victor Stinner742da042016-09-07 17:40:12 -07001217 /* Find the smallest table size > minused. */
1218 for (newsize = PyDict_MINSIZE;
Victor Stinner3d3f2642016-12-15 17:21:23 +01001219 newsize < minsize && newsize > 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 newsize <<= 1)
1221 ;
1222 if (newsize <= 0) {
1223 PyErr_NoMemory();
1224 return -1;
1225 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001226
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001227 oldkeys = mp->ma_keys;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001228
1229 /* NOTE: Current odict checks mp->ma_keys to detect resize happen.
1230 * So we can't reuse oldkeys even if oldkeys->dk_size == newsize.
1231 * TODO: Try reusing oldkeys when reimplement odict.
1232 */
1233
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001234 /* Allocate a new table. */
1235 mp->ma_keys = new_keys_object(newsize);
1236 if (mp->ma_keys == NULL) {
1237 mp->ma_keys = oldkeys;
1238 return -1;
1239 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01001240 // New table must be large enough.
1241 assert(mp->ma_keys->dk_usable >= mp->ma_used);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001242 if (oldkeys->dk_lookup == lookdict)
1243 mp->ma_keys->dk_lookup = lookdict;
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001244
1245 numentries = mp->ma_used;
1246 oldentries = DK_ENTRIES(oldkeys);
1247 newentries = DK_ENTRIES(mp->ma_keys);
1248 oldvalues = mp->ma_values;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001249 if (oldvalues != NULL) {
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001250 /* Convert split table into new combined table.
1251 * We must incref keys; we can transfer values.
1252 * Note that values of split table is always dense.
1253 */
1254 for (Py_ssize_t i = 0; i < numentries; i++) {
1255 assert(oldvalues[i] != NULL);
1256 PyDictKeyEntry *ep = &oldentries[i];
1257 PyObject *key = ep->me_key;
1258 Py_INCREF(key);
1259 newentries[i].me_key = key;
1260 newentries[i].me_hash = ep->me_hash;
1261 newentries[i].me_value = oldvalues[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001263
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001264 DK_DECREF(oldkeys);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001265 mp->ma_values = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001266 if (oldvalues != empty_values) {
1267 free_values(oldvalues);
1268 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001269 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001270 else { // combined table.
1271 if (oldkeys->dk_nentries == numentries) {
1272 memcpy(newentries, oldentries, numentries * sizeof(PyDictKeyEntry));
1273 }
1274 else {
1275 PyDictKeyEntry *ep = oldentries;
1276 for (Py_ssize_t i = 0; i < numentries; i++) {
1277 while (ep->me_value == NULL)
1278 ep++;
1279 newentries[i] = *ep++;
1280 }
1281 }
1282
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001283 assert(oldkeys->dk_lookup != lookdict_split);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001284 assert(oldkeys->dk_refcnt == 1);
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001285 if (oldkeys->dk_size == PyDict_MINSIZE &&
1286 numfreekeys < PyDict_MAXFREELIST) {
1287 DK_DEBUG_DECREF keys_free_list[numfreekeys++] = oldkeys;
1288 }
1289 else {
1290 DK_DEBUG_DECREF PyObject_FREE(oldkeys);
1291 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001292 }
Serhiy Storchakae26e20d2016-10-29 10:50:00 +03001293
1294 build_indices(mp->ma_keys, newentries, numentries);
1295 mp->ma_keys->dk_usable -= numentries;
1296 mp->ma_keys->dk_nentries = numentries;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001298}
1299
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001300/* Returns NULL if unable to split table.
1301 * A NULL return does not necessarily indicate an error */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001302static PyDictKeysObject *
1303make_keys_shared(PyObject *op)
1304{
1305 Py_ssize_t i;
1306 Py_ssize_t size;
1307 PyDictObject *mp = (PyDictObject *)op;
1308
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001309 if (!PyDict_CheckExact(op))
1310 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001311 if (!_PyDict_HasSplitTable(mp)) {
1312 PyDictKeyEntry *ep0;
1313 PyObject **values;
1314 assert(mp->ma_keys->dk_refcnt == 1);
1315 if (mp->ma_keys->dk_lookup == lookdict) {
1316 return NULL;
1317 }
1318 else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
1319 /* Remove dummy keys */
1320 if (dictresize(mp, DK_SIZE(mp->ma_keys)))
1321 return NULL;
1322 }
1323 assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
1324 /* Copy values into a new array */
Victor Stinner742da042016-09-07 17:40:12 -07001325 ep0 = DK_ENTRIES(mp->ma_keys);
1326 size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001327 values = new_values(size);
1328 if (values == NULL) {
1329 PyErr_SetString(PyExc_MemoryError,
1330 "Not enough memory to allocate new values array");
1331 return NULL;
1332 }
1333 for (i = 0; i < size; i++) {
1334 values[i] = ep0[i].me_value;
1335 ep0[i].me_value = NULL;
1336 }
1337 mp->ma_keys->dk_lookup = lookdict_split;
1338 mp->ma_values = values;
1339 }
1340 DK_INCREF(mp->ma_keys);
1341 return mp->ma_keys;
1342}
Christian Heimes99170a52007-12-19 02:07:34 +00001343
1344PyObject *
1345_PyDict_NewPresized(Py_ssize_t minused)
1346{
INADA Naoki92c50ee2016-11-22 00:57:02 +09001347 const Py_ssize_t max_presize = 128 * 1024;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001348 Py_ssize_t newsize;
1349 PyDictKeysObject *new_keys;
INADA Naoki92c50ee2016-11-22 00:57:02 +09001350
1351 /* There are no strict guarantee that returned dict can contain minused
1352 * items without resize. So we create medium size dict instead of very
1353 * large dict or MemoryError.
1354 */
1355 if (minused > USABLE_FRACTION(max_presize)) {
1356 newsize = max_presize;
1357 }
1358 else {
1359 Py_ssize_t minsize = ESTIMATE_SIZE(minused);
1360 newsize = PyDict_MINSIZE;
1361 while (newsize < minsize) {
1362 newsize <<= 1;
1363 }
1364 }
1365 assert(IS_POWER_OF_2(newsize));
1366
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001367 new_keys = new_keys_object(newsize);
1368 if (new_keys == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001370 return new_dict(new_keys, NULL);
Christian Heimes99170a52007-12-19 02:07:34 +00001371}
1372
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001373/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
1374 * that may occur (originally dicts supported only string keys, and exceptions
1375 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001376 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001377 * (suppressed) occurred while computing the key's hash, or that some error
1378 * (suppressed) occurred when comparing keys in the dict's internal probe
1379 * sequence. A nasty example of the latter is when a Python-coded comparison
1380 * function hits a stack-depth error, which can cause this to return NULL
1381 * even if the key is present.
1382 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001383PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001384PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001385{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001386 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001387 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 PyDictObject *mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 PyThreadState *tstate;
INADA Naokiba609772016-12-07 20:41:42 +09001390 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 if (!PyDict_Check(op))
1393 return NULL;
1394 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001395 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 {
1397 hash = PyObject_Hash(key);
1398 if (hash == -1) {
1399 PyErr_Clear();
1400 return NULL;
1401 }
1402 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 /* We can arrive here with a NULL tstate during initialization: try
1405 running "python -Wi" for an example related to string interning.
1406 Let's just hope that no exception occurs then... This must be
1407 _PyThreadState_Current and not PyThreadState_GET() because in debug
1408 mode, the latter complains if tstate is NULL. */
Victor Stinner0cae6092016-11-11 01:43:56 +01001409 tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 if (tstate != NULL && tstate->curexc_type != NULL) {
1411 /* preserve the existing exception */
1412 PyObject *err_type, *err_value, *err_tb;
1413 PyErr_Fetch(&err_type, &err_value, &err_tb);
INADA Naokiba609772016-12-07 20:41:42 +09001414 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 /* ignore errors */
1416 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001417 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 return NULL;
1419 }
1420 else {
INADA Naokiba609772016-12-07 20:41:42 +09001421 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001422 if (ix < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 PyErr_Clear();
1424 return NULL;
1425 }
1426 }
INADA Naokiba609772016-12-07 20:41:42 +09001427 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001428}
1429
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001430/* Same as PyDict_GetItemWithError() but with hash supplied by caller.
1431 This returns NULL *with* an exception set if an exception occurred.
1432 It returns NULL *without* an exception set if the key wasn't present.
1433*/
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001434PyObject *
1435_PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1436{
Victor Stinner742da042016-09-07 17:40:12 -07001437 Py_ssize_t ix;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001438 PyDictObject *mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001439 PyObject *value;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001440
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001441 if (!PyDict_Check(op)) {
1442 PyErr_BadInternalCall();
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001443 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001444 }
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001445
INADA Naokiba609772016-12-07 20:41:42 +09001446 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02001447 if (ix < 0) {
1448 return NULL;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001449 }
INADA Naokiba609772016-12-07 20:41:42 +09001450 return value;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001451}
1452
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001453/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
1454 This returns NULL *with* an exception set if an exception occurred.
1455 It returns NULL *without* an exception set if the key wasn't present.
1456*/
1457PyObject *
1458PyDict_GetItemWithError(PyObject *op, PyObject *key)
1459{
Victor Stinner742da042016-09-07 17:40:12 -07001460 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001461 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 PyDictObject*mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001463 PyObject *value;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 if (!PyDict_Check(op)) {
1466 PyErr_BadInternalCall();
1467 return NULL;
1468 }
1469 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001470 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 {
1472 hash = PyObject_Hash(key);
1473 if (hash == -1) {
1474 return NULL;
1475 }
1476 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001477
INADA Naokiba609772016-12-07 20:41:42 +09001478 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001479 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001481 return value;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001482}
1483
Brett Cannonfd074152012-04-14 14:10:13 -04001484PyObject *
1485_PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
1486{
1487 PyObject *kv;
1488 kv = _PyUnicode_FromId(key); /* borrowed */
1489 if (kv == NULL)
1490 return NULL;
1491 return PyDict_GetItemWithError(dp, kv);
1492}
1493
Victor Stinnerb4efc962015-11-20 09:24:02 +01001494/* Fast version of global value lookup (LOAD_GLOBAL).
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001495 * Lookup in globals, then builtins.
Victor Stinnerb4efc962015-11-20 09:24:02 +01001496 *
1497 * Raise an exception and return NULL if an error occurred (ex: computing the
1498 * key hash failed, key comparison failed, ...). Return NULL if the key doesn't
1499 * exist. Return the value if the key exists.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001500 */
1501PyObject *
1502_PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001503{
Victor Stinner742da042016-09-07 17:40:12 -07001504 Py_ssize_t ix;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001505 Py_hash_t hash;
INADA Naokiba609772016-12-07 20:41:42 +09001506 PyObject *value;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001507
1508 if (!PyUnicode_CheckExact(key) ||
1509 (hash = ((PyASCIIObject *) key)->hash) == -1)
1510 {
1511 hash = PyObject_Hash(key);
1512 if (hash == -1)
1513 return NULL;
Antoine Pitroue965d972012-02-27 00:45:12 +01001514 }
Victor Stinnerb4efc962015-11-20 09:24:02 +01001515
1516 /* namespace 1: globals */
INADA Naokiba609772016-12-07 20:41:42 +09001517 ix = globals->ma_keys->dk_lookup(globals, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001518 if (ix == DKIX_ERROR)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001519 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001520 if (ix != DKIX_EMPTY && value != NULL)
1521 return value;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001522
1523 /* namespace 2: builtins */
INADA Naokiba609772016-12-07 20:41:42 +09001524 ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001525 if (ix < 0)
Victor Stinnerb4efc962015-11-20 09:24:02 +01001526 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001527 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001528}
1529
Antoine Pitroue965d972012-02-27 00:45:12 +01001530/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
1531 * dictionary if it's merely replacing the value for an existing key.
1532 * This means that it's safe to loop over a dictionary with PyDict_Next()
1533 * and occasionally replace a value -- but you can't insert new keys or
1534 * remove them.
1535 */
1536int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001537PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001538{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001539 PyDictObject *mp;
1540 Py_hash_t hash;
Antoine Pitroue965d972012-02-27 00:45:12 +01001541 if (!PyDict_Check(op)) {
1542 PyErr_BadInternalCall();
1543 return -1;
1544 }
1545 assert(key);
1546 assert(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001547 mp = (PyDictObject *)op;
1548 if (!PyUnicode_CheckExact(key) ||
1549 (hash = ((PyASCIIObject *) key)->hash) == -1)
1550 {
Antoine Pitroue965d972012-02-27 00:45:12 +01001551 hash = PyObject_Hash(key);
1552 if (hash == -1)
1553 return -1;
1554 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001555
1556 /* insertdict() handles any resizing that might be necessary */
1557 return insertdict(mp, key, hash, value);
Antoine Pitroue965d972012-02-27 00:45:12 +01001558}
1559
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001560int
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001561_PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
1562 Py_hash_t hash)
1563{
1564 PyDictObject *mp;
1565
1566 if (!PyDict_Check(op)) {
1567 PyErr_BadInternalCall();
1568 return -1;
1569 }
1570 assert(key);
1571 assert(value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001572 assert(hash != -1);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001573 mp = (PyDictObject *)op;
1574
1575 /* insertdict() handles any resizing that might be necessary */
1576 return insertdict(mp, key, hash, value);
1577}
1578
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001579static int
Antoine Pitroud741ed42016-12-27 14:23:43 +01001580delitem_common(PyDictObject *mp, Py_ssize_t hashpos, Py_ssize_t ix,
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001581 PyObject *old_value)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001582{
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001583 PyObject *old_key;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001584 PyDictKeyEntry *ep;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001585
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001586 mp->ma_used--;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001587 mp->ma_version_tag = DICT_NEXT_VERSION();
1588 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1589 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1590 ENSURE_ALLOWS_DELETIONS(mp);
1591 old_key = ep->me_key;
1592 ep->me_key = NULL;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001593 ep->me_value = NULL;
Antoine Pitroud741ed42016-12-27 14:23:43 +01001594 Py_DECREF(old_key);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001595 Py_DECREF(old_value);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001596
1597 assert(_PyDict_CheckConsistency(mp));
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001598 return 0;
1599}
1600
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001601int
Tim Peters1f5871e2000-07-04 17:44:48 +00001602PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001603{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001604 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 assert(key);
1606 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001607 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 hash = PyObject_Hash(key);
1609 if (hash == -1)
1610 return -1;
1611 }
Victor Stinner742da042016-09-07 17:40:12 -07001612
1613 return _PyDict_DelItem_KnownHash(op, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001614}
1615
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001616int
1617_PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1618{
Victor Stinner742da042016-09-07 17:40:12 -07001619 Py_ssize_t hashpos, ix;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001620 PyDictObject *mp;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001621 PyObject *old_value;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001622
1623 if (!PyDict_Check(op)) {
1624 PyErr_BadInternalCall();
1625 return -1;
1626 }
1627 assert(key);
1628 assert(hash != -1);
1629 mp = (PyDictObject *)op;
INADA Naokiba609772016-12-07 20:41:42 +09001630 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value, &hashpos);
Victor Stinner742da042016-09-07 17:40:12 -07001631 if (ix == DKIX_ERROR)
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001632 return -1;
INADA Naokiba609772016-12-07 20:41:42 +09001633 if (ix == DKIX_EMPTY || old_value == NULL) {
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001634 _PyErr_SetKeyError(key);
1635 return -1;
1636 }
Victor Stinner742da042016-09-07 17:40:12 -07001637 assert(dk_get_index(mp->ma_keys, hashpos) == ix);
Victor Stinner78601a32016-09-09 19:28:36 -07001638
1639 // Split table doesn't allow deletion. Combine it.
1640 if (_PyDict_HasSplitTable(mp)) {
1641 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1642 return -1;
1643 }
INADA Naokiba609772016-12-07 20:41:42 +09001644 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value, &hashpos);
Victor Stinner78601a32016-09-09 19:28:36 -07001645 assert(ix >= 0);
1646 }
1647
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001648 return delitem_common(mp, hashpos, ix, old_value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001649}
1650
Antoine Pitroud741ed42016-12-27 14:23:43 +01001651/* This function promises that the predicate -> deletion sequence is atomic
1652 * (i.e. protected by the GIL), assuming the predicate itself doesn't
1653 * release the GIL.
1654 */
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001655int
1656_PyDict_DelItemIf(PyObject *op, PyObject *key,
1657 int (*predicate)(PyObject *value))
1658{
Antoine Pitroud741ed42016-12-27 14:23:43 +01001659 Py_ssize_t hashpos, ix;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001660 PyDictObject *mp;
1661 Py_hash_t hash;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001662 PyObject *old_value;
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001663 int res;
1664
1665 if (!PyDict_Check(op)) {
1666 PyErr_BadInternalCall();
1667 return -1;
1668 }
1669 assert(key);
1670 hash = PyObject_Hash(key);
1671 if (hash == -1)
1672 return -1;
1673 mp = (PyDictObject *)op;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001674 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value, &hashpos);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001675 if (ix == DKIX_ERROR)
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001676 return -1;
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001677 if (ix == DKIX_EMPTY || old_value == NULL) {
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001678 _PyErr_SetKeyError(key);
1679 return -1;
1680 }
Antoine Pitroud741ed42016-12-27 14:23:43 +01001681 assert(dk_get_index(mp->ma_keys, hashpos) == ix);
1682
1683 // Split table doesn't allow deletion. Combine it.
1684 if (_PyDict_HasSplitTable(mp)) {
1685 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1686 return -1;
1687 }
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001688 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value, &hashpos);
Antoine Pitroud741ed42016-12-27 14:23:43 +01001689 assert(ix >= 0);
1690 }
1691
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001692 res = predicate(old_value);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001693 if (res == -1)
1694 return -1;
1695 if (res > 0)
Antoine Pitrouc06ae202016-12-27 14:34:54 +01001696 return delitem_common(mp, hashpos, ix, old_value);
Antoine Pitroue10ca3a2016-12-27 14:19:20 +01001697 else
1698 return 0;
1699}
1700
1701
Guido van Rossum25831651993-05-19 14:50:45 +00001702void
Tim Peters1f5871e2000-07-04 17:44:48 +00001703PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 PyDictObject *mp;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001706 PyDictKeysObject *oldkeys;
1707 PyObject **oldvalues;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +00001709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 if (!PyDict_Check(op))
1711 return;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001712 mp = ((PyDictObject *)op);
1713 oldkeys = mp->ma_keys;
1714 oldvalues = mp->ma_values;
1715 if (oldvalues == empty_values)
1716 return;
1717 /* Empty the dict... */
1718 DK_INCREF(Py_EMPTY_KEYS);
1719 mp->ma_keys = Py_EMPTY_KEYS;
1720 mp->ma_values = empty_values;
1721 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001722 mp->ma_version_tag = DICT_NEXT_VERSION();
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001723 /* ...then clear the keys and values */
1724 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001725 n = oldkeys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001726 for (i = 0; i < n; i++)
1727 Py_CLEAR(oldvalues[i]);
1728 free_values(oldvalues);
1729 DK_DECREF(oldkeys);
1730 }
1731 else {
1732 assert(oldkeys->dk_refcnt == 1);
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001733 DK_DECREF(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001734 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02001735 assert(_PyDict_CheckConsistency(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001736}
1737
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001738/* Internal version of PyDict_Next that returns a hash value in addition
1739 * to the key and value.
1740 * Return 1 on success, return 0 when the reached the end of the dictionary
1741 * (or if op is not a dictionary)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001742 */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001743int
1744_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
1745 PyObject **pvalue, Py_hash_t *phash)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001746{
INADA Naokica2d8be2016-11-04 16:59:10 +09001747 Py_ssize_t i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001748 PyDictObject *mp;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001749 PyDictKeyEntry *entry_ptr;
1750 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001751
1752 if (!PyDict_Check(op))
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001753 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 mp = (PyDictObject *)op;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001755 i = *ppos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001756 if (mp->ma_values) {
INADA Naokica2d8be2016-11-04 16:59:10 +09001757 if (i < 0 || i >= mp->ma_used)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001758 return 0;
INADA Naokica2d8be2016-11-04 16:59:10 +09001759 /* values of split table is always dense */
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001760 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
INADA Naokica2d8be2016-11-04 16:59:10 +09001761 value = mp->ma_values[i];
1762 assert(value != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001764 else {
INADA Naokica2d8be2016-11-04 16:59:10 +09001765 Py_ssize_t n = mp->ma_keys->dk_nentries;
1766 if (i < 0 || i >= n)
1767 return 0;
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001768 entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
1769 while (i < n && entry_ptr->me_value == NULL) {
1770 entry_ptr++;
1771 i++;
Victor Stinner742da042016-09-07 17:40:12 -07001772 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001773 if (i >= n)
1774 return 0;
1775 value = entry_ptr->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 }
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001777 *ppos = i+1;
1778 if (pkey)
1779 *pkey = entry_ptr->me_key;
1780 if (phash)
1781 *phash = entry_ptr->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001782 if (pvalue)
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001783 *pvalue = value;
1784 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001785}
1786
Tim Peters080c88b2003-02-15 03:01:11 +00001787/*
1788 * Iterate over a dict. Use like so:
1789 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001790 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +00001791 * PyObject *key, *value;
1792 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +00001793 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001794 * Refer to borrowed references in key and value.
Tim Peters080c88b2003-02-15 03:01:11 +00001795 * }
1796 *
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001797 * Return 1 on success, return 0 when the reached the end of the dictionary
1798 * (or if op is not a dictionary)
1799 *
Tim Peters080c88b2003-02-15 03:01:11 +00001800 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +00001801 * mutates the dict. One exception: it is safe if the loop merely changes
1802 * the values associated with the keys (but doesn't insert new keys or
1803 * delete keys), via PyDict_SetItem().
1804 */
Guido van Rossum25831651993-05-19 14:50:45 +00001805int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001806PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001807{
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03001808 return _PyDict_Next(op, ppos, pkey, pvalue, NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00001809}
1810
Eric Snow96c6af92015-05-29 22:21:39 -06001811/* Internal version of dict.pop(). */
1812PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001813_PyDict_Pop_KnownHash(PyObject *dict, PyObject *key, Py_hash_t hash, PyObject *deflt)
Eric Snow96c6af92015-05-29 22:21:39 -06001814{
Victor Stinner742da042016-09-07 17:40:12 -07001815 Py_ssize_t ix, hashpos;
Eric Snow96c6af92015-05-29 22:21:39 -06001816 PyObject *old_value, *old_key;
1817 PyDictKeyEntry *ep;
Yury Selivanov684ef2c2016-10-28 19:01:21 -04001818 PyDictObject *mp;
1819
1820 assert(PyDict_Check(dict));
1821 mp = (PyDictObject *)dict;
Eric Snow96c6af92015-05-29 22:21:39 -06001822
1823 if (mp->ma_used == 0) {
1824 if (deflt) {
1825 Py_INCREF(deflt);
1826 return deflt;
1827 }
1828 _PyErr_SetKeyError(key);
1829 return NULL;
1830 }
INADA Naokiba609772016-12-07 20:41:42 +09001831 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value, &hashpos);
Victor Stinner742da042016-09-07 17:40:12 -07001832 if (ix == DKIX_ERROR)
Eric Snow96c6af92015-05-29 22:21:39 -06001833 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001834 if (ix == DKIX_EMPTY || old_value == NULL) {
Eric Snow96c6af92015-05-29 22:21:39 -06001835 if (deflt) {
1836 Py_INCREF(deflt);
1837 return deflt;
1838 }
1839 _PyErr_SetKeyError(key);
1840 return NULL;
1841 }
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001842
Victor Stinner78601a32016-09-09 19:28:36 -07001843 // Split table doesn't allow deletion. Combine it.
1844 if (_PyDict_HasSplitTable(mp)) {
1845 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1846 return NULL;
1847 }
INADA Naokiba609772016-12-07 20:41:42 +09001848 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &old_value, &hashpos);
Victor Stinner78601a32016-09-09 19:28:36 -07001849 assert(ix >= 0);
1850 }
1851
Victor Stinner78601a32016-09-09 19:28:36 -07001852 assert(old_value != NULL);
Eric Snow96c6af92015-05-29 22:21:39 -06001853 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001854 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner78601a32016-09-09 19:28:36 -07001855 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1856 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1857 ENSURE_ALLOWS_DELETIONS(mp);
1858 old_key = ep->me_key;
1859 ep->me_key = NULL;
INADA Naokiba609772016-12-07 20:41:42 +09001860 ep->me_value = NULL;
Victor Stinner78601a32016-09-09 19:28:36 -07001861 Py_DECREF(old_key);
Victor Stinner611b0fa2016-09-14 15:02:01 +02001862
1863 assert(_PyDict_CheckConsistency(mp));
Eric Snow96c6af92015-05-29 22:21:39 -06001864 return old_value;
1865}
1866
Serhiy Storchaka67796522017-01-12 18:34:33 +02001867PyObject *
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001868_PyDict_Pop(PyObject *dict, PyObject *key, PyObject *deflt)
Serhiy Storchaka67796522017-01-12 18:34:33 +02001869{
1870 Py_hash_t hash;
1871
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001872 if (((PyDictObject *)dict)->ma_used == 0) {
Serhiy Storchaka67796522017-01-12 18:34:33 +02001873 if (deflt) {
1874 Py_INCREF(deflt);
1875 return deflt;
1876 }
1877 _PyErr_SetKeyError(key);
1878 return NULL;
1879 }
1880 if (!PyUnicode_CheckExact(key) ||
1881 (hash = ((PyASCIIObject *) key)->hash) == -1) {
1882 hash = PyObject_Hash(key);
1883 if (hash == -1)
1884 return NULL;
1885 }
Serhiy Storchaka42e1ea92017-01-12 19:12:21 +02001886 return _PyDict_Pop_KnownHash(dict, key, hash, deflt);
Serhiy Storchaka67796522017-01-12 18:34:33 +02001887}
1888
Eric Snow96c6af92015-05-29 22:21:39 -06001889/* Internal version of dict.from_keys(). It is subclass-friendly. */
1890PyObject *
1891_PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
1892{
1893 PyObject *it; /* iter(iterable) */
1894 PyObject *key;
1895 PyObject *d;
1896 int status;
1897
Victor Stinnera5ed5f02016-12-06 18:45:50 +01001898 d = _PyObject_CallNoArg(cls);
Eric Snow96c6af92015-05-29 22:21:39 -06001899 if (d == NULL)
1900 return NULL;
1901
1902 if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
1903 if (PyDict_CheckExact(iterable)) {
1904 PyDictObject *mp = (PyDictObject *)d;
1905 PyObject *oldvalue;
1906 Py_ssize_t pos = 0;
1907 PyObject *key;
1908 Py_hash_t hash;
1909
Serhiy Storchakac61ac162017-03-21 08:52:38 +02001910 if (dictresize(mp, ESTIMATE_SIZE(PyDict_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001911 Py_DECREF(d);
1912 return NULL;
1913 }
1914
1915 while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
1916 if (insertdict(mp, key, hash, value)) {
1917 Py_DECREF(d);
1918 return NULL;
1919 }
1920 }
1921 return d;
1922 }
1923 if (PyAnySet_CheckExact(iterable)) {
1924 PyDictObject *mp = (PyDictObject *)d;
1925 Py_ssize_t pos = 0;
1926 PyObject *key;
1927 Py_hash_t hash;
1928
Victor Stinner742da042016-09-07 17:40:12 -07001929 if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001930 Py_DECREF(d);
1931 return NULL;
1932 }
1933
1934 while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
1935 if (insertdict(mp, key, hash, value)) {
1936 Py_DECREF(d);
1937 return NULL;
1938 }
1939 }
1940 return d;
1941 }
1942 }
1943
1944 it = PyObject_GetIter(iterable);
1945 if (it == NULL){
1946 Py_DECREF(d);
1947 return NULL;
1948 }
1949
1950 if (PyDict_CheckExact(d)) {
1951 while ((key = PyIter_Next(it)) != NULL) {
1952 status = PyDict_SetItem(d, key, value);
1953 Py_DECREF(key);
1954 if (status < 0)
1955 goto Fail;
1956 }
1957 } else {
1958 while ((key = PyIter_Next(it)) != NULL) {
1959 status = PyObject_SetItem(d, key, value);
1960 Py_DECREF(key);
1961 if (status < 0)
1962 goto Fail;
1963 }
1964 }
1965
1966 if (PyErr_Occurred())
1967 goto Fail;
1968 Py_DECREF(it);
1969 return d;
1970
1971Fail:
1972 Py_DECREF(it);
1973 Py_DECREF(d);
1974 return NULL;
1975}
1976
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001977/* Methods */
1978
1979static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001980dict_dealloc(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001981{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001982 PyObject **values = mp->ma_values;
1983 PyDictKeysObject *keys = mp->ma_keys;
1984 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 PyObject_GC_UnTrack(mp);
1986 Py_TRASHCAN_SAFE_BEGIN(mp)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001987 if (values != NULL) {
1988 if (values != empty_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001989 for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001990 Py_XDECREF(values[i]);
1991 }
1992 free_values(values);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001994 DK_DECREF(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 }
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02001996 else if (keys != NULL) {
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001997 assert(keys->dk_refcnt == 1);
1998 DK_DECREF(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001999 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
2001 free_list[numfree++] = mp;
2002 else
2003 Py_TYPE(mp)->tp_free((PyObject *)mp);
2004 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002005}
2006
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002007
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002008static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002009dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 Py_ssize_t i;
Victor Stinnerf91929b2013-11-19 13:07:38 +01002012 PyObject *key = NULL, *value = NULL;
2013 _PyUnicodeWriter writer;
2014 int first;
Guido van Rossum255443b1998-04-10 22:47:14 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 i = Py_ReprEnter((PyObject *)mp);
2017 if (i != 0) {
2018 return i > 0 ? PyUnicode_FromString("{...}") : NULL;
2019 }
Guido van Rossum255443b1998-04-10 22:47:14 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 if (mp->ma_used == 0) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01002022 Py_ReprLeave((PyObject *)mp);
2023 return PyUnicode_FromString("{}");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 }
Tim Petersa7259592001-06-16 05:11:17 +00002025
Victor Stinnerf91929b2013-11-19 13:07:38 +01002026 _PyUnicodeWriter_Init(&writer);
2027 writer.overallocate = 1;
2028 /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
2029 writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +00002030
Victor Stinnerf91929b2013-11-19 13:07:38 +01002031 if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
2032 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 /* Do repr() on each key+value pair, and insert ": " between them.
2035 Note that repr may mutate the dict. */
2036 i = 0;
Victor Stinnerf91929b2013-11-19 13:07:38 +01002037 first = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01002039 PyObject *s;
2040 int res;
2041
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002042 /* Prevent repr from deleting key or value during key format. */
2043 Py_INCREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 Py_INCREF(value);
Victor Stinnerf97dfd72013-07-18 01:00:45 +02002045
Victor Stinnerf91929b2013-11-19 13:07:38 +01002046 if (!first) {
2047 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
2048 goto error;
2049 }
2050 first = 0;
2051
2052 s = PyObject_Repr(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 if (s == NULL)
Victor Stinnerf91929b2013-11-19 13:07:38 +01002054 goto error;
2055 res = _PyUnicodeWriter_WriteStr(&writer, s);
2056 Py_DECREF(s);
2057 if (res < 0)
2058 goto error;
2059
2060 if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
2061 goto error;
2062
2063 s = PyObject_Repr(value);
2064 if (s == NULL)
2065 goto error;
2066 res = _PyUnicodeWriter_WriteStr(&writer, s);
2067 Py_DECREF(s);
2068 if (res < 0)
2069 goto error;
2070
2071 Py_CLEAR(key);
2072 Py_CLEAR(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 }
Tim Petersa7259592001-06-16 05:11:17 +00002074
Victor Stinnerf91929b2013-11-19 13:07:38 +01002075 writer.overallocate = 0;
2076 if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
2077 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00002078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 Py_ReprLeave((PyObject *)mp);
Victor Stinnerf91929b2013-11-19 13:07:38 +01002080
2081 return _PyUnicodeWriter_Finish(&writer);
2082
2083error:
2084 Py_ReprLeave((PyObject *)mp);
2085 _PyUnicodeWriter_Dealloc(&writer);
2086 Py_XDECREF(key);
2087 Py_XDECREF(value);
2088 return NULL;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002089}
2090
Martin v. Löwis18e16552006-02-15 17:27:45 +00002091static Py_ssize_t
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002092dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 return mp->ma_used;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002095}
2096
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002097static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002098dict_subscript(PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002099{
Victor Stinner742da042016-09-07 17:40:12 -07002100 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002101 Py_hash_t hash;
INADA Naokiba609772016-12-07 20:41:42 +09002102 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002105 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 hash = PyObject_Hash(key);
2107 if (hash == -1)
2108 return NULL;
2109 }
INADA Naokiba609772016-12-07 20:41:42 +09002110 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value, NULL);
Victor Stinner742da042016-09-07 17:40:12 -07002111 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 return NULL;
INADA Naokiba609772016-12-07 20:41:42 +09002113 if (ix == DKIX_EMPTY || value == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 if (!PyDict_CheckExact(mp)) {
2115 /* Look up __missing__ method if we're a subclass. */
2116 PyObject *missing, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05002117 _Py_IDENTIFIER(__missing__);
2118 missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 if (missing != NULL) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002120 res = PyObject_CallFunctionObjArgs(missing,
2121 key, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 Py_DECREF(missing);
2123 return res;
2124 }
2125 else if (PyErr_Occurred())
2126 return NULL;
2127 }
Raymond Hettinger69492da2013-09-02 15:59:26 -07002128 _PyErr_SetKeyError(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 return NULL;
2130 }
INADA Naokiba609772016-12-07 20:41:42 +09002131 Py_INCREF(value);
2132 return value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002133}
2134
2135static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002136dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 if (w == NULL)
2139 return PyDict_DelItem((PyObject *)mp, v);
2140 else
2141 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002142}
2143
Guido van Rossuma9e7a811997-05-13 21:02:11 +00002144static PyMappingMethods dict_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 (lenfunc)dict_length, /*mp_length*/
2146 (binaryfunc)dict_subscript, /*mp_subscript*/
2147 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002148};
2149
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002150static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002151dict_keys(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002152{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002153 PyObject *v;
2154 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002155 PyDictKeyEntry *ep;
2156 Py_ssize_t size, n, offset;
2157 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002158
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002159 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 n = mp->ma_used;
2161 v = PyList_New(n);
2162 if (v == NULL)
2163 return NULL;
2164 if (n != mp->ma_used) {
2165 /* Durnit. The allocations caused the dict to resize.
2166 * Just start over, this shouldn't normally happen.
2167 */
2168 Py_DECREF(v);
2169 goto again;
2170 }
Victor Stinner742da042016-09-07 17:40:12 -07002171 ep = DK_ENTRIES(mp->ma_keys);
2172 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002173 if (mp->ma_values) {
2174 value_ptr = mp->ma_values;
2175 offset = sizeof(PyObject *);
2176 }
2177 else {
2178 value_ptr = &ep[0].me_value;
2179 offset = sizeof(PyDictKeyEntry);
2180 }
2181 for (i = 0, j = 0; i < size; i++) {
2182 if (*value_ptr != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 PyObject *key = ep[i].me_key;
2184 Py_INCREF(key);
2185 PyList_SET_ITEM(v, j, key);
2186 j++;
2187 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002188 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 }
2190 assert(j == n);
2191 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002192}
2193
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002194static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002195dict_values(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002196{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002197 PyObject *v;
2198 Py_ssize_t i, j;
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002199 PyDictKeyEntry *ep;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002200 Py_ssize_t size, n, offset;
2201 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002202
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002203 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 n = mp->ma_used;
2205 v = PyList_New(n);
2206 if (v == NULL)
2207 return NULL;
2208 if (n != mp->ma_used) {
2209 /* Durnit. The allocations caused the dict to resize.
2210 * Just start over, this shouldn't normally happen.
2211 */
2212 Py_DECREF(v);
2213 goto again;
2214 }
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002215 ep = DK_ENTRIES(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002216 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002217 if (mp->ma_values) {
2218 value_ptr = mp->ma_values;
2219 offset = sizeof(PyObject *);
2220 }
2221 else {
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002222 value_ptr = &ep[0].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002223 offset = sizeof(PyDictKeyEntry);
2224 }
2225 for (i = 0, j = 0; i < size; i++) {
2226 PyObject *value = *value_ptr;
2227 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2228 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 Py_INCREF(value);
2230 PyList_SET_ITEM(v, j, value);
2231 j++;
2232 }
2233 }
2234 assert(j == n);
2235 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002236}
2237
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002238static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002239dict_items(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002240{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002241 PyObject *v;
2242 Py_ssize_t i, j, n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002243 Py_ssize_t size, offset;
2244 PyObject *item, *key;
2245 PyDictKeyEntry *ep;
2246 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 /* Preallocate the list of tuples, to avoid allocations during
2249 * the loop over the items, which could trigger GC, which
2250 * could resize the dict. :-(
2251 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002252 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 n = mp->ma_used;
2254 v = PyList_New(n);
2255 if (v == NULL)
2256 return NULL;
2257 for (i = 0; i < n; i++) {
2258 item = PyTuple_New(2);
2259 if (item == NULL) {
2260 Py_DECREF(v);
2261 return NULL;
2262 }
2263 PyList_SET_ITEM(v, i, item);
2264 }
2265 if (n != mp->ma_used) {
2266 /* Durnit. The allocations caused the dict to resize.
2267 * Just start over, this shouldn't normally happen.
2268 */
2269 Py_DECREF(v);
2270 goto again;
2271 }
2272 /* Nothing we do below makes any function calls. */
Victor Stinner742da042016-09-07 17:40:12 -07002273 ep = DK_ENTRIES(mp->ma_keys);
2274 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002275 if (mp->ma_values) {
2276 value_ptr = mp->ma_values;
2277 offset = sizeof(PyObject *);
2278 }
2279 else {
2280 value_ptr = &ep[0].me_value;
2281 offset = sizeof(PyDictKeyEntry);
2282 }
2283 for (i = 0, j = 0; i < size; i++) {
2284 PyObject *value = *value_ptr;
2285 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2286 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 key = ep[i].me_key;
2288 item = PyList_GET_ITEM(v, j);
2289 Py_INCREF(key);
2290 PyTuple_SET_ITEM(item, 0, key);
2291 Py_INCREF(value);
2292 PyTuple_SET_ITEM(item, 1, value);
2293 j++;
2294 }
2295 }
2296 assert(j == n);
2297 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002298}
2299
Larry Hastings5c661892014-01-24 06:17:25 -08002300/*[clinic input]
2301@classmethod
2302dict.fromkeys
Larry Hastings5c661892014-01-24 06:17:25 -08002303 iterable: object
2304 value: object=None
2305 /
2306
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002307Create a new dictionary with keys from iterable and values set to value.
Larry Hastings5c661892014-01-24 06:17:25 -08002308[clinic start generated code]*/
2309
Larry Hastings5c661892014-01-24 06:17:25 -08002310static PyObject *
2311dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
Serhiy Storchaka78d9e582017-01-25 00:30:04 +02002312/*[clinic end generated code: output=8fb98e4b10384999 input=382ba4855d0f74c3]*/
Larry Hastings5c661892014-01-24 06:17:25 -08002313{
Eric Snow96c6af92015-05-29 22:21:39 -06002314 return _PyDict_FromKeys((PyObject *)type, iterable, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002315}
2316
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002317static int
Victor Stinner742da042016-09-07 17:40:12 -07002318dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
2319 const char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 PyObject *arg = NULL;
2322 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
2325 result = -1;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 else if (arg != NULL) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02002328 _Py_IDENTIFIER(keys);
2329 if (_PyObject_HasAttrId(arg, &PyId_keys))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 result = PyDict_Merge(self, arg, 1);
2331 else
2332 result = PyDict_MergeFromSeq2(self, arg, 1);
2333 }
2334 if (result == 0 && kwds != NULL) {
2335 if (PyArg_ValidateKeywordArguments(kwds))
2336 result = PyDict_Merge(self, kwds, 1);
2337 else
2338 result = -1;
2339 }
2340 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002341}
2342
Victor Stinner91f0d4a2017-01-19 12:45:06 +01002343/* Note: dict.update() uses the METH_VARARGS|METH_KEYWORDS calling convention.
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03002344 Using METH_FASTCALL|METH_KEYWORDS would make dict.update(**dict2) calls
2345 slower, see the issue #29312. */
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002346static PyObject *
2347dict_update(PyObject *self, PyObject *args, PyObject *kwds)
2348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 if (dict_update_common(self, args, kwds, "update") != -1)
2350 Py_RETURN_NONE;
2351 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002352}
2353
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002354/* Update unconditionally replaces existing items.
2355 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00002356 otherwise it leaves existing items unchanged.
2357
2358 PyDict_{Update,Merge} update/merge from a mapping object.
2359
Tim Petersf582b822001-12-11 18:51:08 +00002360 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00002361 producing iterable objects of length 2.
2362*/
2363
Tim Petersf582b822001-12-11 18:51:08 +00002364int
Tim Peters1fc240e2001-10-26 05:06:50 +00002365PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
2366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 PyObject *it; /* iter(seq2) */
2368 Py_ssize_t i; /* index into seq2 of current element */
2369 PyObject *item; /* seq2[i] */
2370 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00002371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 assert(d != NULL);
2373 assert(PyDict_Check(d));
2374 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 it = PyObject_GetIter(seq2);
2377 if (it == NULL)
2378 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 for (i = 0; ; ++i) {
2381 PyObject *key, *value;
2382 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 fast = NULL;
2385 item = PyIter_Next(it);
2386 if (item == NULL) {
2387 if (PyErr_Occurred())
2388 goto Fail;
2389 break;
2390 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 /* Convert item to sequence, and verify length 2. */
2393 fast = PySequence_Fast(item, "");
2394 if (fast == NULL) {
2395 if (PyErr_ExceptionMatches(PyExc_TypeError))
2396 PyErr_Format(PyExc_TypeError,
2397 "cannot convert dictionary update "
2398 "sequence element #%zd to a sequence",
2399 i);
2400 goto Fail;
2401 }
2402 n = PySequence_Fast_GET_SIZE(fast);
2403 if (n != 2) {
2404 PyErr_Format(PyExc_ValueError,
2405 "dictionary update sequence element #%zd "
2406 "has length %zd; 2 is required",
2407 i, n);
2408 goto Fail;
2409 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 /* Update/merge with this (key, value) pair. */
2412 key = PySequence_Fast_GET_ITEM(fast, 0);
2413 value = PySequence_Fast_GET_ITEM(fast, 1);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002414 Py_INCREF(key);
2415 Py_INCREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 if (override || PyDict_GetItem(d, key) == NULL) {
2417 int status = PyDict_SetItem(d, key, value);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002418 if (status < 0) {
2419 Py_DECREF(key);
2420 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 goto Fail;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002422 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 }
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002424 Py_DECREF(key);
2425 Py_DECREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 Py_DECREF(fast);
2427 Py_DECREF(item);
2428 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 i = 0;
Victor Stinner611b0fa2016-09-14 15:02:01 +02002431 assert(_PyDict_CheckConsistency((PyDictObject *)d));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00002433Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 Py_XDECREF(item);
2435 Py_XDECREF(fast);
2436 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002437Return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 Py_DECREF(it);
2439 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00002440}
2441
doko@ubuntu.comc96df682016-10-11 08:04:02 +02002442static int
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002443dict_merge(PyObject *a, PyObject *b, int override)
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002444{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002445 PyDictObject *mp, *other;
2446 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -07002447 PyDictKeyEntry *entry, *ep0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002448
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002449 assert(0 <= override && override <= 2);
2450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 /* We accept for the argument either a concrete dictionary object,
2452 * or an abstract "mapping" object. For the former, we can do
2453 * things quite efficiently. For the latter, we only require that
2454 * PyMapping_Keys() and PyObject_GetItem() be supported.
2455 */
2456 if (a == NULL || !PyDict_Check(a) || b == NULL) {
2457 PyErr_BadInternalCall();
2458 return -1;
2459 }
2460 mp = (PyDictObject*)a;
2461 if (PyDict_Check(b)) {
2462 other = (PyDictObject*)b;
2463 if (other == mp || other->ma_used == 0)
2464 /* a.update(a) or a.update({}); nothing to do */
2465 return 0;
2466 if (mp->ma_used == 0)
2467 /* Since the target dict is empty, PyDict_GetItem()
2468 * always returns NULL. Setting override to 1
2469 * skips the unnecessary test.
2470 */
2471 override = 1;
2472 /* Do one big resize at the start, rather than
2473 * incrementally resizing as we insert new items. Expect
2474 * that there will be no (or few) overlapping keys.
2475 */
INADA Naokib1152be2016-10-27 19:26:50 +09002476 if (USABLE_FRACTION(mp->ma_keys->dk_size) < other->ma_used) {
2477 if (dictresize(mp, ESTIMATE_SIZE(mp->ma_used + other->ma_used))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 return -1;
INADA Naokib1152be2016-10-27 19:26:50 +09002479 }
2480 }
Victor Stinner742da042016-09-07 17:40:12 -07002481 ep0 = DK_ENTRIES(other->ma_keys);
2482 for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002483 PyObject *key, *value;
2484 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002485 entry = &ep0[i];
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002486 key = entry->me_key;
2487 hash = entry->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002488 if (other->ma_values)
2489 value = other->ma_values[i];
2490 else
2491 value = entry->me_value;
2492
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002493 if (value != NULL) {
2494 int err = 0;
2495 Py_INCREF(key);
2496 Py_INCREF(value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002497 if (override == 1)
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002498 err = insertdict(mp, key, hash, value);
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002499 else if (_PyDict_GetItem_KnownHash(a, key, hash) == NULL) {
2500 if (PyErr_Occurred()) {
2501 Py_DECREF(value);
2502 Py_DECREF(key);
2503 return -1;
2504 }
2505 err = insertdict(mp, key, hash, value);
2506 }
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002507 else if (override != 0) {
2508 _PyErr_SetKeyError(key);
2509 Py_DECREF(value);
2510 Py_DECREF(key);
2511 return -1;
2512 }
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002513 Py_DECREF(value);
2514 Py_DECREF(key);
2515 if (err != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 return -1;
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002517
Victor Stinner742da042016-09-07 17:40:12 -07002518 if (n != other->ma_keys->dk_nentries) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002519 PyErr_SetString(PyExc_RuntimeError,
2520 "dict mutated during update");
2521 return -1;
2522 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 }
2524 }
2525 }
2526 else {
2527 /* Do it the generic, slower way */
2528 PyObject *keys = PyMapping_Keys(b);
2529 PyObject *iter;
2530 PyObject *key, *value;
2531 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 if (keys == NULL)
2534 /* Docstring says this is equivalent to E.keys() so
2535 * if E doesn't have a .keys() method we want
2536 * AttributeError to percolate up. Might as well
2537 * do the same for any other error.
2538 */
2539 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 iter = PyObject_GetIter(keys);
2542 Py_DECREF(keys);
2543 if (iter == NULL)
2544 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002547 if (override != 1 && PyDict_GetItem(a, key) != NULL) {
2548 if (override != 0) {
2549 _PyErr_SetKeyError(key);
2550 Py_DECREF(key);
2551 Py_DECREF(iter);
2552 return -1;
2553 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 Py_DECREF(key);
2555 continue;
2556 }
2557 value = PyObject_GetItem(b, key);
2558 if (value == NULL) {
2559 Py_DECREF(iter);
2560 Py_DECREF(key);
2561 return -1;
2562 }
2563 status = PyDict_SetItem(a, key, value);
2564 Py_DECREF(key);
2565 Py_DECREF(value);
2566 if (status < 0) {
2567 Py_DECREF(iter);
2568 return -1;
2569 }
2570 }
2571 Py_DECREF(iter);
2572 if (PyErr_Occurred())
2573 /* Iterator completed, via error */
2574 return -1;
2575 }
Victor Stinner611b0fa2016-09-14 15:02:01 +02002576 assert(_PyDict_CheckConsistency((PyDictObject *)a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002578}
2579
Serhiy Storchakae036ef82016-10-02 11:06:43 +03002580int
2581PyDict_Update(PyObject *a, PyObject *b)
2582{
2583 return dict_merge(a, b, 1);
2584}
2585
2586int
2587PyDict_Merge(PyObject *a, PyObject *b, int override)
2588{
2589 /* XXX Deprecate override not in (0, 1). */
2590 return dict_merge(a, b, override != 0);
2591}
2592
2593int
2594_PyDict_MergeEx(PyObject *a, PyObject *b, int override)
2595{
2596 return dict_merge(a, b, override);
2597}
2598
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002599static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002600dict_copy(PyDictObject *mp)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002603}
2604
2605PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002606PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 PyObject *copy;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002609 PyDictObject *mp;
2610 Py_ssize_t i, n;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 if (o == NULL || !PyDict_Check(o)) {
2613 PyErr_BadInternalCall();
2614 return NULL;
2615 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002616 mp = (PyDictObject *)o;
2617 if (_PyDict_HasSplitTable(mp)) {
2618 PyDictObject *split_copy;
Victor Stinner742da042016-09-07 17:40:12 -07002619 Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
2620 PyObject **newvalues;
2621 newvalues = new_values(size);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002622 if (newvalues == NULL)
2623 return PyErr_NoMemory();
2624 split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
2625 if (split_copy == NULL) {
2626 free_values(newvalues);
2627 return NULL;
2628 }
2629 split_copy->ma_values = newvalues;
2630 split_copy->ma_keys = mp->ma_keys;
2631 split_copy->ma_used = mp->ma_used;
2632 DK_INCREF(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002633 for (i = 0, n = size; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002634 PyObject *value = mp->ma_values[i];
2635 Py_XINCREF(value);
2636 split_copy->ma_values[i] = value;
2637 }
Benjamin Peterson7ce67e42012-04-24 10:32:57 -04002638 if (_PyObject_GC_IS_TRACKED(mp))
2639 _PyObject_GC_TRACK(split_copy);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002640 return (PyObject *)split_copy;
2641 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 copy = PyDict_New();
2643 if (copy == NULL)
2644 return NULL;
2645 if (PyDict_Merge(copy, o, 1) == 0)
2646 return copy;
2647 Py_DECREF(copy);
2648 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002649}
2650
Martin v. Löwis18e16552006-02-15 17:27:45 +00002651Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00002652PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00002653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 if (mp == NULL || !PyDict_Check(mp)) {
2655 PyErr_BadInternalCall();
2656 return -1;
2657 }
2658 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00002659}
2660
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002661PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002662PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 if (mp == NULL || !PyDict_Check(mp)) {
2665 PyErr_BadInternalCall();
2666 return NULL;
2667 }
2668 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002669}
2670
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002671PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002672PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 if (mp == NULL || !PyDict_Check(mp)) {
2675 PyErr_BadInternalCall();
2676 return NULL;
2677 }
2678 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002679}
2680
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002681PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002682PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 if (mp == NULL || !PyDict_Check(mp)) {
2685 PyErr_BadInternalCall();
2686 return NULL;
2687 }
2688 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002689}
2690
Tim Peterse63415e2001-05-08 04:38:29 +00002691/* Return 1 if dicts equal, 0 if not, -1 if error.
2692 * Gets out as soon as any difference is detected.
2693 * Uses only Py_EQ comparison.
2694 */
2695static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002696dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00002697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00002699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 if (a->ma_used != b->ma_used)
2701 /* can't be equal if # of entries differ */
2702 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Victor Stinner742da042016-09-07 17:40:12 -07002704 for (i = 0; i < a->ma_keys->dk_nentries; i++) {
2705 PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002706 PyObject *aval;
2707 if (a->ma_values)
2708 aval = a->ma_values[i];
2709 else
2710 aval = ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 if (aval != NULL) {
2712 int cmp;
2713 PyObject *bval;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002714 PyObject *key = ep->me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 /* temporarily bump aval's refcount to ensure it stays
2716 alive until we're done with it */
2717 Py_INCREF(aval);
2718 /* ditto for key */
2719 Py_INCREF(key);
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002720 /* reuse the known hash value */
INADA Naokiba609772016-12-07 20:41:42 +09002721 b->ma_keys->dk_lookup(b, key, ep->me_hash, &bval, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 if (bval == NULL) {
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002723 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 Py_DECREF(aval);
2725 if (PyErr_Occurred())
2726 return -1;
2727 return 0;
2728 }
2729 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03002730 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 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{
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003615 PyObject *key, *value, *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--;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003653 Py_INCREF(key);
3654 Py_INCREF(value);
3655 result = di->di_result;
3656 if (Py_REFCNT(result) == 1) {
3657 PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
3658 PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
3659 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3660 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003661 Py_INCREF(result);
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003662 Py_DECREF(oldkey);
3663 Py_DECREF(oldvalue);
Serhiy Storchaka49f5cdd2016-10-09 23:08:05 +03003664 }
3665 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 result = PyTuple_New(2);
3667 if (result == NULL)
3668 return NULL;
Serhiy Storchaka753bca32017-05-20 12:30:02 +03003669 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3670 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003672 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003673
3674fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003676 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003677 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003678}
3679
3680PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3682 "dict_itemiterator", /* tp_name */
3683 sizeof(dictiterobject), /* tp_basicsize */
3684 0, /* tp_itemsize */
3685 /* methods */
3686 (destructor)dictiter_dealloc, /* tp_dealloc */
3687 0, /* tp_print */
3688 0, /* tp_getattr */
3689 0, /* tp_setattr */
3690 0, /* tp_reserved */
3691 0, /* tp_repr */
3692 0, /* tp_as_number */
3693 0, /* tp_as_sequence */
3694 0, /* tp_as_mapping */
3695 0, /* tp_hash */
3696 0, /* tp_call */
3697 0, /* tp_str */
3698 PyObject_GenericGetAttr, /* tp_getattro */
3699 0, /* tp_setattro */
3700 0, /* tp_as_buffer */
3701 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3702 0, /* tp_doc */
3703 (traverseproc)dictiter_traverse, /* tp_traverse */
3704 0, /* tp_clear */
3705 0, /* tp_richcompare */
3706 0, /* tp_weaklistoffset */
3707 PyObject_SelfIter, /* tp_iter */
3708 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
3709 dictiter_methods, /* tp_methods */
3710 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003711};
Guido van Rossumb90c8482007-02-10 01:11:45 +00003712
3713
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003714static PyObject *
3715dictiter_reduce(dictiterobject *di)
3716{
3717 PyObject *list;
3718 dictiterobject tmp;
3719
3720 list = PyList_New(0);
3721 if (!list)
3722 return NULL;
3723
3724 /* copy the itertor state */
3725 tmp = *di;
3726 Py_XINCREF(tmp.di_dict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003727
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003728 /* iterate the temporary into a list */
3729 for(;;) {
3730 PyObject *element = 0;
3731 if (Py_TYPE(di) == &PyDictIterItem_Type)
3732 element = dictiter_iternextitem(&tmp);
3733 else if (Py_TYPE(di) == &PyDictIterKey_Type)
3734 element = dictiter_iternextkey(&tmp);
3735 else if (Py_TYPE(di) == &PyDictIterValue_Type)
3736 element = dictiter_iternextvalue(&tmp);
3737 else
3738 assert(0);
3739 if (element) {
3740 if (PyList_Append(list, element)) {
3741 Py_DECREF(element);
3742 Py_DECREF(list);
3743 Py_XDECREF(tmp.di_dict);
3744 return NULL;
3745 }
3746 Py_DECREF(element);
3747 } else
3748 break;
3749 }
3750 Py_XDECREF(tmp.di_dict);
3751 /* check for error */
3752 if (tmp.di_dict != NULL) {
3753 /* we have an error */
3754 Py_DECREF(list);
3755 return NULL;
3756 }
Antoine Pitroua7013882012-04-05 00:04:20 +02003757 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003758}
3759
Guido van Rossum3ac67412007-02-10 18:55:06 +00003760/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003761/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00003762/***********************************************/
3763
Guido van Rossumb90c8482007-02-10 01:11:45 +00003764/* The instance lay-out is the same for all three; but the type differs. */
3765
Guido van Rossumb90c8482007-02-10 01:11:45 +00003766static void
Eric Snow96c6af92015-05-29 22:21:39 -06003767dictview_dealloc(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 Py_XDECREF(dv->dv_dict);
3770 PyObject_GC_Del(dv);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003771}
3772
3773static int
Eric Snow96c6af92015-05-29 22:21:39 -06003774dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 Py_VISIT(dv->dv_dict);
3777 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003778}
3779
Guido van Rossum83825ac2007-02-10 04:54:19 +00003780static Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003781dictview_len(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 Py_ssize_t len = 0;
3784 if (dv->dv_dict != NULL)
3785 len = dv->dv_dict->ma_used;
3786 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003787}
3788
Eric Snow96c6af92015-05-29 22:21:39 -06003789PyObject *
3790_PyDictView_New(PyObject *dict, PyTypeObject *type)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003791{
Eric Snow96c6af92015-05-29 22:21:39 -06003792 _PyDictViewObject *dv;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003793 if (dict == NULL) {
3794 PyErr_BadInternalCall();
3795 return NULL;
3796 }
3797 if (!PyDict_Check(dict)) {
3798 /* XXX Get rid of this restriction later */
3799 PyErr_Format(PyExc_TypeError,
3800 "%s() requires a dict argument, not '%s'",
3801 type->tp_name, dict->ob_type->tp_name);
3802 return NULL;
3803 }
Eric Snow96c6af92015-05-29 22:21:39 -06003804 dv = PyObject_GC_New(_PyDictViewObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003805 if (dv == NULL)
3806 return NULL;
3807 Py_INCREF(dict);
3808 dv->dv_dict = (PyDictObject *)dict;
3809 _PyObject_GC_TRACK(dv);
3810 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003811}
3812
Neal Norwitze36f2ba2007-02-26 23:12:28 +00003813/* TODO(guido): The views objects are not complete:
3814
3815 * support more set operations
3816 * support arbitrary mappings?
3817 - either these should be static or exported in dictobject.h
3818 - if public then they should probably be in builtins
3819*/
3820
Guido van Rossumaac530c2007-08-24 22:33:45 +00003821/* Return 1 if self is a subset of other, iterating over self;
3822 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00003823static int
3824all_contained_in(PyObject *self, PyObject *other)
3825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 PyObject *iter = PyObject_GetIter(self);
3827 int ok = 1;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 if (iter == NULL)
3830 return -1;
3831 for (;;) {
3832 PyObject *next = PyIter_Next(iter);
3833 if (next == NULL) {
3834 if (PyErr_Occurred())
3835 ok = -1;
3836 break;
3837 }
3838 ok = PySequence_Contains(other, next);
3839 Py_DECREF(next);
3840 if (ok <= 0)
3841 break;
3842 }
3843 Py_DECREF(iter);
3844 return ok;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003845}
3846
3847static PyObject *
3848dictview_richcompare(PyObject *self, PyObject *other, int op)
3849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 Py_ssize_t len_self, len_other;
3851 int ok;
3852 PyObject *result;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003854 assert(self != NULL);
3855 assert(PyDictViewSet_Check(self));
3856 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00003857
Brian Curtindfc80e32011-08-10 20:28:54 -05003858 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
3859 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 len_self = PyObject_Size(self);
3862 if (len_self < 0)
3863 return NULL;
3864 len_other = PyObject_Size(other);
3865 if (len_other < 0)
3866 return NULL;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 ok = 0;
3869 switch(op) {
Guido van Rossumaac530c2007-08-24 22:33:45 +00003870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 case Py_NE:
3872 case Py_EQ:
3873 if (len_self == len_other)
3874 ok = all_contained_in(self, other);
3875 if (op == Py_NE && ok >= 0)
3876 ok = !ok;
3877 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 case Py_LT:
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_LE:
3885 if (len_self <= len_other)
3886 ok = all_contained_in(self, other);
3887 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 case Py_GT:
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 case Py_GE:
3895 if (len_self >= len_other)
3896 ok = all_contained_in(other, self);
3897 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 }
3900 if (ok < 0)
3901 return NULL;
3902 result = ok ? Py_True : Py_False;
3903 Py_INCREF(result);
3904 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003905}
3906
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003907static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003908dictview_repr(_PyDictViewObject *dv)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003910 PyObject *seq;
3911 PyObject *result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 seq = PySequence_List((PyObject *)dv);
3914 if (seq == NULL)
3915 return NULL;
3916
3917 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
3918 Py_DECREF(seq);
3919 return result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003920}
3921
Guido van Rossum3ac67412007-02-10 18:55:06 +00003922/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003923
3924static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003925dictkeys_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927 if (dv->dv_dict == NULL) {
3928 Py_RETURN_NONE;
3929 }
3930 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003931}
3932
3933static int
Eric Snow96c6af92015-05-29 22:21:39 -06003934dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00003935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 if (dv->dv_dict == NULL)
3937 return 0;
3938 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003939}
3940
Guido van Rossum83825ac2007-02-10 04:54:19 +00003941static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003942 (lenfunc)dictview_len, /* sq_length */
3943 0, /* sq_concat */
3944 0, /* sq_repeat */
3945 0, /* sq_item */
3946 0, /* sq_slice */
3947 0, /* sq_ass_item */
3948 0, /* sq_ass_slice */
3949 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003950};
3951
Guido van Rossum523259b2007-08-24 23:41:22 +00003952static PyObject*
3953dictviews_sub(PyObject* self, PyObject *other)
3954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 PyObject *result = PySet_New(self);
3956 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003957 _Py_IDENTIFIER(difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003959 if (result == NULL)
3960 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003961
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003962 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 if (tmp == NULL) {
3964 Py_DECREF(result);
3965 return NULL;
3966 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003968 Py_DECREF(tmp);
3969 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003970}
3971
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003972PyObject*
3973_PyDictView_Intersect(PyObject* self, PyObject *other)
Guido van Rossum523259b2007-08-24 23:41:22 +00003974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 PyObject *result = PySet_New(self);
3976 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003977 _Py_IDENTIFIER(intersection_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003979 if (result == NULL)
3980 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003981
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003982 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_intersection_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003983 if (tmp == NULL) {
3984 Py_DECREF(result);
3985 return NULL;
3986 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003988 Py_DECREF(tmp);
3989 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003990}
3991
3992static PyObject*
3993dictviews_or(PyObject* self, PyObject *other)
3994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003995 PyObject *result = PySet_New(self);
3996 PyObject *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02003997 _Py_IDENTIFIER(update);
Victor Stinnerd1a9cc22011-10-13 22:51:17 +02003998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003999 if (result == NULL)
4000 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004001
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08004002 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004003 if (tmp == NULL) {
4004 Py_DECREF(result);
4005 return NULL;
4006 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004008 Py_DECREF(tmp);
4009 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004010}
4011
4012static PyObject*
4013dictviews_xor(PyObject* self, PyObject *other)
4014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004015 PyObject *result = PySet_New(self);
4016 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004017 _Py_IDENTIFIER(symmetric_difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 if (result == NULL)
4020 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00004021
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08004022 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_symmetric_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 if (tmp == NULL) {
4024 Py_DECREF(result);
4025 return NULL;
4026 }
Guido van Rossum523259b2007-08-24 23:41:22 +00004027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 Py_DECREF(tmp);
4029 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00004030}
4031
4032static PyNumberMethods dictviews_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004033 0, /*nb_add*/
4034 (binaryfunc)dictviews_sub, /*nb_subtract*/
4035 0, /*nb_multiply*/
4036 0, /*nb_remainder*/
4037 0, /*nb_divmod*/
4038 0, /*nb_power*/
4039 0, /*nb_negative*/
4040 0, /*nb_positive*/
4041 0, /*nb_absolute*/
4042 0, /*nb_bool*/
4043 0, /*nb_invert*/
4044 0, /*nb_lshift*/
4045 0, /*nb_rshift*/
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004046 (binaryfunc)_PyDictView_Intersect, /*nb_and*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004047 (binaryfunc)dictviews_xor, /*nb_xor*/
4048 (binaryfunc)dictviews_or, /*nb_or*/
Guido van Rossum523259b2007-08-24 23:41:22 +00004049};
4050
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004051static PyObject*
4052dictviews_isdisjoint(PyObject *self, PyObject *other)
4053{
4054 PyObject *it;
4055 PyObject *item = NULL;
4056
4057 if (self == other) {
Eric Snow96c6af92015-05-29 22:21:39 -06004058 if (dictview_len((_PyDictViewObject *)self) == 0)
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004059 Py_RETURN_TRUE;
4060 else
4061 Py_RETURN_FALSE;
4062 }
4063
4064 /* Iterate over the shorter object (only if other is a set,
4065 * because PySequence_Contains may be expensive otherwise): */
4066 if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
Eric Snow96c6af92015-05-29 22:21:39 -06004067 Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004068 Py_ssize_t len_other = PyObject_Size(other);
4069 if (len_other == -1)
4070 return NULL;
4071
4072 if ((len_other > len_self)) {
4073 PyObject *tmp = other;
4074 other = self;
4075 self = tmp;
4076 }
4077 }
4078
4079 it = PyObject_GetIter(other);
4080 if (it == NULL)
4081 return NULL;
4082
4083 while ((item = PyIter_Next(it)) != NULL) {
4084 int contains = PySequence_Contains(self, item);
4085 Py_DECREF(item);
4086 if (contains == -1) {
4087 Py_DECREF(it);
4088 return NULL;
4089 }
4090
4091 if (contains) {
4092 Py_DECREF(it);
4093 Py_RETURN_FALSE;
4094 }
4095 }
4096 Py_DECREF(it);
4097 if (PyErr_Occurred())
4098 return NULL; /* PyIter_Next raised an exception. */
4099 Py_RETURN_TRUE;
4100}
4101
4102PyDoc_STRVAR(isdisjoint_doc,
4103"Return True if the view and the given iterable have a null intersection.");
4104
Guido van Rossumb90c8482007-02-10 01:11:45 +00004105static PyMethodDef dictkeys_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004106 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4107 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004108 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004109};
4110
4111PyTypeObject PyDictKeys_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4113 "dict_keys", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004114 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004115 0, /* tp_itemsize */
4116 /* methods */
4117 (destructor)dictview_dealloc, /* tp_dealloc */
4118 0, /* tp_print */
4119 0, /* tp_getattr */
4120 0, /* tp_setattr */
4121 0, /* tp_reserved */
4122 (reprfunc)dictview_repr, /* tp_repr */
4123 &dictviews_as_number, /* tp_as_number */
4124 &dictkeys_as_sequence, /* tp_as_sequence */
4125 0, /* tp_as_mapping */
4126 0, /* tp_hash */
4127 0, /* tp_call */
4128 0, /* tp_str */
4129 PyObject_GenericGetAttr, /* tp_getattro */
4130 0, /* tp_setattro */
4131 0, /* tp_as_buffer */
4132 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4133 0, /* tp_doc */
4134 (traverseproc)dictview_traverse, /* tp_traverse */
4135 0, /* tp_clear */
4136 dictview_richcompare, /* tp_richcompare */
4137 0, /* tp_weaklistoffset */
4138 (getiterfunc)dictkeys_iter, /* tp_iter */
4139 0, /* tp_iternext */
4140 dictkeys_methods, /* tp_methods */
4141 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004142};
4143
4144static PyObject *
4145dictkeys_new(PyObject *dict)
4146{
Eric Snow96c6af92015-05-29 22:21:39 -06004147 return _PyDictView_New(dict, &PyDictKeys_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004148}
4149
Guido van Rossum3ac67412007-02-10 18:55:06 +00004150/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004151
4152static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004153dictitems_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004155 if (dv->dv_dict == NULL) {
4156 Py_RETURN_NONE;
4157 }
4158 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00004159}
4160
4161static int
Eric Snow96c6af92015-05-29 22:21:39 -06004162dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00004163{
Serhiy Storchaka753bca32017-05-20 12:30:02 +03004164 int result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004165 PyObject *key, *value, *found;
4166 if (dv->dv_dict == NULL)
4167 return 0;
4168 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
4169 return 0;
4170 key = PyTuple_GET_ITEM(obj, 0);
4171 value = PyTuple_GET_ITEM(obj, 1);
Raymond Hettinger6692f012016-09-18 21:46:08 -07004172 found = PyDict_GetItemWithError((PyObject *)dv->dv_dict, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004173 if (found == NULL) {
4174 if (PyErr_Occurred())
4175 return -1;
4176 return 0;
4177 }
Serhiy Storchaka753bca32017-05-20 12:30:02 +03004178 Py_INCREF(found);
4179 result = PyObject_RichCompareBool(value, found, Py_EQ);
4180 Py_DECREF(found);
4181 return result;
Guido van Rossumb90c8482007-02-10 01:11:45 +00004182}
4183
Guido van Rossum83825ac2007-02-10 04:54:19 +00004184static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 (lenfunc)dictview_len, /* sq_length */
4186 0, /* sq_concat */
4187 0, /* sq_repeat */
4188 0, /* sq_item */
4189 0, /* sq_slice */
4190 0, /* sq_ass_item */
4191 0, /* sq_ass_slice */
4192 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004193};
4194
Guido van Rossumb90c8482007-02-10 01:11:45 +00004195static PyMethodDef dictitems_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00004196 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
4197 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004198 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004199};
4200
4201PyTypeObject PyDictItems_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4203 "dict_items", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004204 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 0, /* tp_itemsize */
4206 /* methods */
4207 (destructor)dictview_dealloc, /* tp_dealloc */
4208 0, /* tp_print */
4209 0, /* tp_getattr */
4210 0, /* tp_setattr */
4211 0, /* tp_reserved */
4212 (reprfunc)dictview_repr, /* tp_repr */
4213 &dictviews_as_number, /* tp_as_number */
4214 &dictitems_as_sequence, /* tp_as_sequence */
4215 0, /* tp_as_mapping */
4216 0, /* tp_hash */
4217 0, /* tp_call */
4218 0, /* tp_str */
4219 PyObject_GenericGetAttr, /* tp_getattro */
4220 0, /* tp_setattro */
4221 0, /* tp_as_buffer */
4222 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4223 0, /* tp_doc */
4224 (traverseproc)dictview_traverse, /* tp_traverse */
4225 0, /* tp_clear */
4226 dictview_richcompare, /* tp_richcompare */
4227 0, /* tp_weaklistoffset */
4228 (getiterfunc)dictitems_iter, /* tp_iter */
4229 0, /* tp_iternext */
4230 dictitems_methods, /* tp_methods */
4231 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004232};
4233
4234static PyObject *
4235dictitems_new(PyObject *dict)
4236{
Eric Snow96c6af92015-05-29 22:21:39 -06004237 return _PyDictView_New(dict, &PyDictItems_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004238}
4239
Guido van Rossum3ac67412007-02-10 18:55:06 +00004240/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004241
4242static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004243dictvalues_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004245 if (dv->dv_dict == NULL) {
4246 Py_RETURN_NONE;
4247 }
4248 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004249}
4250
Guido van Rossum83825ac2007-02-10 04:54:19 +00004251static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004252 (lenfunc)dictview_len, /* sq_length */
4253 0, /* sq_concat */
4254 0, /* sq_repeat */
4255 0, /* sq_item */
4256 0, /* sq_slice */
4257 0, /* sq_ass_item */
4258 0, /* sq_ass_slice */
4259 (objobjproc)0, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004260};
4261
Guido van Rossumb90c8482007-02-10 01:11:45 +00004262static PyMethodDef dictvalues_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004263 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004264};
4265
4266PyTypeObject PyDictValues_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4268 "dict_values", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004269 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004270 0, /* tp_itemsize */
4271 /* methods */
4272 (destructor)dictview_dealloc, /* tp_dealloc */
4273 0, /* tp_print */
4274 0, /* tp_getattr */
4275 0, /* tp_setattr */
4276 0, /* tp_reserved */
4277 (reprfunc)dictview_repr, /* tp_repr */
4278 0, /* tp_as_number */
4279 &dictvalues_as_sequence, /* tp_as_sequence */
4280 0, /* tp_as_mapping */
4281 0, /* tp_hash */
4282 0, /* tp_call */
4283 0, /* tp_str */
4284 PyObject_GenericGetAttr, /* tp_getattro */
4285 0, /* tp_setattro */
4286 0, /* tp_as_buffer */
4287 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4288 0, /* tp_doc */
4289 (traverseproc)dictview_traverse, /* tp_traverse */
4290 0, /* tp_clear */
4291 0, /* tp_richcompare */
4292 0, /* tp_weaklistoffset */
4293 (getiterfunc)dictvalues_iter, /* tp_iter */
4294 0, /* tp_iternext */
4295 dictvalues_methods, /* tp_methods */
4296 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004297};
4298
4299static PyObject *
4300dictvalues_new(PyObject *dict)
4301{
Eric Snow96c6af92015-05-29 22:21:39 -06004302 return _PyDictView_New(dict, &PyDictValues_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004303}
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004304
4305/* Returns NULL if cannot allocate a new PyDictKeysObject,
4306 but does not set an error */
4307PyDictKeysObject *
4308_PyDict_NewKeysForClass(void)
4309{
Victor Stinner742da042016-09-07 17:40:12 -07004310 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004311 if (keys == NULL)
4312 PyErr_Clear();
4313 else
4314 keys->dk_lookup = lookdict_split;
4315 return keys;
4316}
4317
4318#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
4319
4320PyObject *
4321PyObject_GenericGetDict(PyObject *obj, void *context)
4322{
4323 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
4324 if (dictptr == NULL) {
4325 PyErr_SetString(PyExc_AttributeError,
4326 "This object has no __dict__");
4327 return NULL;
4328 }
4329 dict = *dictptr;
4330 if (dict == NULL) {
4331 PyTypeObject *tp = Py_TYPE(obj);
4332 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
4333 DK_INCREF(CACHED_KEYS(tp));
4334 *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
4335 }
4336 else {
4337 *dictptr = dict = PyDict_New();
4338 }
4339 }
4340 Py_XINCREF(dict);
4341 return dict;
4342}
4343
4344int
4345_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
Victor Stinner742da042016-09-07 17:40:12 -07004346 PyObject *key, PyObject *value)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004347{
4348 PyObject *dict;
4349 int res;
4350 PyDictKeysObject *cached;
4351
4352 assert(dictptr != NULL);
4353 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
4354 assert(dictptr != NULL);
4355 dict = *dictptr;
4356 if (dict == NULL) {
4357 DK_INCREF(cached);
4358 dict = new_dict_with_shared_keys(cached);
4359 if (dict == NULL)
4360 return -1;
4361 *dictptr = dict;
4362 }
4363 if (value == NULL) {
4364 res = PyDict_DelItem(dict, key);
INADA Naoki2294f3a2017-02-12 13:51:30 +09004365 // Since key sharing dict doesn't allow deletion, PyDict_DelItem()
4366 // always converts dict to combined form.
4367 if ((cached = CACHED_KEYS(tp)) != NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004368 CACHED_KEYS(tp) = NULL;
4369 DK_DECREF(cached);
4370 }
Victor Stinner3d3f2642016-12-15 17:21:23 +01004371 }
4372 else {
INADA Naoki2294f3a2017-02-12 13:51:30 +09004373 int was_shared = (cached == ((PyDictObject *)dict)->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004374 res = PyDict_SetItem(dict, key, value);
INADA Naoki2294f3a2017-02-12 13:51:30 +09004375 if (was_shared &&
4376 (cached = CACHED_KEYS(tp)) != NULL &&
4377 cached != ((PyDictObject *)dict)->ma_keys) {
Victor Stinner3d3f2642016-12-15 17:21:23 +01004378 /* PyDict_SetItem() may call dictresize and convert split table
4379 * into combined table. In such case, convert it to split
4380 * table again and update type's shared key only when this is
4381 * the only dict sharing key with the type.
4382 *
4383 * This is to allow using shared key in class like this:
4384 *
4385 * class C:
4386 * def __init__(self):
4387 * # one dict resize happens
4388 * self.a, self.b, self.c = 1, 2, 3
4389 * self.d, self.e, self.f = 4, 5, 6
4390 * a = C()
4391 */
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004392 if (cached->dk_refcnt == 1) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004393 CACHED_KEYS(tp) = make_keys_shared(dict);
Victor Stinner742da042016-09-07 17:40:12 -07004394 }
4395 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004396 CACHED_KEYS(tp) = NULL;
4397 }
4398 DK_DECREF(cached);
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004399 if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
4400 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004401 }
4402 }
4403 } else {
4404 dict = *dictptr;
4405 if (dict == NULL) {
4406 dict = PyDict_New();
4407 if (dict == NULL)
4408 return -1;
4409 *dictptr = dict;
4410 }
4411 if (value == NULL) {
4412 res = PyDict_DelItem(dict, key);
4413 } else {
4414 res = PyDict_SetItem(dict, key, value);
4415 }
4416 }
4417 return res;
4418}
4419
4420void
4421_PyDictKeys_DecRef(PyDictKeysObject *keys)
4422{
4423 DK_DECREF(keys);
4424}