blob: 91a4e7d55981dbc4c70f32a0adcab4851e0c7074 [file] [log] [blame]
Guido van Rossum2bc13791999-03-24 19:06:42 +00001/* Dictionary object implementation using a hash table */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002
Raymond Hettinger930427b2003-05-03 06:51:59 +00003/* The distribution includes a separate file, Objects/dictnotes.txt,
Tim Peters60b29962006-01-01 01:19:23 +00004 describing explorations into dictionary design and optimization.
Raymond Hettinger930427b2003-05-03 06:51:59 +00005 It covers typical dictionary use patterns, the parameters for
6 tuning dictionaries, and several ideas for possible optimizations.
7*/
8
Victor Stinner742da042016-09-07 17:40:12 -07009/* PyDictKeysObject
10
11This implements the dictionary's hashtable.
12
Berker Peksag71c01d42016-09-09 03:57:23 +030013As of Python 3.6, this is compact and ordered. Basic idea is described here.
Benjamin Peterson003f0592016-09-08 10:14:31 -070014https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html
Victor Stinner742da042016-09-07 17:40:12 -070015
16layout:
17
18+---------------+
19| dk_refcnt |
20| dk_size |
21| dk_lookup |
22| dk_usable |
23| dk_nentries |
24+---------------+
25| dk_indices |
26| |
27+---------------+
28| dk_entries |
29| |
30+---------------+
31
32dk_indices is actual hashtable. It holds index in entries, or DKIX_EMPTY(-1)
33or DKIX_DUMMY(-2).
34Size of indices is dk_size. Type of each index in indices is vary on dk_size:
35
36* int8 for dk_size <= 128
37* int16 for 256 <= dk_size <= 2**15
38* int32 for 2**16 <= dk_size <= 2**31
39* int64 for 2**32 <= dk_size
40
41dk_entries is array of PyDictKeyEntry. It's size is USABLE_FRACTION(dk_size).
42DK_ENTRIES(dk) can be used to get pointer to entries.
43
44NOTE: Since negative value is used for DKIX_EMPTY and DKIX_DUMMY, type of
45dk_indices entry is signed integer and int16 is used for table which
46dk_size == 256.
47*/
48
Benjamin Peterson7d95e402012-04-23 11:24:50 -040049
50/*
Benjamin Peterson7d95e402012-04-23 11:24:50 -040051The DictObject can be in one of two forms.
Victor Stinner742da042016-09-07 17:40:12 -070052
Benjamin Peterson7d95e402012-04-23 11:24:50 -040053Either:
54 A combined table:
55 ma_values == NULL, dk_refcnt == 1.
56 Values are stored in the me_value field of the PyDictKeysObject.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040057Or:
58 A split table:
59 ma_values != NULL, dk_refcnt >= 1
60 Values are stored in the ma_values array.
Victor Stinner742da042016-09-07 17:40:12 -070061 Only string (unicode) keys are allowed.
62 All dicts sharing same key must have same insertion order.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040063
Victor Stinner742da042016-09-07 17:40:12 -070064There are four kinds of slots in the table (slot is index, and
65DK_ENTRIES(keys)[index] if index >= 0):
66
671. Unused. index == DKIX_EMPTY
68 Does not hold an active (key, value) pair now and never did. Unused can
69 transition to Active upon key insertion. This is each slot's initial state.
70
712. Active. index >= 0, me_key != NULL and me_value != NULL
72 Holds an active (key, value) pair. Active can transition to Dummy or
73 Pending upon key deletion (for combined and split tables respectively).
74 This is the only case in which me_value != NULL.
75
763. Dummy. index == DKIX_DUMMY (combined only)
77 Previously held an active (key, value) pair, but that was deleted and an
78 active pair has not yet overwritten the slot. Dummy can transition to
79 Active upon key insertion. Dummy slots cannot be made Unused again
80 else the probe sequence in case of collision would have no way to know
81 they were once active.
82
834. Pending. index >= 0, key != NULL, and value == NULL (split only)
84 Not yet inserted in split-table.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040085*/
86
Victor Stinner742da042016-09-07 17:40:12 -070087/*
88Preserving insertion order
Benjamin Peterson7d95e402012-04-23 11:24:50 -040089
Victor Stinner742da042016-09-07 17:40:12 -070090It's simple for combined table. Since dk_entries is mostly append only, we can
91get insertion order by just iterating dk_entries.
92
93One exception is .popitem(). It removes last item in dk_entries and decrement
94dk_nentries to achieve amortized O(1). Since there are DKIX_DUMMY remains in
95dk_indices, we can't increment dk_usable even though dk_nentries is
96decremented.
97
98In split table, inserting into pending entry is allowed only for dk_entries[ix]
99where ix == mp->ma_used. Inserting into other index and deleting item cause
100converting the dict to the combined table.
101*/
102
103/* PyDict_MINSIZE is the starting size for any new dict.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400104 * 8 allows dicts with no more than 5 active entries; experiments suggested
105 * this suffices for the majority of dicts (consisting mostly of usually-small
106 * dicts created to pass keyword arguments).
107 * Making this 8, rather than 4 reduces the number of resizes for most
108 * dictionaries, without any significant extra memory use.
109 */
Victor Stinner742da042016-09-07 17:40:12 -0700110#define PyDict_MINSIZE 8
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400111
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112#include "Python.h"
Eric Snow96c6af92015-05-29 22:21:39 -0600113#include "dict-common.h"
Victor Stinner990397e2016-09-09 20:22:59 -0700114#include "stringlib/eq.h" /* to get unicode_eq() */
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000115
Larry Hastings61272b72014-01-07 12:41:53 -0800116/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -0800117class dict "PyDictObject *" "&PyDict_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800118[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -0800119/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f157a5a0ce9589d6]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800120
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400121
122/*
123To ensure the lookup algorithm terminates, there must be at least one Unused
124slot (NULL key) in the table.
125To avoid slowing down lookups on a near-full table, we resize the table when
126it's USABLE_FRACTION (currently two-thirds) full.
127*/
Guido van Rossum16e93a81997-01-28 00:00:11 +0000128
Tim Peterseb28ef22001-06-02 05:27:19 +0000129#define PERTURB_SHIFT 5
130
Guido van Rossum16e93a81997-01-28 00:00:11 +0000131/*
Tim Peterseb28ef22001-06-02 05:27:19 +0000132Major subtleties ahead: Most hash schemes depend on having a "good" hash
133function, in the sense of simulating randomness. Python doesn't: its most
R David Murray537ad7a2016-07-10 12:33:18 -0400134important hash functions (for ints) are very regular in common
Tim Peterseb28ef22001-06-02 05:27:19 +0000135cases:
Tim Peters15d49292001-05-27 07:39:22 +0000136
R David Murray537ad7a2016-07-10 12:33:18 -0400137 >>>[hash(i) for i in range(4)]
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000138 [0, 1, 2, 3]
Tim Peters15d49292001-05-27 07:39:22 +0000139
Tim Peterseb28ef22001-06-02 05:27:19 +0000140This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
141the low-order i bits as the initial table index is extremely fast, and there
R David Murray537ad7a2016-07-10 12:33:18 -0400142are no collisions at all for dicts indexed by a contiguous range of ints. So
143this gives better-than-random behavior in common cases, and that's very
144desirable.
Tim Peters15d49292001-05-27 07:39:22 +0000145
Tim Peterseb28ef22001-06-02 05:27:19 +0000146OTOH, when collisions occur, the tendency to fill contiguous slices of the
147hash table makes a good collision resolution strategy crucial. Taking only
148the last i bits of the hash code is also vulnerable: for example, consider
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149the list [i << 16 for i in range(20000)] as a set of keys. Since ints are
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000150their own hash codes, and this fits in a dict of size 2**15, the last 15 bits
151 of every hash code are all 0: they *all* map to the same table index.
Tim Peters15d49292001-05-27 07:39:22 +0000152
Tim Peterseb28ef22001-06-02 05:27:19 +0000153But catering to unusual cases should not slow the usual ones, so we just take
154the last i bits anyway. It's up to collision resolution to do the rest. If
155we *usually* find the key we're looking for on the first try (and, it turns
156out, we usually do -- the table load factor is kept under 2/3, so the odds
157are solidly in our favor), then it makes best sense to keep the initial index
158computation dirt cheap.
Tim Peters15d49292001-05-27 07:39:22 +0000159
Tim Peterseb28ef22001-06-02 05:27:19 +0000160The first half of collision resolution is to visit table indices via this
161recurrence:
Tim Peters15d49292001-05-27 07:39:22 +0000162
Tim Peterseb28ef22001-06-02 05:27:19 +0000163 j = ((5*j) + 1) mod 2**i
Tim Peters15d49292001-05-27 07:39:22 +0000164
Tim Peterseb28ef22001-06-02 05:27:19 +0000165For any initial j in range(2**i), repeating that 2**i times generates each
166int in range(2**i) exactly once (see any text on random-number generation for
167proof). By itself, this doesn't help much: like linear probing (setting
168j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
169order. This would be bad, except that's not the only thing we do, and it's
170actually *good* in the common cases where hash keys are consecutive. In an
171example that's really too small to make this entirely clear, for a table of
172size 2**3 the order of indices is:
Tim Peters15d49292001-05-27 07:39:22 +0000173
Tim Peterseb28ef22001-06-02 05:27:19 +0000174 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
175
176If two things come in at index 5, the first place we look after is index 2,
177not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
178Linear probing is deadly in this case because there the fixed probe order
179is the *same* as the order consecutive keys are likely to arrive. But it's
180extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
181and certain that consecutive hash codes do not.
182
183The other half of the strategy is to get the other bits of the hash code
184into play. This is done by initializing a (unsigned) vrbl "perturb" to the
185full hash code, and changing the recurrence to:
186
187 j = (5*j) + 1 + perturb;
188 perturb >>= PERTURB_SHIFT;
189 use j % 2**i as the next table index;
190
191Now the probe sequence depends (eventually) on every bit in the hash code,
192and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
193because it quickly magnifies small differences in the bits that didn't affect
194the initial index. Note that because perturb is unsigned, if the recurrence
195is executed often enough perturb eventually becomes and remains 0. At that
196point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
197that's certain to find an empty slot eventually (since it generates every int
198in range(2**i), and we make sure there's always at least one empty slot).
199
200Selecting a good value for PERTURB_SHIFT is a balancing act. You want it
201small so that the high bits of the hash code continue to affect the probe
202sequence across iterations; but you want it large so that in really bad cases
203the high-order hash bits have an effect on early iterations. 5 was "the
204best" in minimizing total collisions across experiments Tim Peters ran (on
205both normal and pathological cases), but 4 and 6 weren't significantly worse.
206
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000207Historical: Reimer Behrends contributed the idea of using a polynomial-based
Tim Peterseb28ef22001-06-02 05:27:19 +0000208approach, using repeated multiplication by x in GF(2**n) where an irreducible
209polynomial for each table size was chosen such that x was a primitive root.
210Christian Tismer later extended that to use division by x instead, as an
211efficient way to get the high bits of the hash code into play. This scheme
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000212also gave excellent collision statistics, but was more expensive: two
213if-tests were required inside the loop; computing "the next" index took about
214the same number of operations but without as much potential parallelism
215(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
216above, and then shifting perturb can be done while the table index is being
217masked); and the PyDictObject struct required a member to hold the table's
218polynomial. In Tim's experiments the current scheme ran faster, produced
219equally good collision statistics, needed less code & used less memory.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000220
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000221*/
Tim Petersdea48ec2001-05-22 20:40:22 +0000222
Fred Drake1bff34a2000-08-31 19:31:38 +0000223/* forward declarations */
Victor Stinner742da042016-09-07 17:40:12 -0700224static Py_ssize_t lookdict(PyDictObject *mp, PyObject *key,
225 Py_hash_t hash, PyObject ***value_addr,
226 Py_ssize_t *hashpos);
227static Py_ssize_t lookdict_unicode(PyDictObject *mp, PyObject *key,
228 Py_hash_t hash, PyObject ***value_addr,
229 Py_ssize_t *hashpos);
230static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400231lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700232 Py_hash_t hash, PyObject ***value_addr,
233 Py_ssize_t *hashpos);
234static Py_ssize_t lookdict_split(PyDictObject *mp, PyObject *key,
235 Py_hash_t hash, PyObject ***value_addr,
236 Py_ssize_t *hashpos);
Fred Drake1bff34a2000-08-31 19:31:38 +0000237
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400238static int dictresize(PyDictObject *mp, Py_ssize_t minused);
Tim Petersdea48ec2001-05-22 20:40:22 +0000239
Benjamin Peterson3c569292016-09-08 13:16:41 -0700240/*Global counter used to set ma_version_tag field of dictionary.
Victor Stinner3b6a6b42016-09-08 12:51:24 -0700241 * It is incremented each time that a dictionary is created and each
242 * time that a dictionary is modified. */
243static uint64_t pydict_global_version = 0;
244
245#define DICT_NEXT_VERSION() (++pydict_global_version)
246
Victor Stinner742da042016-09-07 17:40:12 -0700247/* Dictionary reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +0000248#ifndef PyDict_MAXFREELIST
249#define PyDict_MAXFREELIST 80
250#endif
251static PyDictObject *free_list[PyDict_MAXFREELIST];
252static int numfree = 0;
Victor Stinner742da042016-09-07 17:40:12 -0700253static PyDictKeysObject *keys_free_list[PyDict_MAXFREELIST];
254static int numfreekeys = 0;
Raymond Hettinger43442782004-03-17 21:55:03 +0000255
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300256#include "clinic/dictobject.c.h"
257
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100258int
259PyDict_ClearFreeList(void)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 PyDictObject *op;
Victor Stinner742da042016-09-07 17:40:12 -0700262 int ret = numfree + numfreekeys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 while (numfree) {
264 op = free_list[--numfree];
265 assert(PyDict_CheckExact(op));
266 PyObject_GC_Del(op);
267 }
Victor Stinner742da042016-09-07 17:40:12 -0700268 while (numfreekeys) {
269 PyObject_FREE(keys_free_list[--numfreekeys]);
270 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100271 return ret;
272}
273
David Malcolm49526f42012-06-22 14:55:41 -0400274/* Print summary info about the state of the optimized allocator */
275void
276_PyDict_DebugMallocStats(FILE *out)
277{
278 _PyDebugAllocatorStats(out,
279 "free PyDictObject", numfree, sizeof(PyDictObject));
280}
281
282
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100283void
284PyDict_Fini(void)
285{
286 PyDict_ClearFreeList();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000287}
288
Victor Stinner742da042016-09-07 17:40:12 -0700289#define DK_SIZE(dk) ((dk)->dk_size)
290#if SIZEOF_VOID_P > 4
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700291#define DK_IXSIZE(dk) \
292 (DK_SIZE(dk) <= 0xff ? \
293 1 : DK_SIZE(dk) <= 0xffff ? \
294 2 : DK_SIZE(dk) <= 0xffffffff ? \
Benjamin Peterson3c569292016-09-08 13:16:41 -0700295 4 : sizeof(int64_t))
Victor Stinner742da042016-09-07 17:40:12 -0700296#else
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700297#define DK_IXSIZE(dk) \
298 (DK_SIZE(dk) <= 0xff ? \
299 1 : DK_SIZE(dk) <= 0xffff ? \
Benjamin Peterson3c569292016-09-08 13:16:41 -0700300 2 : sizeof(int32_t))
Victor Stinner742da042016-09-07 17:40:12 -0700301#endif
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700302#define DK_ENTRIES(dk) \
Benjamin Peterson186122e2016-09-08 12:20:12 -0700303 ((PyDictKeyEntry*)(&(dk)->dk_indices.as_1[DK_SIZE(dk) * DK_IXSIZE(dk)]))
Victor Stinner742da042016-09-07 17:40:12 -0700304
Antoine Pitrou2d169b22012-05-12 23:43:44 +0200305#define DK_DEBUG_INCREF _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA
306#define DK_DEBUG_DECREF _Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA
307
308#define DK_INCREF(dk) (DK_DEBUG_INCREF ++(dk)->dk_refcnt)
309#define DK_DECREF(dk) if (DK_DEBUG_DECREF (--(dk)->dk_refcnt) == 0) free_keys_object(dk)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400310#define DK_MASK(dk) (((dk)->dk_size)-1)
311#define IS_POWER_OF_2(x) (((x) & (x-1)) == 0)
312
Victor Stinner742da042016-09-07 17:40:12 -0700313
314/* 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 }
Victor Stinner742da042016-09-07 17:40:12 -0700329 else if (s <= 0xffffffff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700330 int32_t *indices = keys->dk_indices.as_4;
Victor Stinner208857e2016-09-08 11:35:46 -0700331 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700332 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700333#if SIZEOF_VOID_P > 4
Victor Stinner742da042016-09-07 17:40:12 -0700334 else {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700335 int64_t *indices = keys->dk_indices.as_8;
Victor Stinner208857e2016-09-08 11:35:46 -0700336 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700337 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700338#endif
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 }
Victor Stinner742da042016-09-07 17:40:12 -0700361 else if (s <= 0xffffffff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700362 int32_t *indices = keys->dk_indices.as_4;
Victor Stinner71211e32016-09-08 10:52:46 -0700363 assert(ix <= 0x7fffffff);
Victor Stinner208857e2016-09-08 11:35:46 -0700364 indices[i] = (int32_t)ix;
Victor Stinner742da042016-09-07 17:40:12 -0700365 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700366#if SIZEOF_VOID_P > 4
Victor Stinner742da042016-09-07 17:40:12 -0700367 else {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700368 int64_t *indices = keys->dk_indices.as_8;
Victor Stinner208857e2016-09-08 11:35:46 -0700369 indices[i] = ix;
Victor Stinner742da042016-09-07 17:40:12 -0700370 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700371#endif
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 */
392#define ESTIMATE_SIZE(n) (((n)*3) >> 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 = {
423 2, /* dk_refcnt 1 for this struct, 1 for dummy_struct */
424 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
436static PyDictKeysObject *new_keys_object(Py_ssize_t size)
437{
438 PyDictKeysObject *dk;
Victor Stinner742da042016-09-07 17:40:12 -0700439 Py_ssize_t es, usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400440
Victor Stinner742da042016-09-07 17:40:12 -0700441 assert(size >= PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400442 assert(IS_POWER_OF_2(size));
Victor Stinner742da042016-09-07 17:40:12 -0700443
444 usable = USABLE_FRACTION(size);
445 if (size <= 0xff) {
446 es = 1;
447 }
448 else if (size <= 0xffff) {
449 es = 2;
450 }
451#if SIZEOF_VOID_P > 4
452 else if (size <= 0xffffffff) {
453 es = 4;
454 }
455#endif
456 else {
457 es = sizeof(Py_ssize_t);
458 }
459
460 if (size == PyDict_MINSIZE && numfreekeys > 0) {
461 dk = keys_free_list[--numfreekeys];
462 }
463 else {
Victor Stinner98ee9d52016-09-08 09:33:56 -0700464 dk = PyObject_MALLOC(sizeof(PyDictKeysObject)
465 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
466 + es * size
467 + sizeof(PyDictKeyEntry) * usable);
Victor Stinner742da042016-09-07 17:40:12 -0700468 if (dk == NULL) {
469 PyErr_NoMemory();
470 return NULL;
471 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400472 }
Antoine Pitrou2d169b22012-05-12 23:43:44 +0200473 DK_DEBUG_INCREF dk->dk_refcnt = 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400474 dk->dk_size = size;
Victor Stinner742da042016-09-07 17:40:12 -0700475 dk->dk_usable = usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400476 dk->dk_lookup = lookdict_unicode_nodummy;
Victor Stinner742da042016-09-07 17:40:12 -0700477 dk->dk_nentries = 0;
Benjamin Peterson186122e2016-09-08 12:20:12 -0700478 memset(&dk->dk_indices.as_1[0], 0xff, es * size);
Victor Stinner742da042016-09-07 17:40:12 -0700479 memset(DK_ENTRIES(dk), 0, sizeof(PyDictKeyEntry) * usable);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400480 return dk;
481}
482
483static void
484free_keys_object(PyDictKeysObject *keys)
485{
Victor Stinner742da042016-09-07 17:40:12 -0700486 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400487 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -0700488 for (i = 0, n = keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400489 Py_XDECREF(entries[i].me_key);
490 Py_XDECREF(entries[i].me_value);
491 }
Victor Stinner742da042016-09-07 17:40:12 -0700492 if (keys->dk_size == PyDict_MINSIZE && numfreekeys < PyDict_MAXFREELIST) {
493 keys_free_list[numfreekeys++] = keys;
494 return;
495 }
Raymond Hettingerce5179f2016-01-31 08:56:21 -0800496 PyObject_FREE(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400497}
498
499#define new_values(size) PyMem_NEW(PyObject *, size)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400500#define free_values(values) PyMem_FREE(values)
501
502/* Consumes a reference to the keys object */
503static PyObject *
504new_dict(PyDictKeysObject *keys, PyObject **values)
505{
506 PyDictObject *mp;
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200507 assert(keys != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 if (numfree) {
509 mp = free_list[--numfree];
510 assert (mp != NULL);
511 assert (Py_TYPE(mp) == &PyDict_Type);
512 _Py_NewReference((PyObject *)mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400514 else {
515 mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
516 if (mp == NULL) {
517 DK_DECREF(keys);
518 free_values(values);
519 return NULL;
520 }
521 }
522 mp->ma_keys = keys;
523 mp->ma_values = values;
524 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -0700525 mp->ma_version_tag = DICT_NEXT_VERSION();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000527}
528
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400529/* Consumes a reference to the keys object */
530static PyObject *
531new_dict_with_shared_keys(PyDictKeysObject *keys)
532{
533 PyObject **values;
534 Py_ssize_t i, size;
535
Victor Stinner742da042016-09-07 17:40:12 -0700536 size = USABLE_FRACTION(DK_SIZE(keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400537 values = new_values(size);
538 if (values == NULL) {
539 DK_DECREF(keys);
540 return PyErr_NoMemory();
541 }
542 for (i = 0; i < size; i++) {
543 values[i] = NULL;
544 }
545 return new_dict(keys, values);
546}
547
548PyObject *
549PyDict_New(void)
550{
Victor Stinner742da042016-09-07 17:40:12 -0700551 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200552 if (keys == NULL)
553 return NULL;
554 return new_dict(keys, NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400555}
556
Victor Stinner742da042016-09-07 17:40:12 -0700557/* Search index of hash table from offset of entry table */
558static Py_ssize_t
559lookdict_index(PyDictKeysObject *k, Py_hash_t hash, Py_ssize_t index)
560{
561 size_t i, perturb;
562 size_t mask = DK_MASK(k);
563 Py_ssize_t ix;
564
565 i = (size_t)hash & mask;
566 ix = dk_get_index(k, i);
567 if (ix == index) {
568 return i;
569 }
570 if (ix == DKIX_EMPTY) {
571 return DKIX_EMPTY;
572 }
573
574 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
575 i = mask & ((i << 2) + i + perturb + 1);
576 ix = dk_get_index(k, i);
577 if (ix == index) {
578 return i;
579 }
580 if (ix == DKIX_EMPTY) {
581 return DKIX_EMPTY;
582 }
583 }
584 assert(0); /* NOT REACHED */
585 return DKIX_ERROR;
586}
587
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000588/*
589The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000590This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000591Open addressing is preferred over chaining since the link overhead for
592chaining would be substantial (100% with typical malloc overhead).
593
Tim Peterseb28ef22001-06-02 05:27:19 +0000594The initial probe index is computed as hash mod the table size. Subsequent
595probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000596
597All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000598
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000599The details in this version are due to Tim Peters, building on many past
Tim Peterseb28ef22001-06-02 05:27:19 +0000600contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000601Christian Tismer.
Fred Drake1bff34a2000-08-31 19:31:38 +0000602
Victor Stinner742da042016-09-07 17:40:12 -0700603lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a
Victor Stinnera4348cc2016-09-08 12:01:25 -0700604comparison raises an exception.
Guido van Rossum89d8c602007-09-18 17:26:56 +0000605lookdict_unicode() below is specialized to string keys, comparison of which can
Victor Stinner742da042016-09-07 17:40:12 -0700606never raise an exception; that function can never return DKIX_ERROR.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400607lookdict_unicode_nodummy is further specialized for string keys that cannot be
608the <dummy> value.
Victor Stinner742da042016-09-07 17:40:12 -0700609For both, when the key isn't found a DKIX_EMPTY is returned. hashpos returns
610where the key index should be inserted.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000611*/
Victor Stinner742da042016-09-07 17:40:12 -0700612static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400613lookdict(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700614 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000615{
Victor Stinner742da042016-09-07 17:40:12 -0700616 size_t i, perturb, mask;
617 Py_ssize_t ix, freeslot;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200618 int cmp;
Victor Stinner742da042016-09-07 17:40:12 -0700619 PyDictKeysObject *dk;
620 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 PyObject *startkey;
Tim Peterseb28ef22001-06-02 05:27:19 +0000622
Antoine Pitrou9a234902012-05-13 20:48:01 +0200623top:
Victor Stinner742da042016-09-07 17:40:12 -0700624 dk = mp->ma_keys;
625 mask = DK_MASK(dk);
626 ep0 = DK_ENTRIES(dk);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700628
629 ix = dk_get_index(dk, i);
630 if (ix == DKIX_EMPTY) {
631 if (hashpos != NULL)
632 *hashpos = i;
633 *value_addr = NULL;
634 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400635 }
Victor Stinner742da042016-09-07 17:40:12 -0700636 if (ix == DKIX_DUMMY) {
637 freeslot = i;
638 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 else {
Victor Stinner742da042016-09-07 17:40:12 -0700640 ep = &ep0[ix];
641 if (ep->me_key == key) {
642 *value_addr = &ep->me_value;
643 if (hashpos != NULL)
644 *hashpos = i;
645 return ix;
646 }
647 if (ep->me_key != NULL && ep->me_hash == hash) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 startkey = ep->me_key;
649 Py_INCREF(startkey);
650 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
651 Py_DECREF(startkey);
652 if (cmp < 0)
Victor Stinner742da042016-09-07 17:40:12 -0700653 return DKIX_ERROR;
654 if (dk == mp->ma_keys && ep->me_key == startkey) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400655 if (cmp > 0) {
656 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700657 if (hashpos != NULL)
658 *hashpos = i;
659 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400660 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 }
662 else {
Antoine Pitrou9a234902012-05-13 20:48:01 +0200663 /* The dict was mutated, restart */
664 goto top;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 }
666 }
Victor Stinner742da042016-09-07 17:40:12 -0700667 freeslot = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 }
Tim Peters15d49292001-05-27 07:39:22 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700671 i = ((i << 2) + i + perturb + 1) & mask;
672 ix = dk_get_index(dk, i);
673 if (ix == DKIX_EMPTY) {
674 if (hashpos != NULL) {
675 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400676 }
Victor Stinner742da042016-09-07 17:40:12 -0700677 *value_addr = NULL;
678 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400679 }
Victor Stinner742da042016-09-07 17:40:12 -0700680 if (ix == DKIX_DUMMY) {
681 if (freeslot == -1)
682 freeslot = i;
683 continue;
684 }
685 ep = &ep0[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400686 if (ep->me_key == key) {
Victor Stinner742da042016-09-07 17:40:12 -0700687 if (hashpos != NULL) {
688 *hashpos = i;
689 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400690 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700691 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400692 }
Victor Stinner742da042016-09-07 17:40:12 -0700693 if (ep->me_hash == hash && ep->me_key != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 startkey = ep->me_key;
695 Py_INCREF(startkey);
696 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
697 Py_DECREF(startkey);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400698 if (cmp < 0) {
699 *value_addr = NULL;
Victor Stinner742da042016-09-07 17:40:12 -0700700 return DKIX_ERROR;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400701 }
Victor Stinner742da042016-09-07 17:40:12 -0700702 if (dk == mp->ma_keys && ep->me_key == startkey) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400703 if (cmp > 0) {
Victor Stinner742da042016-09-07 17:40:12 -0700704 if (hashpos != NULL) {
705 *hashpos = i;
706 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400707 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700708 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400709 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 }
711 else {
Antoine Pitrou9a234902012-05-13 20:48:01 +0200712 /* The dict was mutated, restart */
713 goto top;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 }
715 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 }
717 assert(0); /* NOT REACHED */
718 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000719}
720
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400721/* Specialized version for string-only keys */
Victor Stinner742da042016-09-07 17:40:12 -0700722static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400723lookdict_unicode(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700724 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Fred Drake1bff34a2000-08-31 19:31:38 +0000725{
Victor Stinner742da042016-09-07 17:40:12 -0700726 size_t i, perturb;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200727 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700728 Py_ssize_t ix, freeslot;
729 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Fred Drake1bff34a2000-08-31 19:31:38 +0000730
Victor Stinner742da042016-09-07 17:40:12 -0700731 assert(mp->ma_values == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 /* Make sure this function doesn't have to handle non-unicode keys,
733 including subclasses of str; e.g., one reason to subclass
734 unicodes is to override __eq__, and for speed we don't cater to
735 that here. */
736 if (!PyUnicode_CheckExact(key)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400737 mp->ma_keys->dk_lookup = lookdict;
Victor Stinner742da042016-09-07 17:40:12 -0700738 return lookdict(mp, key, hash, value_addr, hashpos);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 }
Mark Dickinson57e683e2011-09-24 18:18:40 +0100740 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700741 ix = dk_get_index(mp->ma_keys, i);
742 if (ix == DKIX_EMPTY) {
743 if (hashpos != NULL)
744 *hashpos = i;
745 *value_addr = NULL;
746 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400747 }
Victor Stinner742da042016-09-07 17:40:12 -0700748 if (ix == DKIX_DUMMY) {
749 freeslot = i;
750 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 else {
Victor Stinner742da042016-09-07 17:40:12 -0700752 ep = &ep0[ix];
753 /* only split table can be ix != DKIX_DUMMY && me_key == NULL */
754 assert(ep->me_key != NULL);
755 if (ep->me_key == key || (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
756 if (hashpos != NULL)
757 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400758 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700759 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400760 }
Victor Stinner742da042016-09-07 17:40:12 -0700761 freeslot = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 }
Tim Peters15d49292001-05-27 07:39:22 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700765 i = mask & ((i << 2) + i + perturb + 1);
766 ix = dk_get_index(mp->ma_keys, i);
767 if (ix == DKIX_EMPTY) {
768 if (hashpos != NULL) {
769 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400770 }
Victor Stinner742da042016-09-07 17:40:12 -0700771 *value_addr = NULL;
772 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400773 }
Victor Stinner742da042016-09-07 17:40:12 -0700774 if (ix == DKIX_DUMMY) {
775 if (freeslot == -1)
776 freeslot = i;
777 continue;
778 }
779 ep = &ep0[ix];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 if (ep->me_key == key
781 || (ep->me_hash == hash
Victor Stinner742da042016-09-07 17:40:12 -0700782 && ep->me_key != NULL
783 && unicode_eq(ep->me_key, key))) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400784 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700785 if (hashpos != NULL) {
786 *hashpos = i;
787 }
788 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400789 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 }
791 assert(0); /* NOT REACHED */
792 return 0;
Fred Drake1bff34a2000-08-31 19:31:38 +0000793}
794
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400795/* Faster version of lookdict_unicode when it is known that no <dummy> keys
796 * will be present. */
Victor Stinner742da042016-09-07 17:40:12 -0700797static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400798lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700799 Py_hash_t hash, PyObject ***value_addr,
800 Py_ssize_t *hashpos)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400801{
Victor Stinner742da042016-09-07 17:40:12 -0700802 size_t i, perturb;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200803 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700804 Py_ssize_t ix;
805 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400806
Victor Stinner742da042016-09-07 17:40:12 -0700807 assert(mp->ma_values == NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400808 /* Make sure this function doesn't have to handle non-unicode keys,
809 including subclasses of str; e.g., one reason to subclass
810 unicodes is to override __eq__, and for speed we don't cater to
811 that here. */
812 if (!PyUnicode_CheckExact(key)) {
813 mp->ma_keys->dk_lookup = lookdict;
Victor Stinner742da042016-09-07 17:40:12 -0700814 return lookdict(mp, key, hash, value_addr, hashpos);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400815 }
816 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700817 ix = dk_get_index(mp->ma_keys, i);
818 assert (ix != DKIX_DUMMY);
819 if (ix == DKIX_EMPTY) {
820 if (hashpos != NULL)
821 *hashpos = i;
822 *value_addr = NULL;
823 return DKIX_EMPTY;
824 }
825 ep = &ep0[ix];
Victor Stinnerdee6e252016-09-08 11:16:07 -0700826 assert(ep->me_key != NULL);
827 assert(PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700828 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400829 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700830 if (hashpos != NULL)
831 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400832 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700833 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400834 }
835 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700836 i = mask & ((i << 2) + i + perturb + 1);
837 ix = dk_get_index(mp->ma_keys, i);
838 assert (ix != DKIX_DUMMY);
839 if (ix == DKIX_EMPTY) {
840 if (hashpos != NULL)
841 *hashpos = i;
842 *value_addr = NULL;
843 return DKIX_EMPTY;
844 }
845 ep = &ep0[ix];
846 assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
847 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400848 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700849 if (hashpos != NULL)
850 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400851 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700852 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400853 }
854 }
855 assert(0); /* NOT REACHED */
856 return 0;
857}
858
859/* Version of lookdict for split tables.
860 * All split tables and only split tables use this lookup function.
861 * Split tables only contain unicode keys and no dummy keys,
862 * so algorithm is the same as lookdict_unicode_nodummy.
863 */
Victor Stinner742da042016-09-07 17:40:12 -0700864static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400865lookdict_split(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700866 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400867{
Victor Stinner742da042016-09-07 17:40:12 -0700868 size_t i, perturb;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200869 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700870 Py_ssize_t ix;
871 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400872
Victor Stinner742da042016-09-07 17:40:12 -0700873 /* mp must split table */
874 assert(mp->ma_values != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400875 if (!PyUnicode_CheckExact(key)) {
Victor Stinner742da042016-09-07 17:40:12 -0700876 ix = lookdict(mp, key, hash, value_addr, hashpos);
877 if (ix >= 0) {
878 *value_addr = &mp->ma_values[ix];
879 }
880 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400881 }
Victor Stinner742da042016-09-07 17:40:12 -0700882
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400883 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700884 ix = dk_get_index(mp->ma_keys, i);
885 if (ix == DKIX_EMPTY) {
886 if (hashpos != NULL)
887 *hashpos = i;
888 *value_addr = NULL;
889 return DKIX_EMPTY;
890 }
891 assert(ix >= 0);
892 ep = &ep0[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400893 assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700894 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400895 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700896 if (hashpos != NULL)
897 *hashpos = i;
898 *value_addr = &mp->ma_values[ix];
899 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400900 }
901 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700902 i = mask & ((i << 2) + i + perturb + 1);
903 ix = dk_get_index(mp->ma_keys, i);
904 if (ix == DKIX_EMPTY) {
905 if (hashpos != NULL)
906 *hashpos = i;
907 *value_addr = NULL;
908 return DKIX_EMPTY;
909 }
910 assert(ix >= 0);
911 ep = &ep0[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400912 assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700913 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400914 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700915 if (hashpos != NULL)
916 *hashpos = i;
917 *value_addr = &mp->ma_values[ix];
918 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400919 }
920 }
921 assert(0); /* NOT REACHED */
922 return 0;
923}
924
Benjamin Petersonfb886362010-04-24 18:21:17 +0000925int
926_PyDict_HasOnlyStringKeys(PyObject *dict)
927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 Py_ssize_t pos = 0;
929 PyObject *key, *value;
Benjamin Petersonf6096542010-11-17 22:33:12 +0000930 assert(PyDict_Check(dict));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* Shortcut */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400932 if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 return 1;
934 while (PyDict_Next(dict, &pos, &key, &value))
935 if (!PyUnicode_Check(key))
936 return 0;
937 return 1;
Benjamin Petersonfb886362010-04-24 18:21:17 +0000938}
939
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000940#define MAINTAIN_TRACKING(mp, key, value) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 do { \
942 if (!_PyObject_GC_IS_TRACKED(mp)) { \
943 if (_PyObject_GC_MAY_BE_TRACKED(key) || \
944 _PyObject_GC_MAY_BE_TRACKED(value)) { \
945 _PyObject_GC_TRACK(mp); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 } \
947 } \
948 } while(0)
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000949
950void
951_PyDict_MaybeUntrack(PyObject *op)
952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 PyDictObject *mp;
954 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -0700955 Py_ssize_t i, numentries;
956 PyDictKeyEntry *ep0;
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
959 return;
960
961 mp = (PyDictObject *) op;
Victor Stinner742da042016-09-07 17:40:12 -0700962 ep0 = DK_ENTRIES(mp->ma_keys);
963 numentries = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400964 if (_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -0700965 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400966 if ((value = mp->ma_values[i]) == NULL)
967 continue;
968 if (_PyObject_GC_MAY_BE_TRACKED(value)) {
Victor Stinner742da042016-09-07 17:40:12 -0700969 assert(!_PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400970 return;
971 }
972 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400974 else {
Victor Stinner742da042016-09-07 17:40:12 -0700975 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400976 if ((value = ep0[i].me_value) == NULL)
977 continue;
978 if (_PyObject_GC_MAY_BE_TRACKED(value) ||
979 _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
980 return;
981 }
982 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 _PyObject_GC_UNTRACK(op);
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000984}
985
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400986/* Internal function to find slot for an item from its hash
987 * when it is known that the key is not present in the dict.
988 */
Victor Stinner742da042016-09-07 17:40:12 -0700989static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400990find_empty_slot(PyDictObject *mp, PyObject *key, Py_hash_t hash,
Victor Stinner742da042016-09-07 17:40:12 -0700991 PyObject ***value_addr, Py_ssize_t *hashpos)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000992{
Victor Stinner742da042016-09-07 17:40:12 -0700993 size_t i, perturb;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400994 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700995 Py_ssize_t ix;
996 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000997
Victor Stinner742da042016-09-07 17:40:12 -0700998 assert(hashpos != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400999 assert(key != NULL);
1000 if (!PyUnicode_CheckExact(key))
1001 mp->ma_keys->dk_lookup = lookdict;
1002 i = hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -07001003 ix = dk_get_index(mp->ma_keys, i);
1004 for (perturb = hash; ix != DKIX_EMPTY; perturb >>= PERTURB_SHIFT) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001005 i = (i << 2) + i + perturb + 1;
Victor Stinner742da042016-09-07 17:40:12 -07001006 ix = dk_get_index(mp->ma_keys, i & mask);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 }
Victor Stinner742da042016-09-07 17:40:12 -07001008 ep = &ep0[mp->ma_keys->dk_nentries];
1009 *hashpos = i & mask;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001010 assert(ep->me_value == NULL);
1011 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07001012 *value_addr = &mp->ma_values[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001013 else
1014 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -07001015 return ix;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001016}
1017
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001018static int
1019insertion_resize(PyDictObject *mp)
1020{
Raymond Hettinger36f74aa2013-05-17 03:01:13 -07001021 return dictresize(mp, GROWTH_RATE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001022}
Antoine Pitroue965d972012-02-27 00:45:12 +01001023
1024/*
1025Internal routine to insert a new item into the table.
1026Used both by the internal resize routine and by the public insert routine.
Antoine Pitroue965d972012-02-27 00:45:12 +01001027Returns -1 if an error occurred, or 0 on success.
1028*/
1029static int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001030insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001031{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001032 PyObject *old_value;
1033 PyObject **value_addr;
Victor Stinner742da042016-09-07 17:40:12 -07001034 PyDictKeyEntry *ep, *ep0;
1035 Py_ssize_t hashpos, ix;
Antoine Pitroue965d972012-02-27 00:45:12 +01001036
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001037 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
1038 if (insertion_resize(mp) < 0)
1039 return -1;
1040 }
1041
Victor Stinner742da042016-09-07 17:40:12 -07001042 ix = mp->ma_keys->dk_lookup(mp, key, hash, &value_addr, &hashpos);
1043 if (ix == DKIX_ERROR) {
Antoine Pitroue965d972012-02-27 00:45:12 +01001044 return -1;
1045 }
Victor Stinner742da042016-09-07 17:40:12 -07001046
Antoine Pitroud6967322014-10-18 00:35:00 +02001047 assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
Benjamin Petersona6f195e2012-04-30 10:23:40 -04001048 Py_INCREF(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001049 MAINTAIN_TRACKING(mp, key, value);
Victor Stinner742da042016-09-07 17:40:12 -07001050
1051 /* When insertion order is different from shared key, we can't share
1052 * the key anymore. Convert this instance to combine table.
1053 */
1054 if (_PyDict_HasSplitTable(mp) &&
1055 ((ix >= 0 && *value_addr == NULL && mp->ma_used != ix) ||
1056 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
1057 if (insertion_resize(mp) < 0) {
1058 Py_DECREF(value);
1059 return -1;
1060 }
1061 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
1062 ix = DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001063 }
Victor Stinner742da042016-09-07 17:40:12 -07001064
1065 if (ix == DKIX_EMPTY) {
1066 /* Insert into new slot. */
1067 if (mp->ma_keys->dk_usable <= 0) {
1068 /* Need to resize. */
1069 if (insertion_resize(mp) < 0) {
1070 Py_DECREF(value);
1071 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001072 }
Victor Stinner742da042016-09-07 17:40:12 -07001073 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
1074 }
1075 ep0 = DK_ENTRIES(mp->ma_keys);
1076 ep = &ep0[mp->ma_keys->dk_nentries];
1077 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
1078 Py_INCREF(key);
1079 ep->me_key = key;
1080 ep->me_hash = hash;
1081 if (mp->ma_values) {
1082 assert (mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
1083 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001084 }
1085 else {
Victor Stinner742da042016-09-07 17:40:12 -07001086 ep->me_value = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001087 }
1088 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001089 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07001090 mp->ma_keys->dk_usable--;
1091 mp->ma_keys->dk_nentries++;
1092 assert(mp->ma_keys->dk_usable >= 0);
1093 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001094 }
Victor Stinner742da042016-09-07 17:40:12 -07001095
1096 assert(value_addr != NULL);
1097
1098 old_value = *value_addr;
1099 if (old_value != NULL) {
1100 *value_addr = value;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001101 mp->ma_version_tag = DICT_NEXT_VERSION();
1102
Victor Stinner742da042016-09-07 17:40:12 -07001103 Py_DECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
1104 return 0;
1105 }
1106
1107 /* pending state */
1108 assert(_PyDict_HasSplitTable(mp));
1109 assert(ix == mp->ma_used);
1110 *value_addr = value;
1111 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001112 mp->ma_version_tag = DICT_NEXT_VERSION();
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001113 return 0;
Antoine Pitroue965d972012-02-27 00:45:12 +01001114}
1115
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001116/*
1117Internal routine used by dictresize() to insert an item which is
1118known to be absent from the dict. This routine also assumes that
1119the dict contains no deleted entries. Besides the performance benefit,
1120using insertdict() in dictresize() is dangerous (SF bug #1456209).
1121Note that no refcounts are changed by this routine; if needed, the caller
1122is responsible for incref'ing `key` and `value`.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001123Neither mp->ma_used nor k->dk_usable are modified by this routine; the caller
1124must set them correctly
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001125*/
1126static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001127insertdict_clean(PyDictObject *mp, PyObject *key, Py_hash_t hash,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 PyObject *value)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001129{
Victor Stinner742da042016-09-07 17:40:12 -07001130 size_t i, perturb;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001131 PyDictKeysObject *k = mp->ma_keys;
1132 size_t mask = (size_t)DK_SIZE(k)-1;
Victor Stinner742da042016-09-07 17:40:12 -07001133 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001134 PyDictKeyEntry *ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001135
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001136 assert(k->dk_lookup != NULL);
1137 assert(value != NULL);
1138 assert(key != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001139 assert(PyUnicode_CheckExact(key) || k->dk_lookup == lookdict);
1140 i = hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -07001141 for (perturb = hash; dk_get_index(k, i) != DKIX_EMPTY;
1142 perturb >>= PERTURB_SHIFT) {
1143 i = mask & ((i << 2) + i + perturb + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 }
Victor Stinner742da042016-09-07 17:40:12 -07001145 ep = &ep0[k->dk_nentries];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 assert(ep->me_value == NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001147 dk_set_index(k, i, k->dk_nentries);
1148 k->dk_nentries++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 ep->me_key = key;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001150 ep->me_hash = hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 ep->me_value = value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001152}
1153
1154/*
1155Restructure the table by allocating a new table and reinserting all
1156items again. When entries have been deleted, the new table may
1157actually be smaller than the old one.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001158If a table is split (its keys and hashes are shared, its values are not),
1159then the values are temporarily copied into the table, it is resized as
1160a combined table, then the me_value slots in the old table are NULLed out.
1161After resizing a table is always combined,
1162but can be resplit by make_keys_shared().
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001163*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001164static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001165dictresize(PyDictObject *mp, Py_ssize_t minused)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001166{
Victor Stinner742da042016-09-07 17:40:12 -07001167 Py_ssize_t i, newsize;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001168 PyDictKeysObject *oldkeys;
1169 PyObject **oldvalues;
Victor Stinner742da042016-09-07 17:40:12 -07001170 PyDictKeyEntry *ep0;
Tim Peters91a364d2001-05-19 07:04:38 +00001171
Victor Stinner742da042016-09-07 17:40:12 -07001172 /* Find the smallest table size > minused. */
1173 for (newsize = PyDict_MINSIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 newsize <= minused && newsize > 0;
1175 newsize <<= 1)
1176 ;
1177 if (newsize <= 0) {
1178 PyErr_NoMemory();
1179 return -1;
1180 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001181 oldkeys = mp->ma_keys;
1182 oldvalues = mp->ma_values;
1183 /* Allocate a new table. */
1184 mp->ma_keys = new_keys_object(newsize);
1185 if (mp->ma_keys == NULL) {
1186 mp->ma_keys = oldkeys;
1187 return -1;
1188 }
1189 if (oldkeys->dk_lookup == lookdict)
1190 mp->ma_keys->dk_lookup = lookdict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001191 mp->ma_values = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001192 ep0 = DK_ENTRIES(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001193 /* Main loop below assumes we can transfer refcount to new keys
1194 * and that value is stored in me_value.
1195 * Increment ref-counts and copy values here to compensate
1196 * This (resizing a split table) should be relatively rare */
1197 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001198 for (i = 0; i < oldkeys->dk_nentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001199 if (oldvalues[i] != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001200 Py_INCREF(ep0[i].me_key);
1201 ep0[i].me_value = oldvalues[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 }
1204 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001205 /* Main loop */
Victor Stinner742da042016-09-07 17:40:12 -07001206 for (i = 0; i < oldkeys->dk_nentries; i++) {
1207 PyDictKeyEntry *ep = &ep0[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001208 if (ep->me_value != NULL) {
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001209 insertdict_clean(mp, ep->me_key, ep->me_hash, ep->me_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001212 mp->ma_keys->dk_usable -= mp->ma_used;
1213 if (oldvalues != NULL) {
1214 /* NULL out me_value slot in oldkeys, in case it was shared */
Victor Stinner742da042016-09-07 17:40:12 -07001215 for (i = 0; i < oldkeys->dk_nentries; i++)
1216 ep0[i].me_value = NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001217 DK_DECREF(oldkeys);
Victor Stinner742da042016-09-07 17:40:12 -07001218 if (oldvalues != empty_values) {
1219 free_values(oldvalues);
1220 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001221 }
1222 else {
1223 assert(oldkeys->dk_lookup != lookdict_split);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001224 assert(oldkeys->dk_refcnt == 1);
Raymond Hettingerce5179f2016-01-31 08:56:21 -08001225 DK_DEBUG_DECREF PyObject_FREE(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001226 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001228}
1229
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001230/* Returns NULL if unable to split table.
1231 * A NULL return does not necessarily indicate an error */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001232static PyDictKeysObject *
1233make_keys_shared(PyObject *op)
1234{
1235 Py_ssize_t i;
1236 Py_ssize_t size;
1237 PyDictObject *mp = (PyDictObject *)op;
1238
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001239 if (!PyDict_CheckExact(op))
1240 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001241 if (!_PyDict_HasSplitTable(mp)) {
1242 PyDictKeyEntry *ep0;
1243 PyObject **values;
1244 assert(mp->ma_keys->dk_refcnt == 1);
1245 if (mp->ma_keys->dk_lookup == lookdict) {
1246 return NULL;
1247 }
1248 else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
1249 /* Remove dummy keys */
1250 if (dictresize(mp, DK_SIZE(mp->ma_keys)))
1251 return NULL;
1252 }
1253 assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
1254 /* Copy values into a new array */
Victor Stinner742da042016-09-07 17:40:12 -07001255 ep0 = DK_ENTRIES(mp->ma_keys);
1256 size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001257 values = new_values(size);
1258 if (values == NULL) {
1259 PyErr_SetString(PyExc_MemoryError,
1260 "Not enough memory to allocate new values array");
1261 return NULL;
1262 }
1263 for (i = 0; i < size; i++) {
1264 values[i] = ep0[i].me_value;
1265 ep0[i].me_value = NULL;
1266 }
1267 mp->ma_keys->dk_lookup = lookdict_split;
1268 mp->ma_values = values;
1269 }
1270 DK_INCREF(mp->ma_keys);
1271 return mp->ma_keys;
1272}
Christian Heimes99170a52007-12-19 02:07:34 +00001273
1274PyObject *
1275_PyDict_NewPresized(Py_ssize_t minused)
1276{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001277 Py_ssize_t newsize;
1278 PyDictKeysObject *new_keys;
Victor Stinner742da042016-09-07 17:40:12 -07001279 for (newsize = PyDict_MINSIZE;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001280 newsize <= minused && newsize > 0;
1281 newsize <<= 1)
1282 ;
1283 new_keys = new_keys_object(newsize);
1284 if (new_keys == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001286 return new_dict(new_keys, NULL);
Christian Heimes99170a52007-12-19 02:07:34 +00001287}
1288
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001289/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
1290 * that may occur (originally dicts supported only string keys, and exceptions
1291 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001292 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001293 * (suppressed) occurred while computing the key's hash, or that some error
1294 * (suppressed) occurred when comparing keys in the dict's internal probe
1295 * sequence. A nasty example of the latter is when a Python-coded comparison
1296 * function hits a stack-depth error, which can cause this to return NULL
1297 * even if the key is present.
1298 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001299PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001300PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001301{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001302 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001303 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 PyDictObject *mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 PyThreadState *tstate;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001306 PyObject **value_addr;
1307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 if (!PyDict_Check(op))
1309 return NULL;
1310 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001311 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 {
1313 hash = PyObject_Hash(key);
1314 if (hash == -1) {
1315 PyErr_Clear();
1316 return NULL;
1317 }
1318 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 /* We can arrive here with a NULL tstate during initialization: try
1321 running "python -Wi" for an example related to string interning.
1322 Let's just hope that no exception occurs then... This must be
1323 _PyThreadState_Current and not PyThreadState_GET() because in debug
1324 mode, the latter complains if tstate is NULL. */
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001325 tstate = _PyThreadState_UncheckedGet();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 if (tstate != NULL && tstate->curexc_type != NULL) {
1327 /* preserve the existing exception */
1328 PyObject *err_type, *err_value, *err_tb;
1329 PyErr_Fetch(&err_type, &err_value, &err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001330 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 /* ignore errors */
1332 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001333 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 return NULL;
1335 }
1336 else {
Victor Stinner742da042016-09-07 17:40:12 -07001337 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1338 if (ix < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 PyErr_Clear();
1340 return NULL;
1341 }
1342 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001343 return *value_addr;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001344}
1345
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001346PyObject *
1347_PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1348{
Victor Stinner742da042016-09-07 17:40:12 -07001349 Py_ssize_t ix;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001350 PyDictObject *mp = (PyDictObject *)op;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001351 PyThreadState *tstate;
1352 PyObject **value_addr;
1353
1354 if (!PyDict_Check(op))
1355 return NULL;
1356
1357 /* We can arrive here with a NULL tstate during initialization: try
1358 running "python -Wi" for an example related to string interning.
1359 Let's just hope that no exception occurs then... This must be
1360 _PyThreadState_Current and not PyThreadState_GET() because in debug
1361 mode, the latter complains if tstate is NULL. */
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001362 tstate = _PyThreadState_UncheckedGet();
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001363 if (tstate != NULL && tstate->curexc_type != NULL) {
1364 /* preserve the existing exception */
1365 PyObject *err_type, *err_value, *err_tb;
1366 PyErr_Fetch(&err_type, &err_value, &err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001367 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001368 /* ignore errors */
1369 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001370 if (ix == DKIX_EMPTY)
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001371 return NULL;
1372 }
1373 else {
Victor Stinner742da042016-09-07 17:40:12 -07001374 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1375 if (ix == DKIX_EMPTY) {
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001376 PyErr_Clear();
1377 return NULL;
1378 }
1379 }
1380 return *value_addr;
1381}
1382
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001383/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
1384 This returns NULL *with* an exception set if an exception occurred.
1385 It returns NULL *without* an exception set if the key wasn't present.
1386*/
1387PyObject *
1388PyDict_GetItemWithError(PyObject *op, PyObject *key)
1389{
Victor Stinner742da042016-09-07 17:40:12 -07001390 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001391 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 PyDictObject*mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001393 PyObject **value_addr;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 if (!PyDict_Check(op)) {
1396 PyErr_BadInternalCall();
1397 return NULL;
1398 }
1399 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001400 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 {
1402 hash = PyObject_Hash(key);
1403 if (hash == -1) {
1404 return NULL;
1405 }
1406 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001407
Victor Stinner742da042016-09-07 17:40:12 -07001408 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1409 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001411 return *value_addr;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001412}
1413
Brett Cannonfd074152012-04-14 14:10:13 -04001414PyObject *
1415_PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
1416{
1417 PyObject *kv;
1418 kv = _PyUnicode_FromId(key); /* borrowed */
1419 if (kv == NULL)
1420 return NULL;
1421 return PyDict_GetItemWithError(dp, kv);
1422}
1423
Victor Stinnerb4efc962015-11-20 09:24:02 +01001424/* Fast version of global value lookup (LOAD_GLOBAL).
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001425 * Lookup in globals, then builtins.
Victor Stinnerb4efc962015-11-20 09:24:02 +01001426 *
1427 * Raise an exception and return NULL if an error occurred (ex: computing the
1428 * key hash failed, key comparison failed, ...). Return NULL if the key doesn't
1429 * exist. Return the value if the key exists.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001430 */
1431PyObject *
1432_PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001433{
Victor Stinner742da042016-09-07 17:40:12 -07001434 Py_ssize_t ix;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001435 Py_hash_t hash;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001436 PyObject **value_addr;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001437
1438 if (!PyUnicode_CheckExact(key) ||
1439 (hash = ((PyASCIIObject *) key)->hash) == -1)
1440 {
1441 hash = PyObject_Hash(key);
1442 if (hash == -1)
1443 return NULL;
Antoine Pitroue965d972012-02-27 00:45:12 +01001444 }
Victor Stinnerb4efc962015-11-20 09:24:02 +01001445
1446 /* namespace 1: globals */
Victor Stinner742da042016-09-07 17:40:12 -07001447 ix = globals->ma_keys->dk_lookup(globals, key, hash, &value_addr, NULL);
1448 if (ix == DKIX_ERROR)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001449 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001450 if (ix != DKIX_EMPTY && *value_addr != NULL)
1451 return *value_addr;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001452
1453 /* namespace 2: builtins */
Victor Stinner742da042016-09-07 17:40:12 -07001454 ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value_addr, NULL);
1455 if (ix < 0)
Victor Stinnerb4efc962015-11-20 09:24:02 +01001456 return NULL;
1457 return *value_addr;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001458}
1459
Antoine Pitroue965d972012-02-27 00:45:12 +01001460/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
1461 * dictionary if it's merely replacing the value for an existing key.
1462 * This means that it's safe to loop over a dictionary with PyDict_Next()
1463 * and occasionally replace a value -- but you can't insert new keys or
1464 * remove them.
1465 */
1466int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001467PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001468{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001469 PyDictObject *mp;
1470 Py_hash_t hash;
Antoine Pitroue965d972012-02-27 00:45:12 +01001471 if (!PyDict_Check(op)) {
1472 PyErr_BadInternalCall();
1473 return -1;
1474 }
1475 assert(key);
1476 assert(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001477 mp = (PyDictObject *)op;
1478 if (!PyUnicode_CheckExact(key) ||
1479 (hash = ((PyASCIIObject *) key)->hash) == -1)
1480 {
Antoine Pitroue965d972012-02-27 00:45:12 +01001481 hash = PyObject_Hash(key);
1482 if (hash == -1)
1483 return -1;
1484 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001485
1486 /* insertdict() handles any resizing that might be necessary */
1487 return insertdict(mp, key, hash, value);
Antoine Pitroue965d972012-02-27 00:45:12 +01001488}
1489
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001490int
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001491_PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
1492 Py_hash_t hash)
1493{
1494 PyDictObject *mp;
1495
1496 if (!PyDict_Check(op)) {
1497 PyErr_BadInternalCall();
1498 return -1;
1499 }
1500 assert(key);
1501 assert(value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001502 assert(hash != -1);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001503 mp = (PyDictObject *)op;
1504
1505 /* insertdict() handles any resizing that might be necessary */
1506 return insertdict(mp, key, hash, value);
1507}
1508
1509int
Tim Peters1f5871e2000-07-04 17:44:48 +00001510PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001511{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001512 Py_hash_t hash;
Guido van Rossumd7047b31995-01-02 19:07:15 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 assert(key);
1515 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001516 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 hash = PyObject_Hash(key);
1518 if (hash == -1)
1519 return -1;
1520 }
Victor Stinner742da042016-09-07 17:40:12 -07001521
1522 return _PyDict_DelItem_KnownHash(op, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001523}
1524
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001525int
1526_PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1527{
Victor Stinner742da042016-09-07 17:40:12 -07001528 Py_ssize_t hashpos, ix;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001529 PyDictObject *mp;
1530 PyDictKeyEntry *ep;
1531 PyObject *old_key, *old_value;
1532 PyObject **value_addr;
1533
1534 if (!PyDict_Check(op)) {
1535 PyErr_BadInternalCall();
1536 return -1;
1537 }
1538 assert(key);
1539 assert(hash != -1);
1540 mp = (PyDictObject *)op;
Victor Stinner742da042016-09-07 17:40:12 -07001541 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1542 if (ix == DKIX_ERROR)
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001543 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07001544 if (ix == DKIX_EMPTY || *value_addr == NULL) {
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001545 _PyErr_SetKeyError(key);
1546 return -1;
1547 }
Victor Stinner742da042016-09-07 17:40:12 -07001548 assert(dk_get_index(mp->ma_keys, hashpos) == ix);
Victor Stinner78601a32016-09-09 19:28:36 -07001549
1550 // Split table doesn't allow deletion. Combine it.
1551 if (_PyDict_HasSplitTable(mp)) {
1552 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1553 return -1;
1554 }
1555 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1556 assert(ix >= 0);
1557 }
1558
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001559 old_value = *value_addr;
Victor Stinner78601a32016-09-09 19:28:36 -07001560 assert(old_value != NULL);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001561 *value_addr = NULL;
1562 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001563 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner78601a32016-09-09 19:28:36 -07001564 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1565 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1566 ENSURE_ALLOWS_DELETIONS(mp);
1567 old_key = ep->me_key;
1568 ep->me_key = NULL;
1569 Py_DECREF(old_key);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001570 Py_DECREF(old_value);
1571 return 0;
1572}
1573
Guido van Rossum25831651993-05-19 14:50:45 +00001574void
Tim Peters1f5871e2000-07-04 17:44:48 +00001575PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 PyDictObject *mp;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001578 PyDictKeysObject *oldkeys;
1579 PyObject **oldvalues;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 if (!PyDict_Check(op))
1583 return;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001584 mp = ((PyDictObject *)op);
1585 oldkeys = mp->ma_keys;
1586 oldvalues = mp->ma_values;
1587 if (oldvalues == empty_values)
1588 return;
1589 /* Empty the dict... */
1590 DK_INCREF(Py_EMPTY_KEYS);
1591 mp->ma_keys = Py_EMPTY_KEYS;
1592 mp->ma_values = empty_values;
1593 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001594 mp->ma_version_tag = DICT_NEXT_VERSION();
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001595 /* ...then clear the keys and values */
1596 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001597 n = oldkeys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001598 for (i = 0; i < n; i++)
1599 Py_CLEAR(oldvalues[i]);
1600 free_values(oldvalues);
1601 DK_DECREF(oldkeys);
1602 }
1603 else {
1604 assert(oldkeys->dk_refcnt == 1);
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001605 DK_DECREF(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001606 }
1607}
1608
1609/* Returns -1 if no more items (or op is not a dict),
1610 * index of item otherwise. Stores value in pvalue
1611 */
Benjamin Peterson73222252016-09-08 09:58:47 -07001612static inline Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001613dict_next(PyObject *op, Py_ssize_t i, PyObject **pvalue)
1614{
Victor Stinner742da042016-09-07 17:40:12 -07001615 Py_ssize_t n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001616 PyDictObject *mp;
Victor Stinner742da042016-09-07 17:40:12 -07001617 PyObject **value_ptr = NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001618
1619 if (!PyDict_Check(op))
1620 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001622 if (i < 0)
1623 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07001624
1625 n = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001626 if (mp->ma_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001627 for (; i < n; i++) {
1628 value_ptr = &mp->ma_values[i];
1629 if (*value_ptr != NULL)
1630 break;
1631 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001633 else {
Victor Stinner742da042016-09-07 17:40:12 -07001634 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
1635 for (; i < n; i++) {
1636 value_ptr = &ep0[i].me_value;
1637 if (*value_ptr != NULL)
1638 break;
1639 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 }
Victor Stinner742da042016-09-07 17:40:12 -07001641 if (i >= n)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001642 return -1;
1643 if (pvalue)
1644 *pvalue = *value_ptr;
1645 return i;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001646}
1647
Tim Peters080c88b2003-02-15 03:01:11 +00001648/*
1649 * Iterate over a dict. Use like so:
1650 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001651 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +00001652 * PyObject *key, *value;
1653 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +00001654 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Tim Peters080c88b2003-02-15 03:01:11 +00001655 * Refer to borrowed references in key and value.
1656 * }
1657 *
1658 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +00001659 * mutates the dict. One exception: it is safe if the loop merely changes
1660 * the values associated with the keys (but doesn't insert new keys or
1661 * delete keys), via PyDict_SetItem().
1662 */
Guido van Rossum25831651993-05-19 14:50:45 +00001663int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001664PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001665{
Victor Stinner742da042016-09-07 17:40:12 -07001666 PyDictObject *mp = (PyDictObject*)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001667 Py_ssize_t i = dict_next(op, *ppos, pvalue);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 if (i < 0)
1669 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001670 mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 *ppos = i+1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 if (pkey)
Victor Stinner742da042016-09-07 17:40:12 -07001673 *pkey = DK_ENTRIES(mp->ma_keys)[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001675}
1676
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001677/* Internal version of PyDict_Next that returns a hash value in addition
1678 * to the key and value.
1679 */
Thomas Wouterscf297e42007-02-23 15:07:44 +00001680int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001681_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
1682 PyObject **pvalue, Py_hash_t *phash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001683{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001684 PyDictObject *mp;
Victor Stinner742da042016-09-07 17:40:12 -07001685 PyDictKeyEntry *ep0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001686 Py_ssize_t i = dict_next(op, *ppos, pvalue);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 if (i < 0)
1688 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001689 mp = (PyDictObject *)op;
Victor Stinner742da042016-09-07 17:40:12 -07001690 ep0 = DK_ENTRIES(mp->ma_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 *ppos = i+1;
Victor Stinner742da042016-09-07 17:40:12 -07001692 *phash = ep0[i].me_hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 if (pkey)
Victor Stinner742da042016-09-07 17:40:12 -07001694 *pkey = ep0[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 return 1;
Thomas Wouterscf297e42007-02-23 15:07:44 +00001696}
1697
Eric Snow96c6af92015-05-29 22:21:39 -06001698/* Internal version of dict.pop(). */
1699PyObject *
1700_PyDict_Pop(PyDictObject *mp, PyObject *key, PyObject *deflt)
1701{
1702 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001703 Py_ssize_t ix, hashpos;
Eric Snow96c6af92015-05-29 22:21:39 -06001704 PyObject *old_value, *old_key;
1705 PyDictKeyEntry *ep;
1706 PyObject **value_addr;
1707
1708 if (mp->ma_used == 0) {
1709 if (deflt) {
1710 Py_INCREF(deflt);
1711 return deflt;
1712 }
1713 _PyErr_SetKeyError(key);
1714 return NULL;
1715 }
1716 if (!PyUnicode_CheckExact(key) ||
1717 (hash = ((PyASCIIObject *) key)->hash) == -1) {
1718 hash = PyObject_Hash(key);
1719 if (hash == -1)
1720 return NULL;
1721 }
Victor Stinner742da042016-09-07 17:40:12 -07001722 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1723 if (ix == DKIX_ERROR)
Eric Snow96c6af92015-05-29 22:21:39 -06001724 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001725 if (ix == DKIX_EMPTY) {
Eric Snow96c6af92015-05-29 22:21:39 -06001726 if (deflt) {
1727 Py_INCREF(deflt);
1728 return deflt;
1729 }
1730 _PyErr_SetKeyError(key);
1731 return NULL;
1732 }
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001733
Victor Stinner78601a32016-09-09 19:28:36 -07001734 // Split table doesn't allow deletion. Combine it.
1735 if (_PyDict_HasSplitTable(mp)) {
1736 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1737 return NULL;
1738 }
1739 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1740 assert(ix >= 0);
1741 }
1742
Victor Stinner742da042016-09-07 17:40:12 -07001743 old_value = *value_addr;
Victor Stinner78601a32016-09-09 19:28:36 -07001744 assert(old_value != NULL);
Eric Snow96c6af92015-05-29 22:21:39 -06001745 *value_addr = NULL;
1746 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001747 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner78601a32016-09-09 19:28:36 -07001748 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1749 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1750 ENSURE_ALLOWS_DELETIONS(mp);
1751 old_key = ep->me_key;
1752 ep->me_key = NULL;
1753 Py_DECREF(old_key);
Eric Snow96c6af92015-05-29 22:21:39 -06001754 return old_value;
1755}
1756
1757/* Internal version of dict.from_keys(). It is subclass-friendly. */
1758PyObject *
1759_PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
1760{
1761 PyObject *it; /* iter(iterable) */
1762 PyObject *key;
1763 PyObject *d;
1764 int status;
1765
1766 d = PyObject_CallObject(cls, NULL);
1767 if (d == NULL)
1768 return NULL;
1769
1770 if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
1771 if (PyDict_CheckExact(iterable)) {
1772 PyDictObject *mp = (PyDictObject *)d;
1773 PyObject *oldvalue;
1774 Py_ssize_t pos = 0;
1775 PyObject *key;
1776 Py_hash_t hash;
1777
Victor Stinner742da042016-09-07 17:40:12 -07001778 if (dictresize(mp, ESTIMATE_SIZE(Py_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001779 Py_DECREF(d);
1780 return NULL;
1781 }
1782
1783 while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
1784 if (insertdict(mp, key, hash, value)) {
1785 Py_DECREF(d);
1786 return NULL;
1787 }
1788 }
1789 return d;
1790 }
1791 if (PyAnySet_CheckExact(iterable)) {
1792 PyDictObject *mp = (PyDictObject *)d;
1793 Py_ssize_t pos = 0;
1794 PyObject *key;
1795 Py_hash_t hash;
1796
Victor Stinner742da042016-09-07 17:40:12 -07001797 if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001798 Py_DECREF(d);
1799 return NULL;
1800 }
1801
1802 while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
1803 if (insertdict(mp, key, hash, value)) {
1804 Py_DECREF(d);
1805 return NULL;
1806 }
1807 }
1808 return d;
1809 }
1810 }
1811
1812 it = PyObject_GetIter(iterable);
1813 if (it == NULL){
1814 Py_DECREF(d);
1815 return NULL;
1816 }
1817
1818 if (PyDict_CheckExact(d)) {
1819 while ((key = PyIter_Next(it)) != NULL) {
1820 status = PyDict_SetItem(d, key, value);
1821 Py_DECREF(key);
1822 if (status < 0)
1823 goto Fail;
1824 }
1825 } else {
1826 while ((key = PyIter_Next(it)) != NULL) {
1827 status = PyObject_SetItem(d, key, value);
1828 Py_DECREF(key);
1829 if (status < 0)
1830 goto Fail;
1831 }
1832 }
1833
1834 if (PyErr_Occurred())
1835 goto Fail;
1836 Py_DECREF(it);
1837 return d;
1838
1839Fail:
1840 Py_DECREF(it);
1841 Py_DECREF(d);
1842 return NULL;
1843}
1844
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001845/* Methods */
1846
1847static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001848dict_dealloc(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001849{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001850 PyObject **values = mp->ma_values;
1851 PyDictKeysObject *keys = mp->ma_keys;
1852 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 PyObject_GC_UnTrack(mp);
1854 Py_TRASHCAN_SAFE_BEGIN(mp)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001855 if (values != NULL) {
1856 if (values != empty_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001857 for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001858 Py_XDECREF(values[i]);
1859 }
1860 free_values(values);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001862 DK_DECREF(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 }
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02001864 else if (keys != NULL) {
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001865 assert(keys->dk_refcnt == 1);
1866 DK_DECREF(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001867 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
1869 free_list[numfree++] = mp;
1870 else
1871 Py_TYPE(mp)->tp_free((PyObject *)mp);
1872 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001873}
1874
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001875
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001876static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001877dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 Py_ssize_t i;
Victor Stinnerf91929b2013-11-19 13:07:38 +01001880 PyObject *key = NULL, *value = NULL;
1881 _PyUnicodeWriter writer;
1882 int first;
Guido van Rossum255443b1998-04-10 22:47:14 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 i = Py_ReprEnter((PyObject *)mp);
1885 if (i != 0) {
1886 return i > 0 ? PyUnicode_FromString("{...}") : NULL;
1887 }
Guido van Rossum255443b1998-04-10 22:47:14 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 if (mp->ma_used == 0) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01001890 Py_ReprLeave((PyObject *)mp);
1891 return PyUnicode_FromString("{}");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 }
Tim Petersa7259592001-06-16 05:11:17 +00001893
Victor Stinnerf91929b2013-11-19 13:07:38 +01001894 _PyUnicodeWriter_Init(&writer);
1895 writer.overallocate = 1;
1896 /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
1897 writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +00001898
Victor Stinnerf91929b2013-11-19 13:07:38 +01001899 if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
1900 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00001901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 /* Do repr() on each key+value pair, and insert ": " between them.
1903 Note that repr may mutate the dict. */
1904 i = 0;
Victor Stinnerf91929b2013-11-19 13:07:38 +01001905 first = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01001907 PyObject *s;
1908 int res;
1909
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001910 /* Prevent repr from deleting key or value during key format. */
1911 Py_INCREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 Py_INCREF(value);
Victor Stinnerf97dfd72013-07-18 01:00:45 +02001913
Victor Stinnerf91929b2013-11-19 13:07:38 +01001914 if (!first) {
1915 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
1916 goto error;
1917 }
1918 first = 0;
1919
1920 s = PyObject_Repr(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 if (s == NULL)
Victor Stinnerf91929b2013-11-19 13:07:38 +01001922 goto error;
1923 res = _PyUnicodeWriter_WriteStr(&writer, s);
1924 Py_DECREF(s);
1925 if (res < 0)
1926 goto error;
1927
1928 if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
1929 goto error;
1930
1931 s = PyObject_Repr(value);
1932 if (s == NULL)
1933 goto error;
1934 res = _PyUnicodeWriter_WriteStr(&writer, s);
1935 Py_DECREF(s);
1936 if (res < 0)
1937 goto error;
1938
1939 Py_CLEAR(key);
1940 Py_CLEAR(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 }
Tim Petersa7259592001-06-16 05:11:17 +00001942
Victor Stinnerf91929b2013-11-19 13:07:38 +01001943 writer.overallocate = 0;
1944 if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
1945 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00001946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 Py_ReprLeave((PyObject *)mp);
Victor Stinnerf91929b2013-11-19 13:07:38 +01001948
1949 return _PyUnicodeWriter_Finish(&writer);
1950
1951error:
1952 Py_ReprLeave((PyObject *)mp);
1953 _PyUnicodeWriter_Dealloc(&writer);
1954 Py_XDECREF(key);
1955 Py_XDECREF(value);
1956 return NULL;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001957}
1958
Martin v. Löwis18e16552006-02-15 17:27:45 +00001959static Py_ssize_t
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001960dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 return mp->ma_used;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001963}
1964
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001965static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001966dict_subscript(PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 PyObject *v;
Victor Stinner742da042016-09-07 17:40:12 -07001969 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001970 Py_hash_t hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001971 PyObject **value_addr;
1972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001974 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 hash = PyObject_Hash(key);
1976 if (hash == -1)
1977 return NULL;
1978 }
Victor Stinner742da042016-09-07 17:40:12 -07001979 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1980 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001982 if (ix == DKIX_EMPTY || *value_addr == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 if (!PyDict_CheckExact(mp)) {
1984 /* Look up __missing__ method if we're a subclass. */
1985 PyObject *missing, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05001986 _Py_IDENTIFIER(__missing__);
1987 missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 if (missing != NULL) {
1989 res = PyObject_CallFunctionObjArgs(missing,
1990 key, NULL);
1991 Py_DECREF(missing);
1992 return res;
1993 }
1994 else if (PyErr_Occurred())
1995 return NULL;
1996 }
Raymond Hettinger69492da2013-09-02 15:59:26 -07001997 _PyErr_SetKeyError(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 return NULL;
1999 }
Victor Stinner742da042016-09-07 17:40:12 -07002000 v = *value_addr;
2001 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002003}
2004
2005static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002006dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 if (w == NULL)
2009 return PyDict_DelItem((PyObject *)mp, v);
2010 else
2011 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002012}
2013
Guido van Rossuma9e7a811997-05-13 21:02:11 +00002014static PyMappingMethods dict_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 (lenfunc)dict_length, /*mp_length*/
2016 (binaryfunc)dict_subscript, /*mp_subscript*/
2017 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002018};
2019
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002020static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002021dict_keys(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002022{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002023 PyObject *v;
2024 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002025 PyDictKeyEntry *ep;
2026 Py_ssize_t size, n, offset;
2027 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002028
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002029 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 n = mp->ma_used;
2031 v = PyList_New(n);
2032 if (v == NULL)
2033 return NULL;
2034 if (n != mp->ma_used) {
2035 /* Durnit. The allocations caused the dict to resize.
2036 * Just start over, this shouldn't normally happen.
2037 */
2038 Py_DECREF(v);
2039 goto again;
2040 }
Victor Stinner742da042016-09-07 17:40:12 -07002041 ep = DK_ENTRIES(mp->ma_keys);
2042 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002043 if (mp->ma_values) {
2044 value_ptr = mp->ma_values;
2045 offset = sizeof(PyObject *);
2046 }
2047 else {
2048 value_ptr = &ep[0].me_value;
2049 offset = sizeof(PyDictKeyEntry);
2050 }
2051 for (i = 0, j = 0; i < size; i++) {
2052 if (*value_ptr != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 PyObject *key = ep[i].me_key;
2054 Py_INCREF(key);
2055 PyList_SET_ITEM(v, j, key);
2056 j++;
2057 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002058 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 }
2060 assert(j == n);
2061 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002062}
2063
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002064static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002065dict_values(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002066{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002067 PyObject *v;
2068 Py_ssize_t i, j;
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002069 PyDictKeyEntry *ep;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002070 Py_ssize_t size, n, offset;
2071 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002072
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002073 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 n = mp->ma_used;
2075 v = PyList_New(n);
2076 if (v == NULL)
2077 return NULL;
2078 if (n != mp->ma_used) {
2079 /* Durnit. The allocations caused the dict to resize.
2080 * Just start over, this shouldn't normally happen.
2081 */
2082 Py_DECREF(v);
2083 goto again;
2084 }
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002085 ep = DK_ENTRIES(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002086 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002087 if (mp->ma_values) {
2088 value_ptr = mp->ma_values;
2089 offset = sizeof(PyObject *);
2090 }
2091 else {
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002092 value_ptr = &ep[0].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002093 offset = sizeof(PyDictKeyEntry);
2094 }
2095 for (i = 0, j = 0; i < size; i++) {
2096 PyObject *value = *value_ptr;
2097 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2098 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 Py_INCREF(value);
2100 PyList_SET_ITEM(v, j, value);
2101 j++;
2102 }
2103 }
2104 assert(j == n);
2105 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002106}
2107
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002108static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002109dict_items(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002110{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002111 PyObject *v;
2112 Py_ssize_t i, j, n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002113 Py_ssize_t size, offset;
2114 PyObject *item, *key;
2115 PyDictKeyEntry *ep;
2116 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 /* Preallocate the list of tuples, to avoid allocations during
2119 * the loop over the items, which could trigger GC, which
2120 * could resize the dict. :-(
2121 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002122 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 n = mp->ma_used;
2124 v = PyList_New(n);
2125 if (v == NULL)
2126 return NULL;
2127 for (i = 0; i < n; i++) {
2128 item = PyTuple_New(2);
2129 if (item == NULL) {
2130 Py_DECREF(v);
2131 return NULL;
2132 }
2133 PyList_SET_ITEM(v, i, item);
2134 }
2135 if (n != mp->ma_used) {
2136 /* Durnit. The allocations caused the dict to resize.
2137 * Just start over, this shouldn't normally happen.
2138 */
2139 Py_DECREF(v);
2140 goto again;
2141 }
2142 /* Nothing we do below makes any function calls. */
Victor Stinner742da042016-09-07 17:40:12 -07002143 ep = DK_ENTRIES(mp->ma_keys);
2144 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002145 if (mp->ma_values) {
2146 value_ptr = mp->ma_values;
2147 offset = sizeof(PyObject *);
2148 }
2149 else {
2150 value_ptr = &ep[0].me_value;
2151 offset = sizeof(PyDictKeyEntry);
2152 }
2153 for (i = 0, j = 0; i < size; i++) {
2154 PyObject *value = *value_ptr;
2155 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2156 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 key = ep[i].me_key;
2158 item = PyList_GET_ITEM(v, j);
2159 Py_INCREF(key);
2160 PyTuple_SET_ITEM(item, 0, key);
2161 Py_INCREF(value);
2162 PyTuple_SET_ITEM(item, 1, value);
2163 j++;
2164 }
2165 }
2166 assert(j == n);
2167 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002168}
2169
Larry Hastings5c661892014-01-24 06:17:25 -08002170/*[clinic input]
2171@classmethod
2172dict.fromkeys
Larry Hastings5c661892014-01-24 06:17:25 -08002173 iterable: object
2174 value: object=None
2175 /
2176
2177Returns a new dict with keys from iterable and values equal to value.
2178[clinic start generated code]*/
2179
Larry Hastings5c661892014-01-24 06:17:25 -08002180static PyObject *
2181dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002182/*[clinic end generated code: output=8fb98e4b10384999 input=b85a667f9bf4669d]*/
Larry Hastings5c661892014-01-24 06:17:25 -08002183{
Eric Snow96c6af92015-05-29 22:21:39 -06002184 return _PyDict_FromKeys((PyObject *)type, iterable, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002185}
2186
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002187static int
Victor Stinner742da042016-09-07 17:40:12 -07002188dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
2189 const char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 PyObject *arg = NULL;
2192 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
2195 result = -1;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 else if (arg != NULL) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02002198 _Py_IDENTIFIER(keys);
2199 if (_PyObject_HasAttrId(arg, &PyId_keys))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 result = PyDict_Merge(self, arg, 1);
2201 else
2202 result = PyDict_MergeFromSeq2(self, arg, 1);
2203 }
2204 if (result == 0 && kwds != NULL) {
2205 if (PyArg_ValidateKeywordArguments(kwds))
2206 result = PyDict_Merge(self, kwds, 1);
2207 else
2208 result = -1;
2209 }
2210 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002211}
2212
2213static PyObject *
2214dict_update(PyObject *self, PyObject *args, PyObject *kwds)
2215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 if (dict_update_common(self, args, kwds, "update") != -1)
2217 Py_RETURN_NONE;
2218 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002219}
2220
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002221/* Update unconditionally replaces existing items.
2222 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00002223 otherwise it leaves existing items unchanged.
2224
2225 PyDict_{Update,Merge} update/merge from a mapping object.
2226
Tim Petersf582b822001-12-11 18:51:08 +00002227 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00002228 producing iterable objects of length 2.
2229*/
2230
Tim Petersf582b822001-12-11 18:51:08 +00002231int
Tim Peters1fc240e2001-10-26 05:06:50 +00002232PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
2233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 PyObject *it; /* iter(seq2) */
2235 Py_ssize_t i; /* index into seq2 of current element */
2236 PyObject *item; /* seq2[i] */
2237 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 assert(d != NULL);
2240 assert(PyDict_Check(d));
2241 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 it = PyObject_GetIter(seq2);
2244 if (it == NULL)
2245 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 for (i = 0; ; ++i) {
2248 PyObject *key, *value;
2249 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 fast = NULL;
2252 item = PyIter_Next(it);
2253 if (item == NULL) {
2254 if (PyErr_Occurred())
2255 goto Fail;
2256 break;
2257 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 /* Convert item to sequence, and verify length 2. */
2260 fast = PySequence_Fast(item, "");
2261 if (fast == NULL) {
2262 if (PyErr_ExceptionMatches(PyExc_TypeError))
2263 PyErr_Format(PyExc_TypeError,
2264 "cannot convert dictionary update "
2265 "sequence element #%zd to a sequence",
2266 i);
2267 goto Fail;
2268 }
2269 n = PySequence_Fast_GET_SIZE(fast);
2270 if (n != 2) {
2271 PyErr_Format(PyExc_ValueError,
2272 "dictionary update sequence element #%zd "
2273 "has length %zd; 2 is required",
2274 i, n);
2275 goto Fail;
2276 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 /* Update/merge with this (key, value) pair. */
2279 key = PySequence_Fast_GET_ITEM(fast, 0);
2280 value = PySequence_Fast_GET_ITEM(fast, 1);
2281 if (override || PyDict_GetItem(d, key) == NULL) {
2282 int status = PyDict_SetItem(d, key, value);
2283 if (status < 0)
2284 goto Fail;
2285 }
2286 Py_DECREF(fast);
2287 Py_DECREF(item);
2288 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 i = 0;
2291 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00002292Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 Py_XDECREF(item);
2294 Py_XDECREF(fast);
2295 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002296Return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 Py_DECREF(it);
2298 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00002299}
2300
Tim Peters6d6c1a32001-08-02 04:15:00 +00002301int
2302PyDict_Update(PyObject *a, PyObject *b)
2303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 return PyDict_Merge(a, b, 1);
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002305}
2306
2307int
2308PyDict_Merge(PyObject *a, PyObject *b, int override)
2309{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002310 PyDictObject *mp, *other;
2311 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -07002312 PyDictKeyEntry *entry, *ep0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 /* We accept for the argument either a concrete dictionary object,
2315 * or an abstract "mapping" object. For the former, we can do
2316 * things quite efficiently. For the latter, we only require that
2317 * PyMapping_Keys() and PyObject_GetItem() be supported.
2318 */
2319 if (a == NULL || !PyDict_Check(a) || b == NULL) {
2320 PyErr_BadInternalCall();
2321 return -1;
2322 }
2323 mp = (PyDictObject*)a;
2324 if (PyDict_Check(b)) {
2325 other = (PyDictObject*)b;
2326 if (other == mp || other->ma_used == 0)
2327 /* a.update(a) or a.update({}); nothing to do */
2328 return 0;
2329 if (mp->ma_used == 0)
2330 /* Since the target dict is empty, PyDict_GetItem()
2331 * always returns NULL. Setting override to 1
2332 * skips the unnecessary test.
2333 */
2334 override = 1;
2335 /* Do one big resize at the start, rather than
2336 * incrementally resizing as we insert new items. Expect
2337 * that there will be no (or few) overlapping keys.
2338 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002339 if (mp->ma_keys->dk_usable * 3 < other->ma_used * 2)
2340 if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07002342 ep0 = DK_ENTRIES(other->ma_keys);
2343 for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002344 PyObject *key, *value;
2345 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002346 entry = &ep0[i];
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002347 key = entry->me_key;
2348 hash = entry->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002349 if (other->ma_values)
2350 value = other->ma_values[i];
2351 else
2352 value = entry->me_value;
2353
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002354 if (value != NULL) {
2355 int err = 0;
2356 Py_INCREF(key);
2357 Py_INCREF(value);
2358 if (override || PyDict_GetItem(a, key) == NULL)
2359 err = insertdict(mp, key, hash, value);
2360 Py_DECREF(value);
2361 Py_DECREF(key);
2362 if (err != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 return -1;
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002364
Victor Stinner742da042016-09-07 17:40:12 -07002365 if (n != other->ma_keys->dk_nentries) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002366 PyErr_SetString(PyExc_RuntimeError,
2367 "dict mutated during update");
2368 return -1;
2369 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 }
2371 }
2372 }
2373 else {
2374 /* Do it the generic, slower way */
2375 PyObject *keys = PyMapping_Keys(b);
2376 PyObject *iter;
2377 PyObject *key, *value;
2378 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 if (keys == NULL)
2381 /* Docstring says this is equivalent to E.keys() so
2382 * if E doesn't have a .keys() method we want
2383 * AttributeError to percolate up. Might as well
2384 * do the same for any other error.
2385 */
2386 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 iter = PyObject_GetIter(keys);
2389 Py_DECREF(keys);
2390 if (iter == NULL)
2391 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
2394 if (!override && PyDict_GetItem(a, key) != NULL) {
2395 Py_DECREF(key);
2396 continue;
2397 }
2398 value = PyObject_GetItem(b, key);
2399 if (value == NULL) {
2400 Py_DECREF(iter);
2401 Py_DECREF(key);
2402 return -1;
2403 }
2404 status = PyDict_SetItem(a, key, value);
2405 Py_DECREF(key);
2406 Py_DECREF(value);
2407 if (status < 0) {
2408 Py_DECREF(iter);
2409 return -1;
2410 }
2411 }
2412 Py_DECREF(iter);
2413 if (PyErr_Occurred())
2414 /* Iterator completed, via error */
2415 return -1;
2416 }
2417 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002418}
2419
2420static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002421dict_copy(PyDictObject *mp)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002424}
2425
2426PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002427PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 PyObject *copy;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002430 PyDictObject *mp;
2431 Py_ssize_t i, n;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 if (o == NULL || !PyDict_Check(o)) {
2434 PyErr_BadInternalCall();
2435 return NULL;
2436 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002437 mp = (PyDictObject *)o;
2438 if (_PyDict_HasSplitTable(mp)) {
2439 PyDictObject *split_copy;
Victor Stinner742da042016-09-07 17:40:12 -07002440 Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
2441 PyObject **newvalues;
2442 newvalues = new_values(size);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002443 if (newvalues == NULL)
2444 return PyErr_NoMemory();
2445 split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
2446 if (split_copy == NULL) {
2447 free_values(newvalues);
2448 return NULL;
2449 }
2450 split_copy->ma_values = newvalues;
2451 split_copy->ma_keys = mp->ma_keys;
2452 split_copy->ma_used = mp->ma_used;
2453 DK_INCREF(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002454 for (i = 0, n = size; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002455 PyObject *value = mp->ma_values[i];
2456 Py_XINCREF(value);
2457 split_copy->ma_values[i] = value;
2458 }
Benjamin Peterson7ce67e42012-04-24 10:32:57 -04002459 if (_PyObject_GC_IS_TRACKED(mp))
2460 _PyObject_GC_TRACK(split_copy);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002461 return (PyObject *)split_copy;
2462 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 copy = PyDict_New();
2464 if (copy == NULL)
2465 return NULL;
2466 if (PyDict_Merge(copy, o, 1) == 0)
2467 return copy;
2468 Py_DECREF(copy);
2469 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002470}
2471
Martin v. Löwis18e16552006-02-15 17:27:45 +00002472Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00002473PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00002474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 if (mp == NULL || !PyDict_Check(mp)) {
2476 PyErr_BadInternalCall();
2477 return -1;
2478 }
2479 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00002480}
2481
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002482PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002483PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 if (mp == NULL || !PyDict_Check(mp)) {
2486 PyErr_BadInternalCall();
2487 return NULL;
2488 }
2489 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002490}
2491
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002492PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002493PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 if (mp == NULL || !PyDict_Check(mp)) {
2496 PyErr_BadInternalCall();
2497 return NULL;
2498 }
2499 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002500}
2501
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002502PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002503PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 if (mp == NULL || !PyDict_Check(mp)) {
2506 PyErr_BadInternalCall();
2507 return NULL;
2508 }
2509 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002510}
2511
Tim Peterse63415e2001-05-08 04:38:29 +00002512/* Return 1 if dicts equal, 0 if not, -1 if error.
2513 * Gets out as soon as any difference is detected.
2514 * Uses only Py_EQ comparison.
2515 */
2516static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002517dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00002518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00002520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 if (a->ma_used != b->ma_used)
2522 /* can't be equal if # of entries differ */
2523 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Victor Stinner742da042016-09-07 17:40:12 -07002525 for (i = 0; i < a->ma_keys->dk_nentries; i++) {
2526 PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002527 PyObject *aval;
2528 if (a->ma_values)
2529 aval = a->ma_values[i];
2530 else
2531 aval = ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 if (aval != NULL) {
2533 int cmp;
2534 PyObject *bval;
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002535 PyObject **vaddr;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002536 PyObject *key = ep->me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 /* temporarily bump aval's refcount to ensure it stays
2538 alive until we're done with it */
2539 Py_INCREF(aval);
2540 /* ditto for key */
2541 Py_INCREF(key);
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002542 /* reuse the known hash value */
Victor Stinner742da042016-09-07 17:40:12 -07002543 if ((b->ma_keys->dk_lookup)(b, key, ep->me_hash, &vaddr, NULL) < 0)
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002544 bval = NULL;
2545 else
2546 bval = *vaddr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 Py_DECREF(key);
2548 if (bval == NULL) {
2549 Py_DECREF(aval);
2550 if (PyErr_Occurred())
2551 return -1;
2552 return 0;
2553 }
2554 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
2555 Py_DECREF(aval);
2556 if (cmp <= 0) /* error or not equal */
2557 return cmp;
2558 }
2559 }
2560 return 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002561}
Tim Peterse63415e2001-05-08 04:38:29 +00002562
2563static PyObject *
2564dict_richcompare(PyObject *v, PyObject *w, int op)
2565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 int cmp;
2567 PyObject *res;
Tim Peterse63415e2001-05-08 04:38:29 +00002568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 if (!PyDict_Check(v) || !PyDict_Check(w)) {
2570 res = Py_NotImplemented;
2571 }
2572 else if (op == Py_EQ || op == Py_NE) {
2573 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
2574 if (cmp < 0)
2575 return NULL;
2576 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
2577 }
2578 else
2579 res = Py_NotImplemented;
2580 Py_INCREF(res);
2581 return res;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002582}
Tim Peterse63415e2001-05-08 04:38:29 +00002583
Larry Hastings61272b72014-01-07 12:41:53 -08002584/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002585
2586@coexist
2587dict.__contains__
2588
2589 key: object
2590 /
2591
Meador Ingee02de8c2014-01-14 16:48:31 -06002592True if D has a key k, else False.
Larry Hastings61272b72014-01-07 12:41:53 -08002593[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002594
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002595static PyObject *
Larry Hastingsc2047262014-01-25 20:43:29 -08002596dict___contains__(PyDictObject *self, PyObject *key)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002597/*[clinic end generated code: output=a3d03db709ed6e6b input=b852b2a19b51ab24]*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002598{
Larry Hastingsc2047262014-01-25 20:43:29 -08002599 register PyDictObject *mp = self;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002600 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002601 Py_ssize_t ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002602 PyObject **value_addr;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002605 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 hash = PyObject_Hash(key);
2607 if (hash == -1)
2608 return NULL;
2609 }
Victor Stinner742da042016-09-07 17:40:12 -07002610 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2611 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002613 if (ix == DKIX_EMPTY || *value_addr == NULL)
2614 Py_RETURN_FALSE;
2615 Py_RETURN_TRUE;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002616}
2617
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002618static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002619dict_get(PyDictObject *mp, PyObject *args)
Barry Warsawc38c5da1997-10-06 17:49:20 +00002620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 PyObject *key;
2622 PyObject *failobj = Py_None;
2623 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002624 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002625 Py_ssize_t ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002626 PyObject **value_addr;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
2629 return NULL;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002632 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 hash = PyObject_Hash(key);
2634 if (hash == -1)
2635 return NULL;
2636 }
Victor Stinner742da042016-09-07 17:40:12 -07002637 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2638 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002640 if (ix == DKIX_EMPTY || *value_addr == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 val = failobj;
Victor Stinner742da042016-09-07 17:40:12 -07002642 else
2643 val = *value_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 Py_INCREF(val);
2645 return val;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002646}
2647
Benjamin Peterson00e98862013-03-07 22:16:29 -05002648PyObject *
2649PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
Guido van Rossum164452c2000-08-08 16:12:54 +00002650{
Benjamin Peterson00e98862013-03-07 22:16:29 -05002651 PyDictObject *mp = (PyDictObject *)d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002653 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002654 Py_ssize_t hashpos, ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002655 PyDictKeyEntry *ep;
2656 PyObject **value_addr;
Guido van Rossum164452c2000-08-08 16:12:54 +00002657
Benjamin Peterson00e98862013-03-07 22:16:29 -05002658 if (!PyDict_Check(d)) {
2659 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 return NULL;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002661 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002663 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 hash = PyObject_Hash(key);
2665 if (hash == -1)
2666 return NULL;
2667 }
Victor Stinner742da042016-09-07 17:40:12 -07002668 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
2669 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002671 if (ix == DKIX_EMPTY || *value_addr == NULL) {
2672 val = defaultobj;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002673 if (mp->ma_keys->dk_usable <= 0) {
2674 /* Need to resize. */
2675 if (insertion_resize(mp) < 0)
2676 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002677 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002678 }
Victor Stinner742da042016-09-07 17:40:12 -07002679 ix = mp->ma_keys->dk_nentries;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002680 Py_INCREF(defaultobj);
Benjamin Petersonb1efa532013-03-04 09:47:50 -05002681 Py_INCREF(key);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002682 MAINTAIN_TRACKING(mp, key, defaultobj);
Victor Stinner742da042016-09-07 17:40:12 -07002683 dk_set_index(mp->ma_keys, hashpos, ix);
2684 ep = &DK_ENTRIES(mp->ma_keys)[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002685 ep->me_key = key;
2686 ep->me_hash = hash;
Victor Stinner742da042016-09-07 17:40:12 -07002687 if (mp->ma_values) {
2688 mp->ma_values[ix] = val;
2689 }
2690 else {
2691 ep->me_value = val;
2692 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002693 mp->ma_keys->dk_usable--;
Victor Stinner742da042016-09-07 17:40:12 -07002694 mp->ma_keys->dk_nentries++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002695 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07002696 mp->ma_version_tag = DICT_NEXT_VERSION();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 }
Victor Stinner742da042016-09-07 17:40:12 -07002698 else
2699 val = *value_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 return val;
Guido van Rossum164452c2000-08-08 16:12:54 +00002701}
2702
Benjamin Peterson00e98862013-03-07 22:16:29 -05002703static PyObject *
2704dict_setdefault(PyDictObject *mp, PyObject *args)
2705{
2706 PyObject *key, *val;
2707 PyObject *defaultobj = Py_None;
2708
2709 if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &defaultobj))
2710 return NULL;
2711
Benjamin Peterson55898502013-03-08 08:36:49 -05002712 val = PyDict_SetDefault((PyObject *)mp, key, defaultobj);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002713 Py_XINCREF(val);
2714 return val;
2715}
Guido van Rossum164452c2000-08-08 16:12:54 +00002716
2717static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002718dict_clear(PyDictObject *mp)
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 PyDict_Clear((PyObject *)mp);
2721 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002722}
2723
Guido van Rossumba6ab842000-12-12 22:02:18 +00002724static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002725dict_pop(PyDictObject *mp, PyObject *args)
Guido van Rossume027d982002-04-12 15:11:59 +00002726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 PyObject *key, *deflt = NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00002728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
2730 return NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06002731
2732 return _PyDict_Pop(mp, key, deflt);
Guido van Rossume027d982002-04-12 15:11:59 +00002733}
2734
2735static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002736dict_popitem(PyDictObject *mp)
Guido van Rossumba6ab842000-12-12 22:02:18 +00002737{
Victor Stinner742da042016-09-07 17:40:12 -07002738 Py_ssize_t i, j;
2739 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 PyObject *res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 /* Allocate the result tuple before checking the size. Believe it
2743 * or not, this allocation could trigger a garbage collection which
2744 * could empty the dict, so if we checked the size first and that
2745 * happened, the result would be an infinite loop (searching for an
2746 * entry that no longer exists). Note that the usual popitem()
2747 * idiom is "while d: k, v = d.popitem()". so needing to throw the
2748 * tuple away if the dict *is* empty isn't a significant
2749 * inefficiency -- possible, but unlikely in practice.
2750 */
2751 res = PyTuple_New(2);
2752 if (res == NULL)
2753 return NULL;
2754 if (mp->ma_used == 0) {
2755 Py_DECREF(res);
2756 PyErr_SetString(PyExc_KeyError,
2757 "popitem(): dictionary is empty");
2758 return NULL;
2759 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002760 /* Convert split table to combined table */
2761 if (mp->ma_keys->dk_lookup == lookdict_split) {
2762 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
2763 Py_DECREF(res);
2764 return NULL;
2765 }
2766 }
2767 ENSURE_ALLOWS_DELETIONS(mp);
Victor Stinner742da042016-09-07 17:40:12 -07002768
2769 /* Pop last item */
2770 ep0 = DK_ENTRIES(mp->ma_keys);
2771 i = mp->ma_keys->dk_nentries - 1;
2772 while (i >= 0 && ep0[i].me_value == NULL) {
2773 i--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 }
Victor Stinner742da042016-09-07 17:40:12 -07002775 assert(i >= 0);
2776
2777 ep = &ep0[i];
2778 j = lookdict_index(mp->ma_keys, ep->me_hash, i);
2779 assert(j >= 0);
2780 assert(dk_get_index(mp->ma_keys, j) == i);
2781 dk_set_index(mp->ma_keys, j, DKIX_DUMMY);
2782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 PyTuple_SET_ITEM(res, 0, ep->me_key);
2784 PyTuple_SET_ITEM(res, 1, ep->me_value);
Victor Stinner742da042016-09-07 17:40:12 -07002785 ep->me_key = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 ep->me_value = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002787 /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
2788 mp->ma_keys->dk_nentries = i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07002790 mp->ma_version_tag = DICT_NEXT_VERSION();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 return res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002792}
2793
Jeremy Hylton8caad492000-06-23 14:18:11 +00002794static int
2795dict_traverse(PyObject *op, visitproc visit, void *arg)
2796{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002797 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson55f44522016-09-05 12:12:59 -07002798 PyDictKeysObject *keys = mp->ma_keys;
Victor Stinner742da042016-09-07 17:40:12 -07002799 PyDictKeyEntry *entries = DK_ENTRIES(mp->ma_keys);
2800 Py_ssize_t i, n = keys->dk_nentries;
2801
Benjamin Peterson55f44522016-09-05 12:12:59 -07002802 if (keys->dk_lookup == lookdict) {
2803 for (i = 0; i < n; i++) {
2804 if (entries[i].me_value != NULL) {
2805 Py_VISIT(entries[i].me_value);
2806 Py_VISIT(entries[i].me_key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002807 }
2808 }
Victor Stinner742da042016-09-07 17:40:12 -07002809 }
2810 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002811 if (mp->ma_values != NULL) {
Benjamin Peterson55f44522016-09-05 12:12:59 -07002812 for (i = 0; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002813 Py_VISIT(mp->ma_values[i]);
2814 }
2815 }
2816 else {
Benjamin Peterson55f44522016-09-05 12:12:59 -07002817 for (i = 0; i < n; i++) {
2818 Py_VISIT(entries[i].me_value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002819 }
2820 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 }
2822 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002823}
2824
2825static int
2826dict_tp_clear(PyObject *op)
2827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 PyDict_Clear(op);
2829 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002830}
2831
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002832static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00002833
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002834Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06002835_PyDict_SizeOf(PyDictObject *mp)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002836{
Victor Stinner742da042016-09-07 17:40:12 -07002837 Py_ssize_t size, usable, res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002838
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002839 size = DK_SIZE(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002840 usable = USABLE_FRACTION(size);
2841
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002842 res = _PyObject_SIZE(Py_TYPE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002843 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07002844 res += usable * sizeof(PyObject*);
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002845 /* If the dictionary is split, the keys portion is accounted-for
2846 in the type object. */
2847 if (mp->ma_keys->dk_refcnt == 1)
Victor Stinner98ee9d52016-09-08 09:33:56 -07002848 res += (sizeof(PyDictKeysObject)
2849 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
2850 + DK_IXSIZE(mp->ma_keys) * size
2851 + sizeof(PyDictKeyEntry) * usable);
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002852 return res;
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002853}
2854
2855Py_ssize_t
2856_PyDict_KeysSize(PyDictKeysObject *keys)
2857{
Victor Stinner98ee9d52016-09-08 09:33:56 -07002858 return (sizeof(PyDictKeysObject)
2859 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
2860 + DK_IXSIZE(keys) * DK_SIZE(keys)
2861 + USABLE_FRACTION(DK_SIZE(keys)) * sizeof(PyDictKeyEntry));
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002862}
2863
doko@ubuntu.com17210f52016-01-14 14:04:59 +01002864static PyObject *
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002865dict_sizeof(PyDictObject *mp)
2866{
2867 return PyLong_FromSsize_t(_PyDict_SizeOf(mp));
2868}
2869
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002870PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
2871
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002872PyDoc_STRVAR(sizeof__doc__,
2873"D.__sizeof__() -> size of D in memory, in bytes");
2874
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002875PyDoc_STRVAR(get__doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00002876"D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002877
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002878PyDoc_STRVAR(setdefault_doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00002879"D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D");
Tim Petersf7f88b12000-12-13 23:18:45 +00002880
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002881PyDoc_STRVAR(pop__doc__,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002882"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00002883If key is not found, d is returned if given, otherwise KeyError is raised");
Guido van Rossume027d982002-04-12 15:11:59 +00002884
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002885PyDoc_STRVAR(popitem__doc__,
Tim Petersf7f88b12000-12-13 23:18:45 +00002886"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000028872-tuple; but raise KeyError if D is empty.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002888
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002889PyDoc_STRVAR(update__doc__,
Brett Cannonf2754162013-05-11 14:46:48 -04002890"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n\
2891If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]\n\
2892If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n\
2893In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00002894
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002895PyDoc_STRVAR(clear__doc__,
2896"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002897
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002898PyDoc_STRVAR(copy__doc__,
2899"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00002900
Guido van Rossumb90c8482007-02-10 01:11:45 +00002901/* Forward */
2902static PyObject *dictkeys_new(PyObject *);
2903static PyObject *dictitems_new(PyObject *);
2904static PyObject *dictvalues_new(PyObject *);
2905
Guido van Rossum45c85d12007-07-27 16:31:40 +00002906PyDoc_STRVAR(keys__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 "D.keys() -> a set-like object providing a view on D's keys");
Guido van Rossum45c85d12007-07-27 16:31:40 +00002908PyDoc_STRVAR(items__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 "D.items() -> a set-like object providing a view on D's items");
Guido van Rossum45c85d12007-07-27 16:31:40 +00002910PyDoc_STRVAR(values__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 "D.values() -> an object providing a view on D's values");
Guido van Rossumb90c8482007-02-10 01:11:45 +00002912
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002913static PyMethodDef mapp_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -07002914 DICT___CONTAINS___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
2916 getitem__doc__},
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002917 {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 sizeof__doc__},
2919 {"get", (PyCFunction)dict_get, METH_VARARGS,
2920 get__doc__},
2921 {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS,
2922 setdefault_doc__},
2923 {"pop", (PyCFunction)dict_pop, METH_VARARGS,
2924 pop__doc__},
2925 {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
2926 popitem__doc__},
2927 {"keys", (PyCFunction)dictkeys_new, METH_NOARGS,
2928 keys__doc__},
2929 {"items", (PyCFunction)dictitems_new, METH_NOARGS,
2930 items__doc__},
2931 {"values", (PyCFunction)dictvalues_new, METH_NOARGS,
2932 values__doc__},
2933 {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
2934 update__doc__},
Larry Hastings5c661892014-01-24 06:17:25 -08002935 DICT_FROMKEYS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
2937 clear__doc__},
2938 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
2939 copy__doc__},
2940 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002941};
2942
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002943/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00002944int
2945PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002946{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002947 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002948 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002950 PyObject **value_addr;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002953 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 hash = PyObject_Hash(key);
2955 if (hash == -1)
2956 return -1;
2957 }
Victor Stinner742da042016-09-07 17:40:12 -07002958 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2959 if (ix == DKIX_ERROR)
2960 return -1;
2961 return (ix != DKIX_EMPTY && *value_addr != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002962}
2963
Thomas Wouterscf297e42007-02-23 15:07:44 +00002964/* Internal version of PyDict_Contains used when the hash value is already known */
2965int
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002966_PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00002967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002969 PyObject **value_addr;
Victor Stinner742da042016-09-07 17:40:12 -07002970 Py_ssize_t ix;
Thomas Wouterscf297e42007-02-23 15:07:44 +00002971
Victor Stinner742da042016-09-07 17:40:12 -07002972 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2973 if (ix == DKIX_ERROR)
2974 return -1;
2975 return (ix != DKIX_EMPTY && *value_addr != NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00002976}
2977
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002978/* Hack to implement "key in dict" */
2979static PySequenceMethods dict_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 0, /* sq_length */
2981 0, /* sq_concat */
2982 0, /* sq_repeat */
2983 0, /* sq_item */
2984 0, /* sq_slice */
2985 0, /* sq_ass_item */
2986 0, /* sq_ass_slice */
2987 PyDict_Contains, /* sq_contains */
2988 0, /* sq_inplace_concat */
2989 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002990};
2991
Guido van Rossum09e563a2001-05-01 12:10:21 +00002992static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002993dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 PyObject *self;
Victor Stinnera9f61a52013-07-16 22:17:26 +02002996 PyDictObject *d;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 assert(type != NULL && type->tp_alloc != NULL);
2999 self = type->tp_alloc(type, 0);
Victor Stinnera9f61a52013-07-16 22:17:26 +02003000 if (self == NULL)
3001 return NULL;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003002 d = (PyDictObject *)self;
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003003
Victor Stinnera9f61a52013-07-16 22:17:26 +02003004 /* The object has been implicitly tracked by tp_alloc */
3005 if (type == &PyDict_Type)
3006 _PyObject_GC_UNTRACK(d);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003007
3008 d->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07003009 d->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07003010 d->ma_keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003011 if (d->ma_keys == NULL) {
3012 Py_DECREF(self);
3013 return NULL;
3014 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 return self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003016}
3017
Tim Peters25786c02001-09-02 08:22:48 +00003018static int
3019dict_init(PyObject *self, PyObject *args, PyObject *kwds)
3020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00003022}
3023
Tim Peters6d6c1a32001-08-02 04:15:00 +00003024static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003025dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00003026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003028}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003029
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003030PyDoc_STRVAR(dictionary_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00003031"dict() -> new empty dictionary\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00003032"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003033" (key, value) pairs\n"
3034"dict(iterable) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00003035" d = {}\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003036" for k, v in iterable:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00003037" d[k] = v\n"
3038"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
3039" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00003040
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003041PyTypeObject PyDict_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3043 "dict",
3044 sizeof(PyDictObject),
3045 0,
3046 (destructor)dict_dealloc, /* tp_dealloc */
3047 0, /* tp_print */
3048 0, /* tp_getattr */
3049 0, /* tp_setattr */
3050 0, /* tp_reserved */
3051 (reprfunc)dict_repr, /* tp_repr */
3052 0, /* tp_as_number */
3053 &dict_as_sequence, /* tp_as_sequence */
3054 &dict_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003055 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 0, /* tp_call */
3057 0, /* tp_str */
3058 PyObject_GenericGetAttr, /* tp_getattro */
3059 0, /* tp_setattro */
3060 0, /* tp_as_buffer */
3061 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3062 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
3063 dictionary_doc, /* tp_doc */
3064 dict_traverse, /* tp_traverse */
3065 dict_tp_clear, /* tp_clear */
3066 dict_richcompare, /* tp_richcompare */
3067 0, /* tp_weaklistoffset */
3068 (getiterfunc)dict_iter, /* tp_iter */
3069 0, /* tp_iternext */
3070 mapp_methods, /* tp_methods */
3071 0, /* tp_members */
3072 0, /* tp_getset */
3073 0, /* tp_base */
3074 0, /* tp_dict */
3075 0, /* tp_descr_get */
3076 0, /* tp_descr_set */
3077 0, /* tp_dictoffset */
3078 dict_init, /* tp_init */
3079 PyType_GenericAlloc, /* tp_alloc */
3080 dict_new, /* tp_new */
3081 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003082};
3083
Victor Stinner3c1e4812012-03-26 22:10:51 +02003084PyObject *
3085_PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
3086{
3087 PyObject *kv;
3088 kv = _PyUnicode_FromId(key); /* borrowed */
Victor Stinner5b3b1002013-07-22 23:50:57 +02003089 if (kv == NULL) {
3090 PyErr_Clear();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003091 return NULL;
Victor Stinner5b3b1002013-07-22 23:50:57 +02003092 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003093 return PyDict_GetItem(dp, kv);
3094}
3095
Guido van Rossum3cca2451997-05-16 14:23:33 +00003096/* For backward compatibility with old dictionary interface */
3097
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003098PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003099PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003101 PyObject *kv, *rv;
3102 kv = PyUnicode_FromString(key);
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003103 if (kv == NULL) {
3104 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 return NULL;
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003106 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 rv = PyDict_GetItem(v, kv);
3108 Py_DECREF(kv);
3109 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003110}
3111
3112int
Victor Stinner3c1e4812012-03-26 22:10:51 +02003113_PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
3114{
3115 PyObject *kv;
3116 kv = _PyUnicode_FromId(key); /* borrowed */
3117 if (kv == NULL)
3118 return -1;
3119 return PyDict_SetItem(v, kv, item);
3120}
3121
3122int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003123PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 PyObject *kv;
3126 int err;
3127 kv = PyUnicode_FromString(key);
3128 if (kv == NULL)
3129 return -1;
3130 PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
3131 err = PyDict_SetItem(v, kv, item);
3132 Py_DECREF(kv);
3133 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003134}
3135
3136int
Victor Stinner5fd2e5a2013-11-06 18:58:22 +01003137_PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
3138{
3139 PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
3140 if (kv == NULL)
3141 return -1;
3142 return PyDict_DelItem(v, kv);
3143}
3144
3145int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003146PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 PyObject *kv;
3149 int err;
3150 kv = PyUnicode_FromString(key);
3151 if (kv == NULL)
3152 return -1;
3153 err = PyDict_DelItem(v, kv);
3154 Py_DECREF(kv);
3155 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003156}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003157
Raymond Hettinger019a1482004-03-18 02:41:19 +00003158/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003159
3160typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 PyObject_HEAD
3162 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
3163 Py_ssize_t di_used;
3164 Py_ssize_t di_pos;
3165 PyObject* di_result; /* reusable result tuple for iteritems */
3166 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003167} dictiterobject;
3168
3169static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003170dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 dictiterobject *di;
3173 di = PyObject_GC_New(dictiterobject, itertype);
3174 if (di == NULL)
3175 return NULL;
3176 Py_INCREF(dict);
3177 di->di_dict = dict;
3178 di->di_used = dict->ma_used;
3179 di->di_pos = 0;
3180 di->len = dict->ma_used;
3181 if (itertype == &PyDictIterItem_Type) {
3182 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
3183 if (di->di_result == NULL) {
3184 Py_DECREF(di);
3185 return NULL;
3186 }
3187 }
3188 else
3189 di->di_result = NULL;
3190 _PyObject_GC_TRACK(di);
3191 return (PyObject *)di;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003192}
3193
3194static void
3195dictiter_dealloc(dictiterobject *di)
3196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 Py_XDECREF(di->di_dict);
3198 Py_XDECREF(di->di_result);
3199 PyObject_GC_Del(di);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003200}
3201
3202static int
3203dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
3204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 Py_VISIT(di->di_dict);
3206 Py_VISIT(di->di_result);
3207 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003208}
3209
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003210static PyObject *
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003211dictiter_len(dictiterobject *di)
3212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 Py_ssize_t len = 0;
3214 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
3215 len = di->len;
3216 return PyLong_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003217}
3218
Guido van Rossumb90c8482007-02-10 01:11:45 +00003219PyDoc_STRVAR(length_hint_doc,
3220 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003221
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003222static PyObject *
3223dictiter_reduce(dictiterobject *di);
3224
3225PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3226
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003227static PyMethodDef dictiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS,
3229 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003230 {"__reduce__", (PyCFunction)dictiter_reduce, METH_NOARGS,
3231 reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003233};
3234
Raymond Hettinger019a1482004-03-18 02:41:19 +00003235static PyObject *dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00003236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 PyObject *key;
Victor Stinner742da042016-09-07 17:40:12 -07003238 Py_ssize_t i, n, offset;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003239 PyDictKeysObject *k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003241 PyObject **value_ptr;
Guido van Rossum213c7a62001-04-23 14:08:49 +00003242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 if (d == NULL)
3244 return NULL;
3245 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00003246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 if (di->di_used != d->ma_used) {
3248 PyErr_SetString(PyExc_RuntimeError,
3249 "dictionary changed size during iteration");
3250 di->di_used = -1; /* Make this state sticky */
3251 return NULL;
3252 }
Guido van Rossum2147df72002-07-16 20:30:22 +00003253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 i = di->di_pos;
3255 if (i < 0)
3256 goto fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003257 k = d->ma_keys;
3258 if (d->ma_values) {
3259 value_ptr = &d->ma_values[i];
3260 offset = sizeof(PyObject *);
3261 }
3262 else {
Victor Stinner742da042016-09-07 17:40:12 -07003263 value_ptr = &DK_ENTRIES(k)[i].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003264 offset = sizeof(PyDictKeyEntry);
3265 }
Victor Stinner742da042016-09-07 17:40:12 -07003266 n = k->dk_nentries - 1;
3267 while (i <= n && *value_ptr == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003268 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 i++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003270 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 di->di_pos = i+1;
Victor Stinner742da042016-09-07 17:40:12 -07003272 if (i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 goto fail;
3274 di->len--;
Victor Stinner742da042016-09-07 17:40:12 -07003275 key = DK_ENTRIES(k)[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 Py_INCREF(key);
3277 return key;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003278
3279fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003281 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003283}
3284
Raymond Hettinger019a1482004-03-18 02:41:19 +00003285PyTypeObject PyDictIterKey_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3287 "dict_keyiterator", /* tp_name */
3288 sizeof(dictiterobject), /* tp_basicsize */
3289 0, /* tp_itemsize */
3290 /* methods */
3291 (destructor)dictiter_dealloc, /* tp_dealloc */
3292 0, /* tp_print */
3293 0, /* tp_getattr */
3294 0, /* tp_setattr */
3295 0, /* tp_reserved */
3296 0, /* tp_repr */
3297 0, /* tp_as_number */
3298 0, /* tp_as_sequence */
3299 0, /* tp_as_mapping */
3300 0, /* tp_hash */
3301 0, /* tp_call */
3302 0, /* tp_str */
3303 PyObject_GenericGetAttr, /* tp_getattro */
3304 0, /* tp_setattro */
3305 0, /* tp_as_buffer */
3306 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3307 0, /* tp_doc */
3308 (traverseproc)dictiter_traverse, /* tp_traverse */
3309 0, /* tp_clear */
3310 0, /* tp_richcompare */
3311 0, /* tp_weaklistoffset */
3312 PyObject_SelfIter, /* tp_iter */
3313 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
3314 dictiter_methods, /* tp_methods */
3315 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003316};
3317
3318static PyObject *dictiter_iternextvalue(dictiterobject *di)
3319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -07003321 Py_ssize_t i, n, offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003323 PyObject **value_ptr;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 if (d == NULL)
3326 return NULL;
3327 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 if (di->di_used != d->ma_used) {
3330 PyErr_SetString(PyExc_RuntimeError,
3331 "dictionary changed size during iteration");
3332 di->di_used = -1; /* Make this state sticky */
3333 return NULL;
3334 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 i = di->di_pos;
Victor Stinner742da042016-09-07 17:40:12 -07003337 n = d->ma_keys->dk_nentries - 1;
3338 if (i < 0 || i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003339 goto fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003340 if (d->ma_values) {
3341 value_ptr = &d->ma_values[i];
3342 offset = sizeof(PyObject *);
3343 }
3344 else {
Victor Stinner742da042016-09-07 17:40:12 -07003345 value_ptr = &DK_ENTRIES(d->ma_keys)[i].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003346 offset = sizeof(PyDictKeyEntry);
3347 }
Victor Stinner742da042016-09-07 17:40:12 -07003348 while (i <= n && *value_ptr == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003349 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 i++;
Victor Stinner742da042016-09-07 17:40:12 -07003351 if (i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 goto fail;
3353 }
3354 di->di_pos = i+1;
3355 di->len--;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003356 value = *value_ptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 Py_INCREF(value);
3358 return value;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003359
3360fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003361 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003362 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003364}
3365
3366PyTypeObject PyDictIterValue_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3368 "dict_valueiterator", /* tp_name */
3369 sizeof(dictiterobject), /* tp_basicsize */
3370 0, /* tp_itemsize */
3371 /* methods */
3372 (destructor)dictiter_dealloc, /* tp_dealloc */
3373 0, /* tp_print */
3374 0, /* tp_getattr */
3375 0, /* tp_setattr */
3376 0, /* tp_reserved */
3377 0, /* tp_repr */
3378 0, /* tp_as_number */
3379 0, /* tp_as_sequence */
3380 0, /* tp_as_mapping */
3381 0, /* tp_hash */
3382 0, /* tp_call */
3383 0, /* tp_str */
3384 PyObject_GenericGetAttr, /* tp_getattro */
3385 0, /* tp_setattro */
3386 0, /* tp_as_buffer */
3387 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3388 0, /* tp_doc */
3389 (traverseproc)dictiter_traverse, /* tp_traverse */
3390 0, /* tp_clear */
3391 0, /* tp_richcompare */
3392 0, /* tp_weaklistoffset */
3393 PyObject_SelfIter, /* tp_iter */
3394 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
3395 dictiter_methods, /* tp_methods */
3396 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003397};
3398
3399static PyObject *dictiter_iternextitem(dictiterobject *di)
3400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 PyObject *key, *value, *result = di->di_result;
Victor Stinner742da042016-09-07 17:40:12 -07003402 Py_ssize_t i, n, offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003404 PyObject **value_ptr;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 if (d == NULL)
3407 return NULL;
3408 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 if (di->di_used != d->ma_used) {
3411 PyErr_SetString(PyExc_RuntimeError,
3412 "dictionary changed size during iteration");
3413 di->di_used = -1; /* Make this state sticky */
3414 return NULL;
3415 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003417 i = di->di_pos;
3418 if (i < 0)
3419 goto fail;
Victor Stinner742da042016-09-07 17:40:12 -07003420 n = d->ma_keys->dk_nentries - 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003421 if (d->ma_values) {
3422 value_ptr = &d->ma_values[i];
3423 offset = sizeof(PyObject *);
3424 }
3425 else {
Victor Stinner742da042016-09-07 17:40:12 -07003426 value_ptr = &DK_ENTRIES(d->ma_keys)[i].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003427 offset = sizeof(PyDictKeyEntry);
3428 }
Victor Stinner742da042016-09-07 17:40:12 -07003429 while (i <= n && *value_ptr == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003430 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 i++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003432 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 di->di_pos = i+1;
Victor Stinner742da042016-09-07 17:40:12 -07003434 if (i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 goto fail;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 if (result->ob_refcnt == 1) {
3438 Py_INCREF(result);
3439 Py_DECREF(PyTuple_GET_ITEM(result, 0));
3440 Py_DECREF(PyTuple_GET_ITEM(result, 1));
3441 } else {
3442 result = PyTuple_New(2);
3443 if (result == NULL)
3444 return NULL;
3445 }
3446 di->len--;
Victor Stinner742da042016-09-07 17:40:12 -07003447 key = DK_ENTRIES(d->ma_keys)[i].me_key;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003448 value = *value_ptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 Py_INCREF(key);
3450 Py_INCREF(value);
Eric Snow96c6af92015-05-29 22:21:39 -06003451 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3452 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003454
3455fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003457 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003459}
3460
3461PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3463 "dict_itemiterator", /* tp_name */
3464 sizeof(dictiterobject), /* tp_basicsize */
3465 0, /* tp_itemsize */
3466 /* methods */
3467 (destructor)dictiter_dealloc, /* tp_dealloc */
3468 0, /* tp_print */
3469 0, /* tp_getattr */
3470 0, /* tp_setattr */
3471 0, /* tp_reserved */
3472 0, /* tp_repr */
3473 0, /* tp_as_number */
3474 0, /* tp_as_sequence */
3475 0, /* tp_as_mapping */
3476 0, /* tp_hash */
3477 0, /* tp_call */
3478 0, /* tp_str */
3479 PyObject_GenericGetAttr, /* tp_getattro */
3480 0, /* tp_setattro */
3481 0, /* tp_as_buffer */
3482 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3483 0, /* tp_doc */
3484 (traverseproc)dictiter_traverse, /* tp_traverse */
3485 0, /* tp_clear */
3486 0, /* tp_richcompare */
3487 0, /* tp_weaklistoffset */
3488 PyObject_SelfIter, /* tp_iter */
3489 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
3490 dictiter_methods, /* tp_methods */
3491 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003492};
Guido van Rossumb90c8482007-02-10 01:11:45 +00003493
3494
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003495static PyObject *
3496dictiter_reduce(dictiterobject *di)
3497{
3498 PyObject *list;
3499 dictiterobject tmp;
3500
3501 list = PyList_New(0);
3502 if (!list)
3503 return NULL;
3504
3505 /* copy the itertor state */
3506 tmp = *di;
3507 Py_XINCREF(tmp.di_dict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003508
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003509 /* iterate the temporary into a list */
3510 for(;;) {
3511 PyObject *element = 0;
3512 if (Py_TYPE(di) == &PyDictIterItem_Type)
3513 element = dictiter_iternextitem(&tmp);
3514 else if (Py_TYPE(di) == &PyDictIterKey_Type)
3515 element = dictiter_iternextkey(&tmp);
3516 else if (Py_TYPE(di) == &PyDictIterValue_Type)
3517 element = dictiter_iternextvalue(&tmp);
3518 else
3519 assert(0);
3520 if (element) {
3521 if (PyList_Append(list, element)) {
3522 Py_DECREF(element);
3523 Py_DECREF(list);
3524 Py_XDECREF(tmp.di_dict);
3525 return NULL;
3526 }
3527 Py_DECREF(element);
3528 } else
3529 break;
3530 }
3531 Py_XDECREF(tmp.di_dict);
3532 /* check for error */
3533 if (tmp.di_dict != NULL) {
3534 /* we have an error */
3535 Py_DECREF(list);
3536 return NULL;
3537 }
Antoine Pitroua7013882012-04-05 00:04:20 +02003538 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003539}
3540
Guido van Rossum3ac67412007-02-10 18:55:06 +00003541/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003542/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00003543/***********************************************/
3544
Guido van Rossumb90c8482007-02-10 01:11:45 +00003545/* The instance lay-out is the same for all three; but the type differs. */
3546
Guido van Rossumb90c8482007-02-10 01:11:45 +00003547static void
Eric Snow96c6af92015-05-29 22:21:39 -06003548dictview_dealloc(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 Py_XDECREF(dv->dv_dict);
3551 PyObject_GC_Del(dv);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003552}
3553
3554static int
Eric Snow96c6af92015-05-29 22:21:39 -06003555dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557 Py_VISIT(dv->dv_dict);
3558 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003559}
3560
Guido van Rossum83825ac2007-02-10 04:54:19 +00003561static Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003562dictview_len(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 Py_ssize_t len = 0;
3565 if (dv->dv_dict != NULL)
3566 len = dv->dv_dict->ma_used;
3567 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003568}
3569
Eric Snow96c6af92015-05-29 22:21:39 -06003570PyObject *
3571_PyDictView_New(PyObject *dict, PyTypeObject *type)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003572{
Eric Snow96c6af92015-05-29 22:21:39 -06003573 _PyDictViewObject *dv;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 if (dict == NULL) {
3575 PyErr_BadInternalCall();
3576 return NULL;
3577 }
3578 if (!PyDict_Check(dict)) {
3579 /* XXX Get rid of this restriction later */
3580 PyErr_Format(PyExc_TypeError,
3581 "%s() requires a dict argument, not '%s'",
3582 type->tp_name, dict->ob_type->tp_name);
3583 return NULL;
3584 }
Eric Snow96c6af92015-05-29 22:21:39 -06003585 dv = PyObject_GC_New(_PyDictViewObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 if (dv == NULL)
3587 return NULL;
3588 Py_INCREF(dict);
3589 dv->dv_dict = (PyDictObject *)dict;
3590 _PyObject_GC_TRACK(dv);
3591 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003592}
3593
Neal Norwitze36f2ba2007-02-26 23:12:28 +00003594/* TODO(guido): The views objects are not complete:
3595
3596 * support more set operations
3597 * support arbitrary mappings?
3598 - either these should be static or exported in dictobject.h
3599 - if public then they should probably be in builtins
3600*/
3601
Guido van Rossumaac530c2007-08-24 22:33:45 +00003602/* Return 1 if self is a subset of other, iterating over self;
3603 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00003604static int
3605all_contained_in(PyObject *self, PyObject *other)
3606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 PyObject *iter = PyObject_GetIter(self);
3608 int ok = 1;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 if (iter == NULL)
3611 return -1;
3612 for (;;) {
3613 PyObject *next = PyIter_Next(iter);
3614 if (next == NULL) {
3615 if (PyErr_Occurred())
3616 ok = -1;
3617 break;
3618 }
3619 ok = PySequence_Contains(other, next);
3620 Py_DECREF(next);
3621 if (ok <= 0)
3622 break;
3623 }
3624 Py_DECREF(iter);
3625 return ok;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003626}
3627
3628static PyObject *
3629dictview_richcompare(PyObject *self, PyObject *other, int op)
3630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 Py_ssize_t len_self, len_other;
3632 int ok;
3633 PyObject *result;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 assert(self != NULL);
3636 assert(PyDictViewSet_Check(self));
3637 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00003638
Brian Curtindfc80e32011-08-10 20:28:54 -05003639 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
3640 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642 len_self = PyObject_Size(self);
3643 if (len_self < 0)
3644 return NULL;
3645 len_other = PyObject_Size(other);
3646 if (len_other < 0)
3647 return NULL;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 ok = 0;
3650 switch(op) {
Guido van Rossumaac530c2007-08-24 22:33:45 +00003651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 case Py_NE:
3653 case Py_EQ:
3654 if (len_self == len_other)
3655 ok = all_contained_in(self, other);
3656 if (op == Py_NE && ok >= 0)
3657 ok = !ok;
3658 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 case Py_LT:
3661 if (len_self < len_other)
3662 ok = all_contained_in(self, other);
3663 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 case Py_LE:
3666 if (len_self <= len_other)
3667 ok = all_contained_in(self, other);
3668 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 case Py_GT:
3671 if (len_self > len_other)
3672 ok = all_contained_in(other, self);
3673 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 case Py_GE:
3676 if (len_self >= len_other)
3677 ok = all_contained_in(other, self);
3678 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003680 }
3681 if (ok < 0)
3682 return NULL;
3683 result = ok ? Py_True : Py_False;
3684 Py_INCREF(result);
3685 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003686}
3687
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003688static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003689dictview_repr(_PyDictViewObject *dv)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003691 PyObject *seq;
3692 PyObject *result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003694 seq = PySequence_List((PyObject *)dv);
3695 if (seq == NULL)
3696 return NULL;
3697
3698 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
3699 Py_DECREF(seq);
3700 return result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003701}
3702
Guido van Rossum3ac67412007-02-10 18:55:06 +00003703/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003704
3705static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003706dictkeys_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 if (dv->dv_dict == NULL) {
3709 Py_RETURN_NONE;
3710 }
3711 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003712}
3713
3714static int
Eric Snow96c6af92015-05-29 22:21:39 -06003715dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00003716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003717 if (dv->dv_dict == NULL)
3718 return 0;
3719 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003720}
3721
Guido van Rossum83825ac2007-02-10 04:54:19 +00003722static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003723 (lenfunc)dictview_len, /* sq_length */
3724 0, /* sq_concat */
3725 0, /* sq_repeat */
3726 0, /* sq_item */
3727 0, /* sq_slice */
3728 0, /* sq_ass_item */
3729 0, /* sq_ass_slice */
3730 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003731};
3732
Guido van Rossum523259b2007-08-24 23:41:22 +00003733static PyObject*
3734dictviews_sub(PyObject* self, PyObject *other)
3735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003736 PyObject *result = PySet_New(self);
3737 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003738 _Py_IDENTIFIER(difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 if (result == NULL)
3741 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003742
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003743 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003744 if (tmp == NULL) {
3745 Py_DECREF(result);
3746 return NULL;
3747 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 Py_DECREF(tmp);
3750 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003751}
3752
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003753PyObject*
3754_PyDictView_Intersect(PyObject* self, PyObject *other)
Guido van Rossum523259b2007-08-24 23:41:22 +00003755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 PyObject *result = PySet_New(self);
3757 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003758 _Py_IDENTIFIER(intersection_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 if (result == NULL)
3761 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003762
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003763 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_intersection_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 if (tmp == NULL) {
3765 Py_DECREF(result);
3766 return NULL;
3767 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 Py_DECREF(tmp);
3770 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003771}
3772
3773static PyObject*
3774dictviews_or(PyObject* self, PyObject *other)
3775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 PyObject *result = PySet_New(self);
3777 PyObject *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02003778 _Py_IDENTIFIER(update);
Victor Stinnerd1a9cc22011-10-13 22:51:17 +02003779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 if (result == NULL)
3781 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003782
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003783 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003784 if (tmp == NULL) {
3785 Py_DECREF(result);
3786 return NULL;
3787 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003789 Py_DECREF(tmp);
3790 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003791}
3792
3793static PyObject*
3794dictviews_xor(PyObject* self, PyObject *other)
3795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 PyObject *result = PySet_New(self);
3797 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003798 _Py_IDENTIFIER(symmetric_difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 if (result == NULL)
3801 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003802
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003803 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_symmetric_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 if (tmp == NULL) {
3805 Py_DECREF(result);
3806 return NULL;
3807 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 Py_DECREF(tmp);
3810 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003811}
3812
3813static PyNumberMethods dictviews_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 0, /*nb_add*/
3815 (binaryfunc)dictviews_sub, /*nb_subtract*/
3816 0, /*nb_multiply*/
3817 0, /*nb_remainder*/
3818 0, /*nb_divmod*/
3819 0, /*nb_power*/
3820 0, /*nb_negative*/
3821 0, /*nb_positive*/
3822 0, /*nb_absolute*/
3823 0, /*nb_bool*/
3824 0, /*nb_invert*/
3825 0, /*nb_lshift*/
3826 0, /*nb_rshift*/
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003827 (binaryfunc)_PyDictView_Intersect, /*nb_and*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 (binaryfunc)dictviews_xor, /*nb_xor*/
3829 (binaryfunc)dictviews_or, /*nb_or*/
Guido van Rossum523259b2007-08-24 23:41:22 +00003830};
3831
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003832static PyObject*
3833dictviews_isdisjoint(PyObject *self, PyObject *other)
3834{
3835 PyObject *it;
3836 PyObject *item = NULL;
3837
3838 if (self == other) {
Eric Snow96c6af92015-05-29 22:21:39 -06003839 if (dictview_len((_PyDictViewObject *)self) == 0)
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003840 Py_RETURN_TRUE;
3841 else
3842 Py_RETURN_FALSE;
3843 }
3844
3845 /* Iterate over the shorter object (only if other is a set,
3846 * because PySequence_Contains may be expensive otherwise): */
3847 if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
Eric Snow96c6af92015-05-29 22:21:39 -06003848 Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003849 Py_ssize_t len_other = PyObject_Size(other);
3850 if (len_other == -1)
3851 return NULL;
3852
3853 if ((len_other > len_self)) {
3854 PyObject *tmp = other;
3855 other = self;
3856 self = tmp;
3857 }
3858 }
3859
3860 it = PyObject_GetIter(other);
3861 if (it == NULL)
3862 return NULL;
3863
3864 while ((item = PyIter_Next(it)) != NULL) {
3865 int contains = PySequence_Contains(self, item);
3866 Py_DECREF(item);
3867 if (contains == -1) {
3868 Py_DECREF(it);
3869 return NULL;
3870 }
3871
3872 if (contains) {
3873 Py_DECREF(it);
3874 Py_RETURN_FALSE;
3875 }
3876 }
3877 Py_DECREF(it);
3878 if (PyErr_Occurred())
3879 return NULL; /* PyIter_Next raised an exception. */
3880 Py_RETURN_TRUE;
3881}
3882
3883PyDoc_STRVAR(isdisjoint_doc,
3884"Return True if the view and the given iterable have a null intersection.");
3885
Guido van Rossumb90c8482007-02-10 01:11:45 +00003886static PyMethodDef dictkeys_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003887 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
3888 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00003890};
3891
3892PyTypeObject PyDictKeys_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3894 "dict_keys", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06003895 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 0, /* tp_itemsize */
3897 /* methods */
3898 (destructor)dictview_dealloc, /* tp_dealloc */
3899 0, /* tp_print */
3900 0, /* tp_getattr */
3901 0, /* tp_setattr */
3902 0, /* tp_reserved */
3903 (reprfunc)dictview_repr, /* tp_repr */
3904 &dictviews_as_number, /* tp_as_number */
3905 &dictkeys_as_sequence, /* tp_as_sequence */
3906 0, /* tp_as_mapping */
3907 0, /* tp_hash */
3908 0, /* tp_call */
3909 0, /* tp_str */
3910 PyObject_GenericGetAttr, /* tp_getattro */
3911 0, /* tp_setattro */
3912 0, /* tp_as_buffer */
3913 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3914 0, /* tp_doc */
3915 (traverseproc)dictview_traverse, /* tp_traverse */
3916 0, /* tp_clear */
3917 dictview_richcompare, /* tp_richcompare */
3918 0, /* tp_weaklistoffset */
3919 (getiterfunc)dictkeys_iter, /* tp_iter */
3920 0, /* tp_iternext */
3921 dictkeys_methods, /* tp_methods */
3922 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00003923};
3924
3925static PyObject *
3926dictkeys_new(PyObject *dict)
3927{
Eric Snow96c6af92015-05-29 22:21:39 -06003928 return _PyDictView_New(dict, &PyDictKeys_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003929}
3930
Guido van Rossum3ac67412007-02-10 18:55:06 +00003931/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003932
3933static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003934dictitems_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 if (dv->dv_dict == NULL) {
3937 Py_RETURN_NONE;
3938 }
3939 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003940}
3941
3942static int
Eric Snow96c6af92015-05-29 22:21:39 -06003943dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00003944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 PyObject *key, *value, *found;
3946 if (dv->dv_dict == NULL)
3947 return 0;
3948 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
3949 return 0;
3950 key = PyTuple_GET_ITEM(obj, 0);
3951 value = PyTuple_GET_ITEM(obj, 1);
3952 found = PyDict_GetItem((PyObject *)dv->dv_dict, key);
3953 if (found == NULL) {
3954 if (PyErr_Occurred())
3955 return -1;
3956 return 0;
3957 }
3958 return PyObject_RichCompareBool(value, found, Py_EQ);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003959}
3960
Guido van Rossum83825ac2007-02-10 04:54:19 +00003961static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 (lenfunc)dictview_len, /* sq_length */
3963 0, /* sq_concat */
3964 0, /* sq_repeat */
3965 0, /* sq_item */
3966 0, /* sq_slice */
3967 0, /* sq_ass_item */
3968 0, /* sq_ass_slice */
3969 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003970};
3971
Guido van Rossumb90c8482007-02-10 01:11:45 +00003972static PyMethodDef dictitems_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003973 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
3974 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00003976};
3977
3978PyTypeObject PyDictItems_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003979 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3980 "dict_items", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06003981 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 0, /* tp_itemsize */
3983 /* methods */
3984 (destructor)dictview_dealloc, /* tp_dealloc */
3985 0, /* tp_print */
3986 0, /* tp_getattr */
3987 0, /* tp_setattr */
3988 0, /* tp_reserved */
3989 (reprfunc)dictview_repr, /* tp_repr */
3990 &dictviews_as_number, /* tp_as_number */
3991 &dictitems_as_sequence, /* tp_as_sequence */
3992 0, /* tp_as_mapping */
3993 0, /* tp_hash */
3994 0, /* tp_call */
3995 0, /* tp_str */
3996 PyObject_GenericGetAttr, /* tp_getattro */
3997 0, /* tp_setattro */
3998 0, /* tp_as_buffer */
3999 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4000 0, /* tp_doc */
4001 (traverseproc)dictview_traverse, /* tp_traverse */
4002 0, /* tp_clear */
4003 dictview_richcompare, /* tp_richcompare */
4004 0, /* tp_weaklistoffset */
4005 (getiterfunc)dictitems_iter, /* tp_iter */
4006 0, /* tp_iternext */
4007 dictitems_methods, /* tp_methods */
4008 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004009};
4010
4011static PyObject *
4012dictitems_new(PyObject *dict)
4013{
Eric Snow96c6af92015-05-29 22:21:39 -06004014 return _PyDictView_New(dict, &PyDictItems_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004015}
4016
Guido van Rossum3ac67412007-02-10 18:55:06 +00004017/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004018
4019static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004020dictvalues_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 if (dv->dv_dict == NULL) {
4023 Py_RETURN_NONE;
4024 }
4025 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004026}
4027
Guido van Rossum83825ac2007-02-10 04:54:19 +00004028static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004029 (lenfunc)dictview_len, /* sq_length */
4030 0, /* sq_concat */
4031 0, /* sq_repeat */
4032 0, /* sq_item */
4033 0, /* sq_slice */
4034 0, /* sq_ass_item */
4035 0, /* sq_ass_slice */
4036 (objobjproc)0, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004037};
4038
Guido van Rossumb90c8482007-02-10 01:11:45 +00004039static PyMethodDef dictvalues_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004040 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004041};
4042
4043PyTypeObject PyDictValues_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4045 "dict_values", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004046 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004047 0, /* tp_itemsize */
4048 /* methods */
4049 (destructor)dictview_dealloc, /* tp_dealloc */
4050 0, /* tp_print */
4051 0, /* tp_getattr */
4052 0, /* tp_setattr */
4053 0, /* tp_reserved */
4054 (reprfunc)dictview_repr, /* tp_repr */
4055 0, /* tp_as_number */
4056 &dictvalues_as_sequence, /* tp_as_sequence */
4057 0, /* tp_as_mapping */
4058 0, /* tp_hash */
4059 0, /* tp_call */
4060 0, /* tp_str */
4061 PyObject_GenericGetAttr, /* tp_getattro */
4062 0, /* tp_setattro */
4063 0, /* tp_as_buffer */
4064 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4065 0, /* tp_doc */
4066 (traverseproc)dictview_traverse, /* tp_traverse */
4067 0, /* tp_clear */
4068 0, /* tp_richcompare */
4069 0, /* tp_weaklistoffset */
4070 (getiterfunc)dictvalues_iter, /* tp_iter */
4071 0, /* tp_iternext */
4072 dictvalues_methods, /* tp_methods */
4073 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004074};
4075
4076static PyObject *
4077dictvalues_new(PyObject *dict)
4078{
Eric Snow96c6af92015-05-29 22:21:39 -06004079 return _PyDictView_New(dict, &PyDictValues_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004080}
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004081
4082/* Returns NULL if cannot allocate a new PyDictKeysObject,
4083 but does not set an error */
4084PyDictKeysObject *
4085_PyDict_NewKeysForClass(void)
4086{
Victor Stinner742da042016-09-07 17:40:12 -07004087 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004088 if (keys == NULL)
4089 PyErr_Clear();
4090 else
4091 keys->dk_lookup = lookdict_split;
4092 return keys;
4093}
4094
4095#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
4096
4097PyObject *
4098PyObject_GenericGetDict(PyObject *obj, void *context)
4099{
4100 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
4101 if (dictptr == NULL) {
4102 PyErr_SetString(PyExc_AttributeError,
4103 "This object has no __dict__");
4104 return NULL;
4105 }
4106 dict = *dictptr;
4107 if (dict == NULL) {
4108 PyTypeObject *tp = Py_TYPE(obj);
4109 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
4110 DK_INCREF(CACHED_KEYS(tp));
4111 *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
4112 }
4113 else {
4114 *dictptr = dict = PyDict_New();
4115 }
4116 }
4117 Py_XINCREF(dict);
4118 return dict;
4119}
4120
4121int
4122_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
Victor Stinner742da042016-09-07 17:40:12 -07004123 PyObject *key, PyObject *value)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004124{
4125 PyObject *dict;
4126 int res;
4127 PyDictKeysObject *cached;
4128
4129 assert(dictptr != NULL);
4130 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
4131 assert(dictptr != NULL);
4132 dict = *dictptr;
4133 if (dict == NULL) {
4134 DK_INCREF(cached);
4135 dict = new_dict_with_shared_keys(cached);
4136 if (dict == NULL)
4137 return -1;
4138 *dictptr = dict;
4139 }
4140 if (value == NULL) {
4141 res = PyDict_DelItem(dict, key);
4142 if (cached != ((PyDictObject *)dict)->ma_keys) {
4143 CACHED_KEYS(tp) = NULL;
4144 DK_DECREF(cached);
4145 }
4146 } else {
4147 res = PyDict_SetItem(dict, key, value);
4148 if (cached != ((PyDictObject *)dict)->ma_keys) {
4149 /* Either update tp->ht_cached_keys or delete it */
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004150 if (cached->dk_refcnt == 1) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004151 CACHED_KEYS(tp) = make_keys_shared(dict);
Victor Stinner742da042016-09-07 17:40:12 -07004152 }
4153 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004154 CACHED_KEYS(tp) = NULL;
4155 }
4156 DK_DECREF(cached);
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004157 if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
4158 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004159 }
4160 }
4161 } else {
4162 dict = *dictptr;
4163 if (dict == NULL) {
4164 dict = PyDict_New();
4165 if (dict == NULL)
4166 return -1;
4167 *dictptr = dict;
4168 }
4169 if (value == NULL) {
4170 res = PyDict_DelItem(dict, key);
4171 } else {
4172 res = PyDict_SetItem(dict, key, value);
4173 }
4174 }
4175 return res;
4176}
4177
4178void
4179_PyDictKeys_DecRef(PyDictKeysObject *keys)
4180{
4181 DK_DECREF(keys);
4182}