blob: 866a23397aaedfd96ad95f3c28bb36e296005ebf [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
13As of Python 3.6, this is compact and orderd. 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"
Christian Heimes0ded5b52007-12-10 15:50:56 +0000114#include "stringlib/eq.h"
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
Victor Stinner742da042016-09-07 17:40:12 -0700240/* Dictionary reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +0000241#ifndef PyDict_MAXFREELIST
242#define PyDict_MAXFREELIST 80
243#endif
244static PyDictObject *free_list[PyDict_MAXFREELIST];
245static int numfree = 0;
Victor Stinner742da042016-09-07 17:40:12 -0700246static PyDictKeysObject *keys_free_list[PyDict_MAXFREELIST];
247static int numfreekeys = 0;
Raymond Hettinger43442782004-03-17 21:55:03 +0000248
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300249#include "clinic/dictobject.c.h"
250
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100251int
252PyDict_ClearFreeList(void)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 PyDictObject *op;
Victor Stinner742da042016-09-07 17:40:12 -0700255 int ret = numfree + numfreekeys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 while (numfree) {
257 op = free_list[--numfree];
258 assert(PyDict_CheckExact(op));
259 PyObject_GC_Del(op);
260 }
Victor Stinner742da042016-09-07 17:40:12 -0700261 while (numfreekeys) {
262 PyObject_FREE(keys_free_list[--numfreekeys]);
263 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100264 return ret;
265}
266
David Malcolm49526f42012-06-22 14:55:41 -0400267/* Print summary info about the state of the optimized allocator */
268void
269_PyDict_DebugMallocStats(FILE *out)
270{
271 _PyDebugAllocatorStats(out,
272 "free PyDictObject", numfree, sizeof(PyDictObject));
273}
274
275
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100276void
277PyDict_Fini(void)
278{
279 PyDict_ClearFreeList();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000280}
281
Victor Stinner742da042016-09-07 17:40:12 -0700282#define DK_SIZE(dk) ((dk)->dk_size)
283#if SIZEOF_VOID_P > 4
284#define DK_IXSIZE(dk) (DK_SIZE(dk) <= 0xff ? 1 : DK_SIZE(dk) <= 0xffff ? 2 : \
285 DK_SIZE(dk) <= 0xffffffff ? 4 : sizeof(Py_ssize_t))
286#else
287#define DK_IXSIZE(dk) (DK_SIZE(dk) <= 0xff ? 1 : DK_SIZE(dk) <= 0xffff ? 2 : \
288 sizeof(Py_ssize_t))
289#endif
290#define DK_ENTRIES(dk) ((PyDictKeyEntry*)(&(dk)->dk_indices[DK_SIZE(dk) * \
291 DK_IXSIZE(dk)]))
292
Antoine Pitrou2d169b22012-05-12 23:43:44 +0200293#define DK_DEBUG_INCREF _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA
294#define DK_DEBUG_DECREF _Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA
295
296#define DK_INCREF(dk) (DK_DEBUG_INCREF ++(dk)->dk_refcnt)
297#define DK_DECREF(dk) if (DK_DEBUG_DECREF (--(dk)->dk_refcnt) == 0) free_keys_object(dk)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400298#define DK_MASK(dk) (((dk)->dk_size)-1)
299#define IS_POWER_OF_2(x) (((x) & (x-1)) == 0)
300
Victor Stinner742da042016-09-07 17:40:12 -0700301
302/* lookup indices. returns DKIX_EMPTY, DKIX_DUMMY, or ix >=0 */
Benjamin Peterson73222252016-09-08 09:58:47 -0700303static inline Py_ssize_t
Victor Stinner742da042016-09-07 17:40:12 -0700304dk_get_index(PyDictKeysObject *keys, Py_ssize_t i)
305{
306 Py_ssize_t s = DK_SIZE(keys);
307 if (s <= 0xff) {
308 return ((char*) &keys->dk_indices[0])[i];
309 }
310 else if (s <= 0xffff) {
311 return ((int16_t*)&keys->dk_indices[0])[i];
312 }
313#if SIZEOF_VOID_P > 4
314 else if (s <= 0xffffffff) {
315 return ((int32_t*)&keys->dk_indices[0])[i];
316 }
317#endif
318 else {
319 return ((Py_ssize_t*)&keys->dk_indices[0])[i];
320 }
321}
322
323/* write to indices. */
Benjamin Peterson73222252016-09-08 09:58:47 -0700324static inline void
Victor Stinner742da042016-09-07 17:40:12 -0700325dk_set_index(PyDictKeysObject *keys, Py_ssize_t i, Py_ssize_t ix)
326{
327 Py_ssize_t s = DK_SIZE(keys);
328 if (s <= 0xff) {
329 ((char*) &keys->dk_indices[0])[i] = (char)ix;
330 }
331 else if (s <= 0xffff) {
332 ((int16_t*) &keys->dk_indices[0])[i] = (int16_t)ix;
333 }
334#if SIZEOF_VOID_P > 4
335 else if (s <= 0xffffffff) {
336 ((int32_t*) &keys->dk_indices[0])[i] = (int32_t)ix;
337 }
338#endif
339 else {
340 ((Py_ssize_t*) &keys->dk_indices[0])[i] = ix;
341 }
342}
343
344
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200345/* USABLE_FRACTION is the maximum dictionary load.
Victor Stinner742da042016-09-07 17:40:12 -0700346 * Increasing this ratio makes dictionaries more dense resulting in more
347 * collisions. Decreasing it improves sparseness at the expense of spreading
348 * indices over more cache lines and at the cost of total memory consumed.
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200349 *
350 * USABLE_FRACTION must obey the following:
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400351 * (0 < USABLE_FRACTION(n) < n) for all n >= 2
352 *
Victor Stinner742da042016-09-07 17:40:12 -0700353 * USABLE_FRACTION should be quick to calculate.
354 * Fractions around 1/2 to 2/3 seem to work well in practice.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400355 */
Victor Stinner742da042016-09-07 17:40:12 -0700356#define USABLE_FRACTION(n) (((n) << 1)/3)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400357
Victor Stinner742da042016-09-07 17:40:12 -0700358/* ESTIMATE_SIZE is reverse function of USABLE_FRACTION.
359 * This can be used to reserve enough size to insert n entries without
360 * resizing.
361 */
362#define ESTIMATE_SIZE(n) (((n)*3) >> 1)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400363
Victor Stinner742da042016-09-07 17:40:12 -0700364/* Alternative fraction that is otherwise close enough to 2n/3 to make
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400365 * little difference. 8 * 2/3 == 8 * 5/8 == 5. 16 * 2/3 == 16 * 5/8 == 10.
366 * 32 * 2/3 = 21, 32 * 5/8 = 20.
367 * Its advantage is that it is faster to compute on machines with slow division.
368 * #define USABLE_FRACTION(n) (((n) >> 1) + ((n) >> 2) - ((n) >> 3))
Victor Stinner742da042016-09-07 17:40:12 -0700369 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400370
Victor Stinnera9f61a52013-07-16 22:17:26 +0200371/* GROWTH_RATE. Growth rate upon hitting maximum load.
372 * Currently set to used*2 + capacity/2.
373 * This means that dicts double in size when growing without deletions,
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700374 * but have more head room when the number of deletions is on a par with the
375 * number of insertions.
376 * Raising this to used*4 doubles memory consumption depending on the size of
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200377 * the dictionary, but results in half the number of resizes, less effort to
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700378 * resize.
379 * GROWTH_RATE was set to used*4 up to version 3.2.
380 * GROWTH_RATE was set to used*2 in version 3.3.0
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200381 */
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700382#define GROWTH_RATE(d) (((d)->ma_used*2)+((d)->ma_keys->dk_size>>1))
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400383
384#define ENSURE_ALLOWS_DELETIONS(d) \
385 if ((d)->ma_keys->dk_lookup == lookdict_unicode_nodummy) { \
386 (d)->ma_keys->dk_lookup = lookdict_unicode; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400388
389/* This immutable, empty PyDictKeysObject is used for PyDict_Clear()
390 * (which cannot fail and thus can do no allocation).
391 */
392static PyDictKeysObject empty_keys_struct = {
393 2, /* dk_refcnt 1 for this struct, 1 for dummy_struct */
394 1, /* dk_size */
395 lookdict_split, /* dk_lookup */
396 0, /* dk_usable (immutable) */
Victor Stinner742da042016-09-07 17:40:12 -0700397 0, /* dk_nentries */
398 {DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY,
399 DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY}, /* dk_indices */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400400};
401
402static PyObject *empty_values[1] = { NULL };
403
404#define Py_EMPTY_KEYS &empty_keys_struct
405
406static PyDictKeysObject *new_keys_object(Py_ssize_t size)
407{
408 PyDictKeysObject *dk;
Victor Stinner742da042016-09-07 17:40:12 -0700409 Py_ssize_t es, usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400410
Victor Stinner742da042016-09-07 17:40:12 -0700411 assert(size >= PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400412 assert(IS_POWER_OF_2(size));
Victor Stinner742da042016-09-07 17:40:12 -0700413
414 usable = USABLE_FRACTION(size);
415 if (size <= 0xff) {
416 es = 1;
417 }
418 else if (size <= 0xffff) {
419 es = 2;
420 }
421#if SIZEOF_VOID_P > 4
422 else if (size <= 0xffffffff) {
423 es = 4;
424 }
425#endif
426 else {
427 es = sizeof(Py_ssize_t);
428 }
429
430 if (size == PyDict_MINSIZE && numfreekeys > 0) {
431 dk = keys_free_list[--numfreekeys];
432 }
433 else {
Victor Stinner98ee9d52016-09-08 09:33:56 -0700434 dk = PyObject_MALLOC(sizeof(PyDictKeysObject)
435 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
436 + es * size
437 + sizeof(PyDictKeyEntry) * usable);
Victor Stinner742da042016-09-07 17:40:12 -0700438 if (dk == NULL) {
439 PyErr_NoMemory();
440 return NULL;
441 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400442 }
Antoine Pitrou2d169b22012-05-12 23:43:44 +0200443 DK_DEBUG_INCREF dk->dk_refcnt = 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400444 dk->dk_size = size;
Victor Stinner742da042016-09-07 17:40:12 -0700445 dk->dk_usable = usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400446 dk->dk_lookup = lookdict_unicode_nodummy;
Victor Stinner742da042016-09-07 17:40:12 -0700447 dk->dk_nentries = 0;
448 memset(&dk->dk_indices[0], 0xff, es * size);
449 memset(DK_ENTRIES(dk), 0, sizeof(PyDictKeyEntry) * usable);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400450 return dk;
451}
452
453static void
454free_keys_object(PyDictKeysObject *keys)
455{
Victor Stinner742da042016-09-07 17:40:12 -0700456 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400457 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -0700458 for (i = 0, n = keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400459 Py_XDECREF(entries[i].me_key);
460 Py_XDECREF(entries[i].me_value);
461 }
Victor Stinner742da042016-09-07 17:40:12 -0700462 if (keys->dk_size == PyDict_MINSIZE && numfreekeys < PyDict_MAXFREELIST) {
463 keys_free_list[numfreekeys++] = keys;
464 return;
465 }
Raymond Hettingerce5179f2016-01-31 08:56:21 -0800466 PyObject_FREE(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400467}
468
469#define new_values(size) PyMem_NEW(PyObject *, size)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400470#define free_values(values) PyMem_FREE(values)
471
472/* Consumes a reference to the keys object */
473static PyObject *
474new_dict(PyDictKeysObject *keys, PyObject **values)
475{
476 PyDictObject *mp;
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200477 assert(keys != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 if (numfree) {
479 mp = free_list[--numfree];
480 assert (mp != NULL);
481 assert (Py_TYPE(mp) == &PyDict_Type);
482 _Py_NewReference((PyObject *)mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400484 else {
485 mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
486 if (mp == NULL) {
487 DK_DECREF(keys);
488 free_values(values);
489 return NULL;
490 }
491 }
492 mp->ma_keys = keys;
493 mp->ma_values = values;
494 mp->ma_used = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000496}
497
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400498/* Consumes a reference to the keys object */
499static PyObject *
500new_dict_with_shared_keys(PyDictKeysObject *keys)
501{
502 PyObject **values;
503 Py_ssize_t i, size;
504
Victor Stinner742da042016-09-07 17:40:12 -0700505 size = USABLE_FRACTION(DK_SIZE(keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400506 values = new_values(size);
507 if (values == NULL) {
508 DK_DECREF(keys);
509 return PyErr_NoMemory();
510 }
511 for (i = 0; i < size; i++) {
512 values[i] = NULL;
513 }
514 return new_dict(keys, values);
515}
516
517PyObject *
518PyDict_New(void)
519{
Victor Stinner742da042016-09-07 17:40:12 -0700520 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200521 if (keys == NULL)
522 return NULL;
523 return new_dict(keys, NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400524}
525
Victor Stinner742da042016-09-07 17:40:12 -0700526/* Search index of hash table from offset of entry table */
527static Py_ssize_t
528lookdict_index(PyDictKeysObject *k, Py_hash_t hash, Py_ssize_t index)
529{
530 size_t i, perturb;
531 size_t mask = DK_MASK(k);
532 Py_ssize_t ix;
533
534 i = (size_t)hash & mask;
535 ix = dk_get_index(k, i);
536 if (ix == index) {
537 return i;
538 }
539 if (ix == DKIX_EMPTY) {
540 return DKIX_EMPTY;
541 }
542
543 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
544 i = mask & ((i << 2) + i + perturb + 1);
545 ix = dk_get_index(k, i);
546 if (ix == index) {
547 return i;
548 }
549 if (ix == DKIX_EMPTY) {
550 return DKIX_EMPTY;
551 }
552 }
553 assert(0); /* NOT REACHED */
554 return DKIX_ERROR;
555}
556
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000557/*
558The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000559This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000560Open addressing is preferred over chaining since the link overhead for
561chaining would be substantial (100% with typical malloc overhead).
562
Tim Peterseb28ef22001-06-02 05:27:19 +0000563The initial probe index is computed as hash mod the table size. Subsequent
564probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000565
566All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000567
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000568The details in this version are due to Tim Peters, building on many past
Tim Peterseb28ef22001-06-02 05:27:19 +0000569contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000570Christian Tismer.
Fred Drake1bff34a2000-08-31 19:31:38 +0000571
Victor Stinner742da042016-09-07 17:40:12 -0700572lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000573comparison raises an exception (this was new in Python 2.5).
Guido van Rossum89d8c602007-09-18 17:26:56 +0000574lookdict_unicode() below is specialized to string keys, comparison of which can
Victor Stinner742da042016-09-07 17:40:12 -0700575never raise an exception; that function can never return DKIX_ERROR.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400576lookdict_unicode_nodummy is further specialized for string keys that cannot be
577the <dummy> value.
Victor Stinner742da042016-09-07 17:40:12 -0700578For both, when the key isn't found a DKIX_EMPTY is returned. hashpos returns
579where the key index should be inserted.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000580*/
Victor Stinner742da042016-09-07 17:40:12 -0700581static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400582lookdict(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700583 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000584{
Victor Stinner742da042016-09-07 17:40:12 -0700585 size_t i, perturb, mask;
586 Py_ssize_t ix, freeslot;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200587 int cmp;
Victor Stinner742da042016-09-07 17:40:12 -0700588 PyDictKeysObject *dk;
589 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 PyObject *startkey;
Tim Peterseb28ef22001-06-02 05:27:19 +0000591
Antoine Pitrou9a234902012-05-13 20:48:01 +0200592top:
Victor Stinner742da042016-09-07 17:40:12 -0700593 dk = mp->ma_keys;
594 mask = DK_MASK(dk);
595 ep0 = DK_ENTRIES(dk);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700597
598 ix = dk_get_index(dk, i);
599 if (ix == DKIX_EMPTY) {
600 if (hashpos != NULL)
601 *hashpos = i;
602 *value_addr = NULL;
603 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400604 }
Victor Stinner742da042016-09-07 17:40:12 -0700605 if (ix == DKIX_DUMMY) {
606 freeslot = i;
607 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 else {
Victor Stinner742da042016-09-07 17:40:12 -0700609 ep = &ep0[ix];
610 if (ep->me_key == key) {
611 *value_addr = &ep->me_value;
612 if (hashpos != NULL)
613 *hashpos = i;
614 return ix;
615 }
616 if (ep->me_key != NULL && ep->me_hash == hash) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 startkey = ep->me_key;
618 Py_INCREF(startkey);
619 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
620 Py_DECREF(startkey);
621 if (cmp < 0)
Victor Stinner742da042016-09-07 17:40:12 -0700622 return DKIX_ERROR;
623 if (dk == mp->ma_keys && ep->me_key == startkey) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400624 if (cmp > 0) {
625 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700626 if (hashpos != NULL)
627 *hashpos = i;
628 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400629 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 }
631 else {
Antoine Pitrou9a234902012-05-13 20:48:01 +0200632 /* The dict was mutated, restart */
633 goto top;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 }
635 }
Victor Stinner742da042016-09-07 17:40:12 -0700636 freeslot = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 }
Tim Peters15d49292001-05-27 07:39:22 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700640 i = ((i << 2) + i + perturb + 1) & mask;
641 ix = dk_get_index(dk, i);
642 if (ix == DKIX_EMPTY) {
643 if (hashpos != NULL) {
644 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400645 }
Victor Stinner742da042016-09-07 17:40:12 -0700646 *value_addr = NULL;
647 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400648 }
Victor Stinner742da042016-09-07 17:40:12 -0700649 if (ix == DKIX_DUMMY) {
650 if (freeslot == -1)
651 freeslot = i;
652 continue;
653 }
654 ep = &ep0[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400655 if (ep->me_key == key) {
Victor Stinner742da042016-09-07 17:40:12 -0700656 if (hashpos != NULL) {
657 *hashpos = i;
658 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400659 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700660 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400661 }
Victor Stinner742da042016-09-07 17:40:12 -0700662 if (ep->me_hash == hash && ep->me_key != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 startkey = ep->me_key;
664 Py_INCREF(startkey);
665 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
666 Py_DECREF(startkey);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400667 if (cmp < 0) {
668 *value_addr = NULL;
Victor Stinner742da042016-09-07 17:40:12 -0700669 return DKIX_ERROR;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400670 }
Victor Stinner742da042016-09-07 17:40:12 -0700671 if (dk == mp->ma_keys && ep->me_key == startkey) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400672 if (cmp > 0) {
Victor Stinner742da042016-09-07 17:40:12 -0700673 if (hashpos != NULL) {
674 *hashpos = i;
675 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400676 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700677 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400678 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 }
680 else {
Antoine Pitrou9a234902012-05-13 20:48:01 +0200681 /* The dict was mutated, restart */
682 goto top;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 }
684 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 }
686 assert(0); /* NOT REACHED */
687 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000688}
689
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400690/* Specialized version for string-only keys */
Victor Stinner742da042016-09-07 17:40:12 -0700691static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400692lookdict_unicode(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700693 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Fred Drake1bff34a2000-08-31 19:31:38 +0000694{
Victor Stinner742da042016-09-07 17:40:12 -0700695 size_t i, perturb;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200696 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700697 Py_ssize_t ix, freeslot;
698 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Fred Drake1bff34a2000-08-31 19:31:38 +0000699
Victor Stinner742da042016-09-07 17:40:12 -0700700 assert(mp->ma_values == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 /* Make sure this function doesn't have to handle non-unicode keys,
702 including subclasses of str; e.g., one reason to subclass
703 unicodes is to override __eq__, and for speed we don't cater to
704 that here. */
705 if (!PyUnicode_CheckExact(key)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400706 mp->ma_keys->dk_lookup = lookdict;
Victor Stinner742da042016-09-07 17:40:12 -0700707 return lookdict(mp, key, hash, value_addr, hashpos);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 }
Mark Dickinson57e683e2011-09-24 18:18:40 +0100709 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700710 ix = dk_get_index(mp->ma_keys, i);
711 if (ix == DKIX_EMPTY) {
712 if (hashpos != NULL)
713 *hashpos = i;
714 *value_addr = NULL;
715 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400716 }
Victor Stinner742da042016-09-07 17:40:12 -0700717 if (ix == DKIX_DUMMY) {
718 freeslot = i;
719 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 else {
Victor Stinner742da042016-09-07 17:40:12 -0700721 ep = &ep0[ix];
722 /* only split table can be ix != DKIX_DUMMY && me_key == NULL */
723 assert(ep->me_key != NULL);
724 if (ep->me_key == key || (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
725 if (hashpos != NULL)
726 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400727 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700728 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400729 }
Victor Stinner742da042016-09-07 17:40:12 -0700730 freeslot = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 }
Tim Peters15d49292001-05-27 07:39:22 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700734 i = mask & ((i << 2) + i + perturb + 1);
735 ix = dk_get_index(mp->ma_keys, i);
736 if (ix == DKIX_EMPTY) {
737 if (hashpos != NULL) {
738 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400739 }
Victor Stinner742da042016-09-07 17:40:12 -0700740 *value_addr = NULL;
741 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400742 }
Victor Stinner742da042016-09-07 17:40:12 -0700743 if (ix == DKIX_DUMMY) {
744 if (freeslot == -1)
745 freeslot = i;
746 continue;
747 }
748 ep = &ep0[ix];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 if (ep->me_key == key
750 || (ep->me_hash == hash
Victor Stinner742da042016-09-07 17:40:12 -0700751 && ep->me_key != NULL
752 && unicode_eq(ep->me_key, key))) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400753 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700754 if (hashpos != NULL) {
755 *hashpos = i;
756 }
757 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400758 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 }
760 assert(0); /* NOT REACHED */
761 return 0;
Fred Drake1bff34a2000-08-31 19:31:38 +0000762}
763
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400764/* Faster version of lookdict_unicode when it is known that no <dummy> keys
765 * will be present. */
Victor Stinner742da042016-09-07 17:40:12 -0700766static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400767lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700768 Py_hash_t hash, PyObject ***value_addr,
769 Py_ssize_t *hashpos)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400770{
Victor Stinner742da042016-09-07 17:40:12 -0700771 size_t i, perturb;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200772 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700773 Py_ssize_t ix;
774 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400775
Victor Stinner742da042016-09-07 17:40:12 -0700776 assert(mp->ma_values == NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400777 /* Make sure this function doesn't have to handle non-unicode keys,
778 including subclasses of str; e.g., one reason to subclass
779 unicodes is to override __eq__, and for speed we don't cater to
780 that here. */
781 if (!PyUnicode_CheckExact(key)) {
782 mp->ma_keys->dk_lookup = lookdict;
Victor Stinner742da042016-09-07 17:40:12 -0700783 return lookdict(mp, key, hash, value_addr, hashpos);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400784 }
785 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700786 ix = dk_get_index(mp->ma_keys, i);
787 assert (ix != DKIX_DUMMY);
788 if (ix == DKIX_EMPTY) {
789 if (hashpos != NULL)
790 *hashpos = i;
791 *value_addr = NULL;
792 return DKIX_EMPTY;
793 }
794 ep = &ep0[ix];
795 assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
796 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400797 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700798 if (hashpos != NULL)
799 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400800 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700801 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400802 }
803 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700804 i = mask & ((i << 2) + i + perturb + 1);
805 ix = dk_get_index(mp->ma_keys, i);
806 assert (ix != DKIX_DUMMY);
807 if (ix == DKIX_EMPTY) {
808 if (hashpos != NULL)
809 *hashpos = i;
810 *value_addr = NULL;
811 return DKIX_EMPTY;
812 }
813 ep = &ep0[ix];
814 assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
815 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400816 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700817 if (hashpos != NULL)
818 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400819 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700820 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400821 }
822 }
823 assert(0); /* NOT REACHED */
824 return 0;
825}
826
827/* Version of lookdict for split tables.
828 * All split tables and only split tables use this lookup function.
829 * Split tables only contain unicode keys and no dummy keys,
830 * so algorithm is the same as lookdict_unicode_nodummy.
831 */
Victor Stinner742da042016-09-07 17:40:12 -0700832static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400833lookdict_split(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700834 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400835{
Victor Stinner742da042016-09-07 17:40:12 -0700836 size_t i, perturb;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200837 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700838 Py_ssize_t ix;
839 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400840
Victor Stinner742da042016-09-07 17:40:12 -0700841 /* mp must split table */
842 assert(mp->ma_values != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400843 if (!PyUnicode_CheckExact(key)) {
Victor Stinner742da042016-09-07 17:40:12 -0700844 ix = lookdict(mp, key, hash, value_addr, hashpos);
845 if (ix >= 0) {
846 *value_addr = &mp->ma_values[ix];
847 }
848 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400849 }
Victor Stinner742da042016-09-07 17:40:12 -0700850
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400851 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700852 ix = dk_get_index(mp->ma_keys, i);
853 if (ix == DKIX_EMPTY) {
854 if (hashpos != NULL)
855 *hashpos = i;
856 *value_addr = NULL;
857 return DKIX_EMPTY;
858 }
859 assert(ix >= 0);
860 ep = &ep0[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400861 assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700862 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400863 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700864 if (hashpos != NULL)
865 *hashpos = i;
866 *value_addr = &mp->ma_values[ix];
867 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400868 }
869 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700870 i = mask & ((i << 2) + i + perturb + 1);
871 ix = dk_get_index(mp->ma_keys, i);
872 if (ix == DKIX_EMPTY) {
873 if (hashpos != NULL)
874 *hashpos = i;
875 *value_addr = NULL;
876 return DKIX_EMPTY;
877 }
878 assert(ix >= 0);
879 ep = &ep0[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400880 assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700881 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400882 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700883 if (hashpos != NULL)
884 *hashpos = i;
885 *value_addr = &mp->ma_values[ix];
886 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400887 }
888 }
889 assert(0); /* NOT REACHED */
890 return 0;
891}
892
Benjamin Petersonfb886362010-04-24 18:21:17 +0000893int
894_PyDict_HasOnlyStringKeys(PyObject *dict)
895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 Py_ssize_t pos = 0;
897 PyObject *key, *value;
Benjamin Petersonf6096542010-11-17 22:33:12 +0000898 assert(PyDict_Check(dict));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 /* Shortcut */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400900 if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 return 1;
902 while (PyDict_Next(dict, &pos, &key, &value))
903 if (!PyUnicode_Check(key))
904 return 0;
905 return 1;
Benjamin Petersonfb886362010-04-24 18:21:17 +0000906}
907
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000908#define MAINTAIN_TRACKING(mp, key, value) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 do { \
910 if (!_PyObject_GC_IS_TRACKED(mp)) { \
911 if (_PyObject_GC_MAY_BE_TRACKED(key) || \
912 _PyObject_GC_MAY_BE_TRACKED(value)) { \
913 _PyObject_GC_TRACK(mp); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 } \
915 } \
916 } while(0)
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000917
918void
919_PyDict_MaybeUntrack(PyObject *op)
920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 PyDictObject *mp;
922 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -0700923 Py_ssize_t i, numentries;
924 PyDictKeyEntry *ep0;
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
927 return;
928
929 mp = (PyDictObject *) op;
Victor Stinner742da042016-09-07 17:40:12 -0700930 ep0 = DK_ENTRIES(mp->ma_keys);
931 numentries = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400932 if (_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -0700933 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400934 if ((value = mp->ma_values[i]) == NULL)
935 continue;
936 if (_PyObject_GC_MAY_BE_TRACKED(value)) {
Victor Stinner742da042016-09-07 17:40:12 -0700937 assert(!_PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400938 return;
939 }
940 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400942 else {
Victor Stinner742da042016-09-07 17:40:12 -0700943 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400944 if ((value = ep0[i].me_value) == NULL)
945 continue;
946 if (_PyObject_GC_MAY_BE_TRACKED(value) ||
947 _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
948 return;
949 }
950 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 _PyObject_GC_UNTRACK(op);
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000952}
953
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400954/* Internal function to find slot for an item from its hash
955 * when it is known that the key is not present in the dict.
956 */
Victor Stinner742da042016-09-07 17:40:12 -0700957static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400958find_empty_slot(PyDictObject *mp, PyObject *key, Py_hash_t hash,
Victor Stinner742da042016-09-07 17:40:12 -0700959 PyObject ***value_addr, Py_ssize_t *hashpos)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000960{
Victor Stinner742da042016-09-07 17:40:12 -0700961 size_t i, perturb;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400962 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700963 Py_ssize_t ix;
964 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000965
Victor Stinner742da042016-09-07 17:40:12 -0700966 assert(hashpos != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400967 assert(key != NULL);
968 if (!PyUnicode_CheckExact(key))
969 mp->ma_keys->dk_lookup = lookdict;
970 i = hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700971 ix = dk_get_index(mp->ma_keys, i);
972 for (perturb = hash; ix != DKIX_EMPTY; perturb >>= PERTURB_SHIFT) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400973 i = (i << 2) + i + perturb + 1;
Victor Stinner742da042016-09-07 17:40:12 -0700974 ix = dk_get_index(mp->ma_keys, i & mask);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 }
Victor Stinner742da042016-09-07 17:40:12 -0700976 ep = &ep0[mp->ma_keys->dk_nentries];
977 *hashpos = i & mask;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400978 assert(ep->me_value == NULL);
979 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -0700980 *value_addr = &mp->ma_values[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400981 else
982 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700983 return ix;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000984}
985
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400986static int
987insertion_resize(PyDictObject *mp)
988{
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700989 return dictresize(mp, GROWTH_RATE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400990}
Antoine Pitroue965d972012-02-27 00:45:12 +0100991
992/*
993Internal routine to insert a new item into the table.
994Used both by the internal resize routine and by the public insert routine.
Antoine Pitroue965d972012-02-27 00:45:12 +0100995Returns -1 if an error occurred, or 0 on success.
996*/
997static int
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400998insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +0100999{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001000 PyObject *old_value;
1001 PyObject **value_addr;
Victor Stinner742da042016-09-07 17:40:12 -07001002 PyDictKeyEntry *ep, *ep0;
1003 Py_ssize_t hashpos, ix;
Antoine Pitroue965d972012-02-27 00:45:12 +01001004
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001005 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
1006 if (insertion_resize(mp) < 0)
1007 return -1;
1008 }
1009
Victor Stinner742da042016-09-07 17:40:12 -07001010 ix = mp->ma_keys->dk_lookup(mp, key, hash, &value_addr, &hashpos);
1011 if (ix == DKIX_ERROR) {
Antoine Pitroue965d972012-02-27 00:45:12 +01001012 return -1;
1013 }
Victor Stinner742da042016-09-07 17:40:12 -07001014
Antoine Pitroud6967322014-10-18 00:35:00 +02001015 assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
Benjamin Petersona6f195e2012-04-30 10:23:40 -04001016 Py_INCREF(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001017 MAINTAIN_TRACKING(mp, key, value);
Victor Stinner742da042016-09-07 17:40:12 -07001018
1019 /* When insertion order is different from shared key, we can't share
1020 * the key anymore. Convert this instance to combine table.
1021 */
1022 if (_PyDict_HasSplitTable(mp) &&
1023 ((ix >= 0 && *value_addr == NULL && mp->ma_used != ix) ||
1024 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
1025 if (insertion_resize(mp) < 0) {
1026 Py_DECREF(value);
1027 return -1;
1028 }
1029 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
1030 ix = DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001031 }
Victor Stinner742da042016-09-07 17:40:12 -07001032
1033 if (ix == DKIX_EMPTY) {
1034 /* Insert into new slot. */
1035 if (mp->ma_keys->dk_usable <= 0) {
1036 /* Need to resize. */
1037 if (insertion_resize(mp) < 0) {
1038 Py_DECREF(value);
1039 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001040 }
Victor Stinner742da042016-09-07 17:40:12 -07001041 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
1042 }
1043 ep0 = DK_ENTRIES(mp->ma_keys);
1044 ep = &ep0[mp->ma_keys->dk_nentries];
1045 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
1046 Py_INCREF(key);
1047 ep->me_key = key;
1048 ep->me_hash = hash;
1049 if (mp->ma_values) {
1050 assert (mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
1051 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001052 }
1053 else {
Victor Stinner742da042016-09-07 17:40:12 -07001054 ep->me_value = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001055 }
1056 mp->ma_used++;
Victor Stinner742da042016-09-07 17:40:12 -07001057 mp->ma_keys->dk_usable--;
1058 mp->ma_keys->dk_nentries++;
1059 assert(mp->ma_keys->dk_usable >= 0);
1060 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001061 }
Victor Stinner742da042016-09-07 17:40:12 -07001062
1063 assert(value_addr != NULL);
1064
1065 old_value = *value_addr;
1066 if (old_value != NULL) {
1067 *value_addr = value;
1068 Py_DECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
1069 return 0;
1070 }
1071
1072 /* pending state */
1073 assert(_PyDict_HasSplitTable(mp));
1074 assert(ix == mp->ma_used);
1075 *value_addr = value;
1076 mp->ma_used++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001077 return 0;
Antoine Pitroue965d972012-02-27 00:45:12 +01001078}
1079
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001080/*
1081Internal routine used by dictresize() to insert an item which is
1082known to be absent from the dict. This routine also assumes that
1083the dict contains no deleted entries. Besides the performance benefit,
1084using insertdict() in dictresize() is dangerous (SF bug #1456209).
1085Note that no refcounts are changed by this routine; if needed, the caller
1086is responsible for incref'ing `key` and `value`.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001087Neither mp->ma_used nor k->dk_usable are modified by this routine; the caller
1088must set them correctly
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001089*/
1090static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001091insertdict_clean(PyDictObject *mp, PyObject *key, Py_hash_t hash,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 PyObject *value)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001093{
Victor Stinner742da042016-09-07 17:40:12 -07001094 size_t i, perturb;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001095 PyDictKeysObject *k = mp->ma_keys;
1096 size_t mask = (size_t)DK_SIZE(k)-1;
Victor Stinner742da042016-09-07 17:40:12 -07001097 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001098 PyDictKeyEntry *ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001099
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001100 assert(k->dk_lookup != NULL);
1101 assert(value != NULL);
1102 assert(key != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001103 assert(PyUnicode_CheckExact(key) || k->dk_lookup == lookdict);
1104 i = hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -07001105 for (perturb = hash; dk_get_index(k, i) != DKIX_EMPTY;
1106 perturb >>= PERTURB_SHIFT) {
1107 i = mask & ((i << 2) + i + perturb + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 }
Victor Stinner742da042016-09-07 17:40:12 -07001109 ep = &ep0[k->dk_nentries];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 assert(ep->me_value == NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001111 dk_set_index(k, i, k->dk_nentries);
1112 k->dk_nentries++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 ep->me_key = key;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001114 ep->me_hash = hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 ep->me_value = value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001116}
1117
1118/*
1119Restructure the table by allocating a new table and reinserting all
1120items again. When entries have been deleted, the new table may
1121actually be smaller than the old one.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001122If a table is split (its keys and hashes are shared, its values are not),
1123then the values are temporarily copied into the table, it is resized as
1124a combined table, then the me_value slots in the old table are NULLed out.
1125After resizing a table is always combined,
1126but can be resplit by make_keys_shared().
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001127*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001128static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001129dictresize(PyDictObject *mp, Py_ssize_t minused)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001130{
Victor Stinner742da042016-09-07 17:40:12 -07001131 Py_ssize_t i, newsize;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001132 PyDictKeysObject *oldkeys;
1133 PyObject **oldvalues;
Victor Stinner742da042016-09-07 17:40:12 -07001134 PyDictKeyEntry *ep0;
Tim Peters91a364d2001-05-19 07:04:38 +00001135
Victor Stinner742da042016-09-07 17:40:12 -07001136 /* Find the smallest table size > minused. */
1137 for (newsize = PyDict_MINSIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 newsize <= minused && newsize > 0;
1139 newsize <<= 1)
1140 ;
1141 if (newsize <= 0) {
1142 PyErr_NoMemory();
1143 return -1;
1144 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001145 oldkeys = mp->ma_keys;
1146 oldvalues = mp->ma_values;
1147 /* Allocate a new table. */
1148 mp->ma_keys = new_keys_object(newsize);
1149 if (mp->ma_keys == NULL) {
1150 mp->ma_keys = oldkeys;
1151 return -1;
1152 }
1153 if (oldkeys->dk_lookup == lookdict)
1154 mp->ma_keys->dk_lookup = lookdict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001155 mp->ma_values = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001156 ep0 = DK_ENTRIES(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001157 /* Main loop below assumes we can transfer refcount to new keys
1158 * and that value is stored in me_value.
1159 * Increment ref-counts and copy values here to compensate
1160 * This (resizing a split table) should be relatively rare */
1161 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001162 for (i = 0; i < oldkeys->dk_nentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001163 if (oldvalues[i] != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001164 Py_INCREF(ep0[i].me_key);
1165 ep0[i].me_value = oldvalues[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 }
1168 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001169 /* Main loop */
Victor Stinner742da042016-09-07 17:40:12 -07001170 for (i = 0; i < oldkeys->dk_nentries; i++) {
1171 PyDictKeyEntry *ep = &ep0[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001172 if (ep->me_value != NULL) {
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001173 insertdict_clean(mp, ep->me_key, ep->me_hash, ep->me_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001176 mp->ma_keys->dk_usable -= mp->ma_used;
1177 if (oldvalues != NULL) {
1178 /* NULL out me_value slot in oldkeys, in case it was shared */
Victor Stinner742da042016-09-07 17:40:12 -07001179 for (i = 0; i < oldkeys->dk_nentries; i++)
1180 ep0[i].me_value = NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001181 DK_DECREF(oldkeys);
Victor Stinner742da042016-09-07 17:40:12 -07001182 if (oldvalues != empty_values) {
1183 free_values(oldvalues);
1184 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001185 }
1186 else {
1187 assert(oldkeys->dk_lookup != lookdict_split);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001188 assert(oldkeys->dk_refcnt == 1);
Raymond Hettingerce5179f2016-01-31 08:56:21 -08001189 DK_DEBUG_DECREF PyObject_FREE(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001190 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001192}
1193
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001194/* Returns NULL if unable to split table.
1195 * A NULL return does not necessarily indicate an error */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001196static PyDictKeysObject *
1197make_keys_shared(PyObject *op)
1198{
1199 Py_ssize_t i;
1200 Py_ssize_t size;
1201 PyDictObject *mp = (PyDictObject *)op;
1202
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001203 if (!PyDict_CheckExact(op))
1204 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001205 if (!_PyDict_HasSplitTable(mp)) {
1206 PyDictKeyEntry *ep0;
1207 PyObject **values;
1208 assert(mp->ma_keys->dk_refcnt == 1);
1209 if (mp->ma_keys->dk_lookup == lookdict) {
1210 return NULL;
1211 }
1212 else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
1213 /* Remove dummy keys */
1214 if (dictresize(mp, DK_SIZE(mp->ma_keys)))
1215 return NULL;
1216 }
1217 assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
1218 /* Copy values into a new array */
Victor Stinner742da042016-09-07 17:40:12 -07001219 ep0 = DK_ENTRIES(mp->ma_keys);
1220 size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001221 values = new_values(size);
1222 if (values == NULL) {
1223 PyErr_SetString(PyExc_MemoryError,
1224 "Not enough memory to allocate new values array");
1225 return NULL;
1226 }
1227 for (i = 0; i < size; i++) {
1228 values[i] = ep0[i].me_value;
1229 ep0[i].me_value = NULL;
1230 }
1231 mp->ma_keys->dk_lookup = lookdict_split;
1232 mp->ma_values = values;
1233 }
1234 DK_INCREF(mp->ma_keys);
1235 return mp->ma_keys;
1236}
Christian Heimes99170a52007-12-19 02:07:34 +00001237
1238PyObject *
1239_PyDict_NewPresized(Py_ssize_t minused)
1240{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001241 Py_ssize_t newsize;
1242 PyDictKeysObject *new_keys;
Victor Stinner742da042016-09-07 17:40:12 -07001243 for (newsize = PyDict_MINSIZE;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001244 newsize <= minused && newsize > 0;
1245 newsize <<= 1)
1246 ;
1247 new_keys = new_keys_object(newsize);
1248 if (new_keys == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001250 return new_dict(new_keys, NULL);
Christian Heimes99170a52007-12-19 02:07:34 +00001251}
1252
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001253/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
1254 * that may occur (originally dicts supported only string keys, and exceptions
1255 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001256 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001257 * (suppressed) occurred while computing the key's hash, or that some error
1258 * (suppressed) occurred when comparing keys in the dict's internal probe
1259 * sequence. A nasty example of the latter is when a Python-coded comparison
1260 * function hits a stack-depth error, which can cause this to return NULL
1261 * even if the key is present.
1262 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001263PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001264PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001265{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001266 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001267 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 PyDictObject *mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 PyThreadState *tstate;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001270 PyObject **value_addr;
1271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 if (!PyDict_Check(op))
1273 return NULL;
1274 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001275 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 {
1277 hash = PyObject_Hash(key);
1278 if (hash == -1) {
1279 PyErr_Clear();
1280 return NULL;
1281 }
1282 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 /* We can arrive here with a NULL tstate during initialization: try
1285 running "python -Wi" for an example related to string interning.
1286 Let's just hope that no exception occurs then... This must be
1287 _PyThreadState_Current and not PyThreadState_GET() because in debug
1288 mode, the latter complains if tstate is NULL. */
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001289 tstate = _PyThreadState_UncheckedGet();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (tstate != NULL && tstate->curexc_type != NULL) {
1291 /* preserve the existing exception */
1292 PyObject *err_type, *err_value, *err_tb;
1293 PyErr_Fetch(&err_type, &err_value, &err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001294 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 /* ignore errors */
1296 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001297 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 return NULL;
1299 }
1300 else {
Victor Stinner742da042016-09-07 17:40:12 -07001301 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1302 if (ix < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 PyErr_Clear();
1304 return NULL;
1305 }
1306 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001307 return *value_addr;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001308}
1309
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001310PyObject *
1311_PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1312{
Victor Stinner742da042016-09-07 17:40:12 -07001313 Py_ssize_t ix;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001314 PyDictObject *mp = (PyDictObject *)op;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001315 PyThreadState *tstate;
1316 PyObject **value_addr;
1317
1318 if (!PyDict_Check(op))
1319 return NULL;
1320
1321 /* We can arrive here with a NULL tstate during initialization: try
1322 running "python -Wi" for an example related to string interning.
1323 Let's just hope that no exception occurs then... This must be
1324 _PyThreadState_Current and not PyThreadState_GET() because in debug
1325 mode, the latter complains if tstate is NULL. */
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001326 tstate = _PyThreadState_UncheckedGet();
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001327 if (tstate != NULL && tstate->curexc_type != NULL) {
1328 /* preserve the existing exception */
1329 PyObject *err_type, *err_value, *err_tb;
1330 PyErr_Fetch(&err_type, &err_value, &err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001331 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001332 /* ignore errors */
1333 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001334 if (ix == DKIX_EMPTY)
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001335 return NULL;
1336 }
1337 else {
Victor Stinner742da042016-09-07 17:40:12 -07001338 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1339 if (ix == DKIX_EMPTY) {
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001340 PyErr_Clear();
1341 return NULL;
1342 }
1343 }
1344 return *value_addr;
1345}
1346
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001347/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
1348 This returns NULL *with* an exception set if an exception occurred.
1349 It returns NULL *without* an exception set if the key wasn't present.
1350*/
1351PyObject *
1352PyDict_GetItemWithError(PyObject *op, PyObject *key)
1353{
Victor Stinner742da042016-09-07 17:40:12 -07001354 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001355 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 PyDictObject*mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001357 PyObject **value_addr;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 if (!PyDict_Check(op)) {
1360 PyErr_BadInternalCall();
1361 return NULL;
1362 }
1363 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001364 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 {
1366 hash = PyObject_Hash(key);
1367 if (hash == -1) {
1368 return NULL;
1369 }
1370 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001371
Victor Stinner742da042016-09-07 17:40:12 -07001372 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1373 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001375 return *value_addr;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001376}
1377
Brett Cannonfd074152012-04-14 14:10:13 -04001378PyObject *
1379_PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
1380{
1381 PyObject *kv;
1382 kv = _PyUnicode_FromId(key); /* borrowed */
1383 if (kv == NULL)
1384 return NULL;
1385 return PyDict_GetItemWithError(dp, kv);
1386}
1387
Victor Stinnerb4efc962015-11-20 09:24:02 +01001388/* Fast version of global value lookup (LOAD_GLOBAL).
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001389 * Lookup in globals, then builtins.
Victor Stinnerb4efc962015-11-20 09:24:02 +01001390 *
1391 * Raise an exception and return NULL if an error occurred (ex: computing the
1392 * key hash failed, key comparison failed, ...). Return NULL if the key doesn't
1393 * exist. Return the value if the key exists.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001394 */
1395PyObject *
1396_PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001397{
Victor Stinner742da042016-09-07 17:40:12 -07001398 Py_ssize_t ix;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001399 Py_hash_t hash;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001400 PyObject **value_addr;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001401
1402 if (!PyUnicode_CheckExact(key) ||
1403 (hash = ((PyASCIIObject *) key)->hash) == -1)
1404 {
1405 hash = PyObject_Hash(key);
1406 if (hash == -1)
1407 return NULL;
Antoine Pitroue965d972012-02-27 00:45:12 +01001408 }
Victor Stinnerb4efc962015-11-20 09:24:02 +01001409
1410 /* namespace 1: globals */
Victor Stinner742da042016-09-07 17:40:12 -07001411 ix = globals->ma_keys->dk_lookup(globals, key, hash, &value_addr, NULL);
1412 if (ix == DKIX_ERROR)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001413 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001414 if (ix != DKIX_EMPTY && *value_addr != NULL)
1415 return *value_addr;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001416
1417 /* namespace 2: builtins */
Victor Stinner742da042016-09-07 17:40:12 -07001418 ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value_addr, NULL);
1419 if (ix < 0)
Victor Stinnerb4efc962015-11-20 09:24:02 +01001420 return NULL;
1421 return *value_addr;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001422}
1423
Antoine Pitroue965d972012-02-27 00:45:12 +01001424/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
1425 * dictionary if it's merely replacing the value for an existing key.
1426 * This means that it's safe to loop over a dictionary with PyDict_Next()
1427 * and occasionally replace a value -- but you can't insert new keys or
1428 * remove them.
1429 */
1430int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001431PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001432{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001433 PyDictObject *mp;
1434 Py_hash_t hash;
Antoine Pitroue965d972012-02-27 00:45:12 +01001435 if (!PyDict_Check(op)) {
1436 PyErr_BadInternalCall();
1437 return -1;
1438 }
1439 assert(key);
1440 assert(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001441 mp = (PyDictObject *)op;
1442 if (!PyUnicode_CheckExact(key) ||
1443 (hash = ((PyASCIIObject *) key)->hash) == -1)
1444 {
Antoine Pitroue965d972012-02-27 00:45:12 +01001445 hash = PyObject_Hash(key);
1446 if (hash == -1)
1447 return -1;
1448 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001449
1450 /* insertdict() handles any resizing that might be necessary */
1451 return insertdict(mp, key, hash, value);
Antoine Pitroue965d972012-02-27 00:45:12 +01001452}
1453
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001454int
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001455_PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
1456 Py_hash_t hash)
1457{
1458 PyDictObject *mp;
1459
1460 if (!PyDict_Check(op)) {
1461 PyErr_BadInternalCall();
1462 return -1;
1463 }
1464 assert(key);
1465 assert(value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001466 assert(hash != -1);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001467 mp = (PyDictObject *)op;
1468
1469 /* insertdict() handles any resizing that might be necessary */
1470 return insertdict(mp, key, hash, value);
1471}
1472
1473int
Tim Peters1f5871e2000-07-04 17:44:48 +00001474PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001475{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001476 Py_hash_t hash;
Guido van Rossumd7047b31995-01-02 19:07:15 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 assert(key);
1479 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001480 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 hash = PyObject_Hash(key);
1482 if (hash == -1)
1483 return -1;
1484 }
Victor Stinner742da042016-09-07 17:40:12 -07001485
1486 return _PyDict_DelItem_KnownHash(op, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001487}
1488
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001489int
1490_PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1491{
Victor Stinner742da042016-09-07 17:40:12 -07001492 Py_ssize_t hashpos, ix;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001493 PyDictObject *mp;
1494 PyDictKeyEntry *ep;
1495 PyObject *old_key, *old_value;
1496 PyObject **value_addr;
1497
1498 if (!PyDict_Check(op)) {
1499 PyErr_BadInternalCall();
1500 return -1;
1501 }
1502 assert(key);
1503 assert(hash != -1);
1504 mp = (PyDictObject *)op;
Victor Stinner742da042016-09-07 17:40:12 -07001505 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1506 if (ix == DKIX_ERROR)
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001507 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07001508 if (ix == DKIX_EMPTY || *value_addr == NULL) {
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001509 _PyErr_SetKeyError(key);
1510 return -1;
1511 }
Victor Stinner742da042016-09-07 17:40:12 -07001512 assert(dk_get_index(mp->ma_keys, hashpos) == ix);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001513 old_value = *value_addr;
1514 *value_addr = NULL;
1515 mp->ma_used--;
Victor Stinner742da042016-09-07 17:40:12 -07001516 if (_PyDict_HasSplitTable(mp)) {
1517 mp->ma_keys->dk_usable = 0;
1518 }
1519 else {
1520 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1521 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001522 ENSURE_ALLOWS_DELETIONS(mp);
1523 old_key = ep->me_key;
Victor Stinner742da042016-09-07 17:40:12 -07001524 ep->me_key = NULL;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001525 Py_DECREF(old_key);
1526 }
1527 Py_DECREF(old_value);
1528 return 0;
1529}
1530
Guido van Rossum25831651993-05-19 14:50:45 +00001531void
Tim Peters1f5871e2000-07-04 17:44:48 +00001532PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 PyDictObject *mp;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001535 PyDictKeysObject *oldkeys;
1536 PyObject **oldvalues;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +00001538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 if (!PyDict_Check(op))
1540 return;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001541 mp = ((PyDictObject *)op);
1542 oldkeys = mp->ma_keys;
1543 oldvalues = mp->ma_values;
1544 if (oldvalues == empty_values)
1545 return;
1546 /* Empty the dict... */
1547 DK_INCREF(Py_EMPTY_KEYS);
1548 mp->ma_keys = Py_EMPTY_KEYS;
1549 mp->ma_values = empty_values;
1550 mp->ma_used = 0;
1551 /* ...then clear the keys and values */
1552 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001553 n = oldkeys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001554 for (i = 0; i < n; i++)
1555 Py_CLEAR(oldvalues[i]);
1556 free_values(oldvalues);
1557 DK_DECREF(oldkeys);
1558 }
1559 else {
1560 assert(oldkeys->dk_refcnt == 1);
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001561 DK_DECREF(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001562 }
1563}
1564
1565/* Returns -1 if no more items (or op is not a dict),
1566 * index of item otherwise. Stores value in pvalue
1567 */
Benjamin Peterson73222252016-09-08 09:58:47 -07001568static inline Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001569dict_next(PyObject *op, Py_ssize_t i, PyObject **pvalue)
1570{
Victor Stinner742da042016-09-07 17:40:12 -07001571 Py_ssize_t n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001572 PyDictObject *mp;
Victor Stinner742da042016-09-07 17:40:12 -07001573 PyObject **value_ptr = NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001574
1575 if (!PyDict_Check(op))
1576 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001578 if (i < 0)
1579 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07001580
1581 n = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001582 if (mp->ma_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001583 for (; i < n; i++) {
1584 value_ptr = &mp->ma_values[i];
1585 if (*value_ptr != NULL)
1586 break;
1587 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001589 else {
Victor Stinner742da042016-09-07 17:40:12 -07001590 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
1591 for (; i < n; i++) {
1592 value_ptr = &ep0[i].me_value;
1593 if (*value_ptr != NULL)
1594 break;
1595 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 }
Victor Stinner742da042016-09-07 17:40:12 -07001597 if (i >= n)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001598 return -1;
1599 if (pvalue)
1600 *pvalue = *value_ptr;
1601 return i;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001602}
1603
Tim Peters080c88b2003-02-15 03:01:11 +00001604/*
1605 * Iterate over a dict. Use like so:
1606 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001607 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +00001608 * PyObject *key, *value;
1609 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +00001610 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Tim Peters080c88b2003-02-15 03:01:11 +00001611 * Refer to borrowed references in key and value.
1612 * }
1613 *
1614 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +00001615 * mutates the dict. One exception: it is safe if the loop merely changes
1616 * the values associated with the keys (but doesn't insert new keys or
1617 * delete keys), via PyDict_SetItem().
1618 */
Guido van Rossum25831651993-05-19 14:50:45 +00001619int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001620PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001621{
Victor Stinner742da042016-09-07 17:40:12 -07001622 PyDictObject *mp = (PyDictObject*)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001623 Py_ssize_t i = dict_next(op, *ppos, pvalue);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 if (i < 0)
1625 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001626 mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 *ppos = i+1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 if (pkey)
Victor Stinner742da042016-09-07 17:40:12 -07001629 *pkey = DK_ENTRIES(mp->ma_keys)[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001631}
1632
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001633/* Internal version of PyDict_Next that returns a hash value in addition
1634 * to the key and value.
1635 */
Thomas Wouterscf297e42007-02-23 15:07:44 +00001636int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001637_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
1638 PyObject **pvalue, Py_hash_t *phash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001639{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001640 PyDictObject *mp;
Victor Stinner742da042016-09-07 17:40:12 -07001641 PyDictKeyEntry *ep0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001642 Py_ssize_t i = dict_next(op, *ppos, pvalue);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 if (i < 0)
1644 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001645 mp = (PyDictObject *)op;
Victor Stinner742da042016-09-07 17:40:12 -07001646 ep0 = DK_ENTRIES(mp->ma_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 *ppos = i+1;
Victor Stinner742da042016-09-07 17:40:12 -07001648 *phash = ep0[i].me_hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 if (pkey)
Victor Stinner742da042016-09-07 17:40:12 -07001650 *pkey = ep0[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 return 1;
Thomas Wouterscf297e42007-02-23 15:07:44 +00001652}
1653
Eric Snow96c6af92015-05-29 22:21:39 -06001654/* Internal version of dict.pop(). */
1655PyObject *
1656_PyDict_Pop(PyDictObject *mp, PyObject *key, PyObject *deflt)
1657{
1658 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001659 Py_ssize_t ix, hashpos;
Eric Snow96c6af92015-05-29 22:21:39 -06001660 PyObject *old_value, *old_key;
1661 PyDictKeyEntry *ep;
1662 PyObject **value_addr;
1663
1664 if (mp->ma_used == 0) {
1665 if (deflt) {
1666 Py_INCREF(deflt);
1667 return deflt;
1668 }
1669 _PyErr_SetKeyError(key);
1670 return NULL;
1671 }
1672 if (!PyUnicode_CheckExact(key) ||
1673 (hash = ((PyASCIIObject *) key)->hash) == -1) {
1674 hash = PyObject_Hash(key);
1675 if (hash == -1)
1676 return NULL;
1677 }
Victor Stinner742da042016-09-07 17:40:12 -07001678 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1679 if (ix == DKIX_ERROR)
Eric Snow96c6af92015-05-29 22:21:39 -06001680 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001681 if (ix == DKIX_EMPTY) {
Eric Snow96c6af92015-05-29 22:21:39 -06001682 if (deflt) {
1683 Py_INCREF(deflt);
1684 return deflt;
1685 }
1686 _PyErr_SetKeyError(key);
1687 return NULL;
1688 }
Victor Stinner742da042016-09-07 17:40:12 -07001689 old_value = *value_addr;
Eric Snow96c6af92015-05-29 22:21:39 -06001690 *value_addr = NULL;
1691 mp->ma_used--;
1692 if (!_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -07001693 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1694 ep = &DK_ENTRIES(mp->ma_keys)[ix];
Eric Snow96c6af92015-05-29 22:21:39 -06001695 ENSURE_ALLOWS_DELETIONS(mp);
1696 old_key = ep->me_key;
Victor Stinner742da042016-09-07 17:40:12 -07001697 ep->me_key = NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06001698 Py_DECREF(old_key);
1699 }
1700 return old_value;
1701}
1702
1703/* Internal version of dict.from_keys(). It is subclass-friendly. */
1704PyObject *
1705_PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
1706{
1707 PyObject *it; /* iter(iterable) */
1708 PyObject *key;
1709 PyObject *d;
1710 int status;
1711
1712 d = PyObject_CallObject(cls, NULL);
1713 if (d == NULL)
1714 return NULL;
1715
1716 if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
1717 if (PyDict_CheckExact(iterable)) {
1718 PyDictObject *mp = (PyDictObject *)d;
1719 PyObject *oldvalue;
1720 Py_ssize_t pos = 0;
1721 PyObject *key;
1722 Py_hash_t hash;
1723
Victor Stinner742da042016-09-07 17:40:12 -07001724 if (dictresize(mp, ESTIMATE_SIZE(Py_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001725 Py_DECREF(d);
1726 return NULL;
1727 }
1728
1729 while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
1730 if (insertdict(mp, key, hash, value)) {
1731 Py_DECREF(d);
1732 return NULL;
1733 }
1734 }
1735 return d;
1736 }
1737 if (PyAnySet_CheckExact(iterable)) {
1738 PyDictObject *mp = (PyDictObject *)d;
1739 Py_ssize_t pos = 0;
1740 PyObject *key;
1741 Py_hash_t hash;
1742
Victor Stinner742da042016-09-07 17:40:12 -07001743 if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001744 Py_DECREF(d);
1745 return NULL;
1746 }
1747
1748 while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
1749 if (insertdict(mp, key, hash, value)) {
1750 Py_DECREF(d);
1751 return NULL;
1752 }
1753 }
1754 return d;
1755 }
1756 }
1757
1758 it = PyObject_GetIter(iterable);
1759 if (it == NULL){
1760 Py_DECREF(d);
1761 return NULL;
1762 }
1763
1764 if (PyDict_CheckExact(d)) {
1765 while ((key = PyIter_Next(it)) != NULL) {
1766 status = PyDict_SetItem(d, key, value);
1767 Py_DECREF(key);
1768 if (status < 0)
1769 goto Fail;
1770 }
1771 } else {
1772 while ((key = PyIter_Next(it)) != NULL) {
1773 status = PyObject_SetItem(d, key, value);
1774 Py_DECREF(key);
1775 if (status < 0)
1776 goto Fail;
1777 }
1778 }
1779
1780 if (PyErr_Occurred())
1781 goto Fail;
1782 Py_DECREF(it);
1783 return d;
1784
1785Fail:
1786 Py_DECREF(it);
1787 Py_DECREF(d);
1788 return NULL;
1789}
1790
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001791/* Methods */
1792
1793static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001794dict_dealloc(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001795{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001796 PyObject **values = mp->ma_values;
1797 PyDictKeysObject *keys = mp->ma_keys;
1798 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 PyObject_GC_UnTrack(mp);
1800 Py_TRASHCAN_SAFE_BEGIN(mp)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001801 if (values != NULL) {
1802 if (values != empty_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001803 for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001804 Py_XDECREF(values[i]);
1805 }
1806 free_values(values);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001808 DK_DECREF(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 }
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02001810 else if (keys != NULL) {
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001811 assert(keys->dk_refcnt == 1);
1812 DK_DECREF(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001813 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
1815 free_list[numfree++] = mp;
1816 else
1817 Py_TYPE(mp)->tp_free((PyObject *)mp);
1818 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001819}
1820
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001821
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001822static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001823dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 Py_ssize_t i;
Victor Stinnerf91929b2013-11-19 13:07:38 +01001826 PyObject *key = NULL, *value = NULL;
1827 _PyUnicodeWriter writer;
1828 int first;
Guido van Rossum255443b1998-04-10 22:47:14 +00001829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 i = Py_ReprEnter((PyObject *)mp);
1831 if (i != 0) {
1832 return i > 0 ? PyUnicode_FromString("{...}") : NULL;
1833 }
Guido van Rossum255443b1998-04-10 22:47:14 +00001834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 if (mp->ma_used == 0) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01001836 Py_ReprLeave((PyObject *)mp);
1837 return PyUnicode_FromString("{}");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 }
Tim Petersa7259592001-06-16 05:11:17 +00001839
Victor Stinnerf91929b2013-11-19 13:07:38 +01001840 _PyUnicodeWriter_Init(&writer);
1841 writer.overallocate = 1;
1842 /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
1843 writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +00001844
Victor Stinnerf91929b2013-11-19 13:07:38 +01001845 if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
1846 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00001847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 /* Do repr() on each key+value pair, and insert ": " between them.
1849 Note that repr may mutate the dict. */
1850 i = 0;
Victor Stinnerf91929b2013-11-19 13:07:38 +01001851 first = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01001853 PyObject *s;
1854 int res;
1855
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001856 /* Prevent repr from deleting key or value during key format. */
1857 Py_INCREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 Py_INCREF(value);
Victor Stinnerf97dfd72013-07-18 01:00:45 +02001859
Victor Stinnerf91929b2013-11-19 13:07:38 +01001860 if (!first) {
1861 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
1862 goto error;
1863 }
1864 first = 0;
1865
1866 s = PyObject_Repr(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 if (s == NULL)
Victor Stinnerf91929b2013-11-19 13:07:38 +01001868 goto error;
1869 res = _PyUnicodeWriter_WriteStr(&writer, s);
1870 Py_DECREF(s);
1871 if (res < 0)
1872 goto error;
1873
1874 if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
1875 goto error;
1876
1877 s = PyObject_Repr(value);
1878 if (s == NULL)
1879 goto error;
1880 res = _PyUnicodeWriter_WriteStr(&writer, s);
1881 Py_DECREF(s);
1882 if (res < 0)
1883 goto error;
1884
1885 Py_CLEAR(key);
1886 Py_CLEAR(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 }
Tim Petersa7259592001-06-16 05:11:17 +00001888
Victor Stinnerf91929b2013-11-19 13:07:38 +01001889 writer.overallocate = 0;
1890 if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
1891 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 Py_ReprLeave((PyObject *)mp);
Victor Stinnerf91929b2013-11-19 13:07:38 +01001894
1895 return _PyUnicodeWriter_Finish(&writer);
1896
1897error:
1898 Py_ReprLeave((PyObject *)mp);
1899 _PyUnicodeWriter_Dealloc(&writer);
1900 Py_XDECREF(key);
1901 Py_XDECREF(value);
1902 return NULL;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001903}
1904
Martin v. Löwis18e16552006-02-15 17:27:45 +00001905static Py_ssize_t
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001906dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 return mp->ma_used;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001909}
1910
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001911static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001912dict_subscript(PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 PyObject *v;
Victor Stinner742da042016-09-07 17:40:12 -07001915 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001916 Py_hash_t hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001917 PyObject **value_addr;
1918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001920 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 hash = PyObject_Hash(key);
1922 if (hash == -1)
1923 return NULL;
1924 }
Victor Stinner742da042016-09-07 17:40:12 -07001925 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1926 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001928 if (ix == DKIX_EMPTY || *value_addr == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 if (!PyDict_CheckExact(mp)) {
1930 /* Look up __missing__ method if we're a subclass. */
1931 PyObject *missing, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05001932 _Py_IDENTIFIER(__missing__);
1933 missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 if (missing != NULL) {
1935 res = PyObject_CallFunctionObjArgs(missing,
1936 key, NULL);
1937 Py_DECREF(missing);
1938 return res;
1939 }
1940 else if (PyErr_Occurred())
1941 return NULL;
1942 }
Raymond Hettinger69492da2013-09-02 15:59:26 -07001943 _PyErr_SetKeyError(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 return NULL;
1945 }
Victor Stinner742da042016-09-07 17:40:12 -07001946 v = *value_addr;
1947 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001949}
1950
1951static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001952dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 if (w == NULL)
1955 return PyDict_DelItem((PyObject *)mp, v);
1956 else
1957 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001958}
1959
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001960static PyMappingMethods dict_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 (lenfunc)dict_length, /*mp_length*/
1962 (binaryfunc)dict_subscript, /*mp_subscript*/
1963 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001964};
1965
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001966static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001967dict_keys(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001968{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001969 PyObject *v;
1970 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001971 PyDictKeyEntry *ep;
1972 Py_ssize_t size, n, offset;
1973 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001974
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001975 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 n = mp->ma_used;
1977 v = PyList_New(n);
1978 if (v == NULL)
1979 return NULL;
1980 if (n != mp->ma_used) {
1981 /* Durnit. The allocations caused the dict to resize.
1982 * Just start over, this shouldn't normally happen.
1983 */
1984 Py_DECREF(v);
1985 goto again;
1986 }
Victor Stinner742da042016-09-07 17:40:12 -07001987 ep = DK_ENTRIES(mp->ma_keys);
1988 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001989 if (mp->ma_values) {
1990 value_ptr = mp->ma_values;
1991 offset = sizeof(PyObject *);
1992 }
1993 else {
1994 value_ptr = &ep[0].me_value;
1995 offset = sizeof(PyDictKeyEntry);
1996 }
1997 for (i = 0, j = 0; i < size; i++) {
1998 if (*value_ptr != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 PyObject *key = ep[i].me_key;
2000 Py_INCREF(key);
2001 PyList_SET_ITEM(v, j, key);
2002 j++;
2003 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002004 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 }
2006 assert(j == n);
2007 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002008}
2009
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002010static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002011dict_values(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002012{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002013 PyObject *v;
2014 Py_ssize_t i, j;
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002015 PyDictKeyEntry *ep;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002016 Py_ssize_t size, n, offset;
2017 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002018
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002019 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 n = mp->ma_used;
2021 v = PyList_New(n);
2022 if (v == NULL)
2023 return NULL;
2024 if (n != mp->ma_used) {
2025 /* Durnit. The allocations caused the dict to resize.
2026 * Just start over, this shouldn't normally happen.
2027 */
2028 Py_DECREF(v);
2029 goto again;
2030 }
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002031 ep = DK_ENTRIES(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002032 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002033 if (mp->ma_values) {
2034 value_ptr = mp->ma_values;
2035 offset = sizeof(PyObject *);
2036 }
2037 else {
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002038 value_ptr = &ep[0].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002039 offset = sizeof(PyDictKeyEntry);
2040 }
2041 for (i = 0, j = 0; i < size; i++) {
2042 PyObject *value = *value_ptr;
2043 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2044 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 Py_INCREF(value);
2046 PyList_SET_ITEM(v, j, value);
2047 j++;
2048 }
2049 }
2050 assert(j == n);
2051 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002052}
2053
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002054static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002055dict_items(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002056{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002057 PyObject *v;
2058 Py_ssize_t i, j, n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002059 Py_ssize_t size, offset;
2060 PyObject *item, *key;
2061 PyDictKeyEntry *ep;
2062 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 /* Preallocate the list of tuples, to avoid allocations during
2065 * the loop over the items, which could trigger GC, which
2066 * could resize the dict. :-(
2067 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002068 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 n = mp->ma_used;
2070 v = PyList_New(n);
2071 if (v == NULL)
2072 return NULL;
2073 for (i = 0; i < n; i++) {
2074 item = PyTuple_New(2);
2075 if (item == NULL) {
2076 Py_DECREF(v);
2077 return NULL;
2078 }
2079 PyList_SET_ITEM(v, i, item);
2080 }
2081 if (n != mp->ma_used) {
2082 /* Durnit. The allocations caused the dict to resize.
2083 * Just start over, this shouldn't normally happen.
2084 */
2085 Py_DECREF(v);
2086 goto again;
2087 }
2088 /* Nothing we do below makes any function calls. */
Victor Stinner742da042016-09-07 17:40:12 -07002089 ep = DK_ENTRIES(mp->ma_keys);
2090 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002091 if (mp->ma_values) {
2092 value_ptr = mp->ma_values;
2093 offset = sizeof(PyObject *);
2094 }
2095 else {
2096 value_ptr = &ep[0].me_value;
2097 offset = sizeof(PyDictKeyEntry);
2098 }
2099 for (i = 0, j = 0; i < size; i++) {
2100 PyObject *value = *value_ptr;
2101 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2102 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 key = ep[i].me_key;
2104 item = PyList_GET_ITEM(v, j);
2105 Py_INCREF(key);
2106 PyTuple_SET_ITEM(item, 0, key);
2107 Py_INCREF(value);
2108 PyTuple_SET_ITEM(item, 1, value);
2109 j++;
2110 }
2111 }
2112 assert(j == n);
2113 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002114}
2115
Larry Hastings5c661892014-01-24 06:17:25 -08002116/*[clinic input]
2117@classmethod
2118dict.fromkeys
Larry Hastings5c661892014-01-24 06:17:25 -08002119 iterable: object
2120 value: object=None
2121 /
2122
2123Returns a new dict with keys from iterable and values equal to value.
2124[clinic start generated code]*/
2125
Larry Hastings5c661892014-01-24 06:17:25 -08002126static PyObject *
2127dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002128/*[clinic end generated code: output=8fb98e4b10384999 input=b85a667f9bf4669d]*/
Larry Hastings5c661892014-01-24 06:17:25 -08002129{
Eric Snow96c6af92015-05-29 22:21:39 -06002130 return _PyDict_FromKeys((PyObject *)type, iterable, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002131}
2132
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002133static int
Victor Stinner742da042016-09-07 17:40:12 -07002134dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
2135 const char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 PyObject *arg = NULL;
2138 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
2141 result = -1;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 else if (arg != NULL) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02002144 _Py_IDENTIFIER(keys);
2145 if (_PyObject_HasAttrId(arg, &PyId_keys))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 result = PyDict_Merge(self, arg, 1);
2147 else
2148 result = PyDict_MergeFromSeq2(self, arg, 1);
2149 }
2150 if (result == 0 && kwds != NULL) {
2151 if (PyArg_ValidateKeywordArguments(kwds))
2152 result = PyDict_Merge(self, kwds, 1);
2153 else
2154 result = -1;
2155 }
2156 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002157}
2158
2159static PyObject *
2160dict_update(PyObject *self, PyObject *args, PyObject *kwds)
2161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 if (dict_update_common(self, args, kwds, "update") != -1)
2163 Py_RETURN_NONE;
2164 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002165}
2166
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002167/* Update unconditionally replaces existing items.
2168 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00002169 otherwise it leaves existing items unchanged.
2170
2171 PyDict_{Update,Merge} update/merge from a mapping object.
2172
Tim Petersf582b822001-12-11 18:51:08 +00002173 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00002174 producing iterable objects of length 2.
2175*/
2176
Tim Petersf582b822001-12-11 18:51:08 +00002177int
Tim Peters1fc240e2001-10-26 05:06:50 +00002178PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
2179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 PyObject *it; /* iter(seq2) */
2181 Py_ssize_t i; /* index into seq2 of current element */
2182 PyObject *item; /* seq2[i] */
2183 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00002184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 assert(d != NULL);
2186 assert(PyDict_Check(d));
2187 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 it = PyObject_GetIter(seq2);
2190 if (it == NULL)
2191 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 for (i = 0; ; ++i) {
2194 PyObject *key, *value;
2195 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 fast = NULL;
2198 item = PyIter_Next(it);
2199 if (item == NULL) {
2200 if (PyErr_Occurred())
2201 goto Fail;
2202 break;
2203 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 /* Convert item to sequence, and verify length 2. */
2206 fast = PySequence_Fast(item, "");
2207 if (fast == NULL) {
2208 if (PyErr_ExceptionMatches(PyExc_TypeError))
2209 PyErr_Format(PyExc_TypeError,
2210 "cannot convert dictionary update "
2211 "sequence element #%zd to a sequence",
2212 i);
2213 goto Fail;
2214 }
2215 n = PySequence_Fast_GET_SIZE(fast);
2216 if (n != 2) {
2217 PyErr_Format(PyExc_ValueError,
2218 "dictionary update sequence element #%zd "
2219 "has length %zd; 2 is required",
2220 i, n);
2221 goto Fail;
2222 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 /* Update/merge with this (key, value) pair. */
2225 key = PySequence_Fast_GET_ITEM(fast, 0);
2226 value = PySequence_Fast_GET_ITEM(fast, 1);
2227 if (override || PyDict_GetItem(d, key) == NULL) {
2228 int status = PyDict_SetItem(d, key, value);
2229 if (status < 0)
2230 goto Fail;
2231 }
2232 Py_DECREF(fast);
2233 Py_DECREF(item);
2234 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 i = 0;
2237 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00002238Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 Py_XDECREF(item);
2240 Py_XDECREF(fast);
2241 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002242Return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 Py_DECREF(it);
2244 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00002245}
2246
Tim Peters6d6c1a32001-08-02 04:15:00 +00002247int
2248PyDict_Update(PyObject *a, PyObject *b)
2249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 return PyDict_Merge(a, b, 1);
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002251}
2252
2253int
2254PyDict_Merge(PyObject *a, PyObject *b, int override)
2255{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002256 PyDictObject *mp, *other;
2257 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -07002258 PyDictKeyEntry *entry, *ep0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 /* We accept for the argument either a concrete dictionary object,
2261 * or an abstract "mapping" object. For the former, we can do
2262 * things quite efficiently. For the latter, we only require that
2263 * PyMapping_Keys() and PyObject_GetItem() be supported.
2264 */
2265 if (a == NULL || !PyDict_Check(a) || b == NULL) {
2266 PyErr_BadInternalCall();
2267 return -1;
2268 }
2269 mp = (PyDictObject*)a;
2270 if (PyDict_Check(b)) {
2271 other = (PyDictObject*)b;
2272 if (other == mp || other->ma_used == 0)
2273 /* a.update(a) or a.update({}); nothing to do */
2274 return 0;
2275 if (mp->ma_used == 0)
2276 /* Since the target dict is empty, PyDict_GetItem()
2277 * always returns NULL. Setting override to 1
2278 * skips the unnecessary test.
2279 */
2280 override = 1;
2281 /* Do one big resize at the start, rather than
2282 * incrementally resizing as we insert new items. Expect
2283 * that there will be no (or few) overlapping keys.
2284 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002285 if (mp->ma_keys->dk_usable * 3 < other->ma_used * 2)
2286 if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07002288 ep0 = DK_ENTRIES(other->ma_keys);
2289 for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002290 PyObject *key, *value;
2291 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002292 entry = &ep0[i];
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002293 key = entry->me_key;
2294 hash = entry->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002295 if (other->ma_values)
2296 value = other->ma_values[i];
2297 else
2298 value = entry->me_value;
2299
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002300 if (value != NULL) {
2301 int err = 0;
2302 Py_INCREF(key);
2303 Py_INCREF(value);
2304 if (override || PyDict_GetItem(a, key) == NULL)
2305 err = insertdict(mp, key, hash, value);
2306 Py_DECREF(value);
2307 Py_DECREF(key);
2308 if (err != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 return -1;
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002310
Victor Stinner742da042016-09-07 17:40:12 -07002311 if (n != other->ma_keys->dk_nentries) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002312 PyErr_SetString(PyExc_RuntimeError,
2313 "dict mutated during update");
2314 return -1;
2315 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 }
2317 }
2318 }
2319 else {
2320 /* Do it the generic, slower way */
2321 PyObject *keys = PyMapping_Keys(b);
2322 PyObject *iter;
2323 PyObject *key, *value;
2324 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 if (keys == NULL)
2327 /* Docstring says this is equivalent to E.keys() so
2328 * if E doesn't have a .keys() method we want
2329 * AttributeError to percolate up. Might as well
2330 * do the same for any other error.
2331 */
2332 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 iter = PyObject_GetIter(keys);
2335 Py_DECREF(keys);
2336 if (iter == NULL)
2337 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
2340 if (!override && PyDict_GetItem(a, key) != NULL) {
2341 Py_DECREF(key);
2342 continue;
2343 }
2344 value = PyObject_GetItem(b, key);
2345 if (value == NULL) {
2346 Py_DECREF(iter);
2347 Py_DECREF(key);
2348 return -1;
2349 }
2350 status = PyDict_SetItem(a, key, value);
2351 Py_DECREF(key);
2352 Py_DECREF(value);
2353 if (status < 0) {
2354 Py_DECREF(iter);
2355 return -1;
2356 }
2357 }
2358 Py_DECREF(iter);
2359 if (PyErr_Occurred())
2360 /* Iterator completed, via error */
2361 return -1;
2362 }
2363 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002364}
2365
2366static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002367dict_copy(PyDictObject *mp)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002370}
2371
2372PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002373PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 PyObject *copy;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002376 PyDictObject *mp;
2377 Py_ssize_t i, n;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 if (o == NULL || !PyDict_Check(o)) {
2380 PyErr_BadInternalCall();
2381 return NULL;
2382 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002383 mp = (PyDictObject *)o;
2384 if (_PyDict_HasSplitTable(mp)) {
2385 PyDictObject *split_copy;
Victor Stinner742da042016-09-07 17:40:12 -07002386 Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
2387 PyObject **newvalues;
2388 newvalues = new_values(size);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002389 if (newvalues == NULL)
2390 return PyErr_NoMemory();
2391 split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
2392 if (split_copy == NULL) {
2393 free_values(newvalues);
2394 return NULL;
2395 }
2396 split_copy->ma_values = newvalues;
2397 split_copy->ma_keys = mp->ma_keys;
2398 split_copy->ma_used = mp->ma_used;
2399 DK_INCREF(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002400 for (i = 0, n = size; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002401 PyObject *value = mp->ma_values[i];
2402 Py_XINCREF(value);
2403 split_copy->ma_values[i] = value;
2404 }
Benjamin Peterson7ce67e42012-04-24 10:32:57 -04002405 if (_PyObject_GC_IS_TRACKED(mp))
2406 _PyObject_GC_TRACK(split_copy);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002407 return (PyObject *)split_copy;
2408 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 copy = PyDict_New();
2410 if (copy == NULL)
2411 return NULL;
2412 if (PyDict_Merge(copy, o, 1) == 0)
2413 return copy;
2414 Py_DECREF(copy);
2415 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002416}
2417
Martin v. Löwis18e16552006-02-15 17:27:45 +00002418Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00002419PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00002420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 if (mp == NULL || !PyDict_Check(mp)) {
2422 PyErr_BadInternalCall();
2423 return -1;
2424 }
2425 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00002426}
2427
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002428PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002429PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 if (mp == NULL || !PyDict_Check(mp)) {
2432 PyErr_BadInternalCall();
2433 return NULL;
2434 }
2435 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002436}
2437
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002438PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002439PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 if (mp == NULL || !PyDict_Check(mp)) {
2442 PyErr_BadInternalCall();
2443 return NULL;
2444 }
2445 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002446}
2447
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002448PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002449PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 if (mp == NULL || !PyDict_Check(mp)) {
2452 PyErr_BadInternalCall();
2453 return NULL;
2454 }
2455 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002456}
2457
Tim Peterse63415e2001-05-08 04:38:29 +00002458/* Return 1 if dicts equal, 0 if not, -1 if error.
2459 * Gets out as soon as any difference is detected.
2460 * Uses only Py_EQ comparison.
2461 */
2462static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002463dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00002464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00002466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 if (a->ma_used != b->ma_used)
2468 /* can't be equal if # of entries differ */
2469 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Victor Stinner742da042016-09-07 17:40:12 -07002471 for (i = 0; i < a->ma_keys->dk_nentries; i++) {
2472 PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002473 PyObject *aval;
2474 if (a->ma_values)
2475 aval = a->ma_values[i];
2476 else
2477 aval = ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 if (aval != NULL) {
2479 int cmp;
2480 PyObject *bval;
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002481 PyObject **vaddr;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002482 PyObject *key = ep->me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 /* temporarily bump aval's refcount to ensure it stays
2484 alive until we're done with it */
2485 Py_INCREF(aval);
2486 /* ditto for key */
2487 Py_INCREF(key);
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002488 /* reuse the known hash value */
Victor Stinner742da042016-09-07 17:40:12 -07002489 if ((b->ma_keys->dk_lookup)(b, key, ep->me_hash, &vaddr, NULL) < 0)
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002490 bval = NULL;
2491 else
2492 bval = *vaddr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 Py_DECREF(key);
2494 if (bval == NULL) {
2495 Py_DECREF(aval);
2496 if (PyErr_Occurred())
2497 return -1;
2498 return 0;
2499 }
2500 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
2501 Py_DECREF(aval);
2502 if (cmp <= 0) /* error or not equal */
2503 return cmp;
2504 }
2505 }
2506 return 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002507}
Tim Peterse63415e2001-05-08 04:38:29 +00002508
2509static PyObject *
2510dict_richcompare(PyObject *v, PyObject *w, int op)
2511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 int cmp;
2513 PyObject *res;
Tim Peterse63415e2001-05-08 04:38:29 +00002514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 if (!PyDict_Check(v) || !PyDict_Check(w)) {
2516 res = Py_NotImplemented;
2517 }
2518 else if (op == Py_EQ || op == Py_NE) {
2519 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
2520 if (cmp < 0)
2521 return NULL;
2522 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
2523 }
2524 else
2525 res = Py_NotImplemented;
2526 Py_INCREF(res);
2527 return res;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002528}
Tim Peterse63415e2001-05-08 04:38:29 +00002529
Larry Hastings61272b72014-01-07 12:41:53 -08002530/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002531
2532@coexist
2533dict.__contains__
2534
2535 key: object
2536 /
2537
Meador Ingee02de8c2014-01-14 16:48:31 -06002538True if D has a key k, else False.
Larry Hastings61272b72014-01-07 12:41:53 -08002539[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002540
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002541static PyObject *
Larry Hastingsc2047262014-01-25 20:43:29 -08002542dict___contains__(PyDictObject *self, PyObject *key)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002543/*[clinic end generated code: output=a3d03db709ed6e6b input=b852b2a19b51ab24]*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002544{
Larry Hastingsc2047262014-01-25 20:43:29 -08002545 register PyDictObject *mp = self;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002546 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002547 Py_ssize_t ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002548 PyObject **value_addr;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002551 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 hash = PyObject_Hash(key);
2553 if (hash == -1)
2554 return NULL;
2555 }
Victor Stinner742da042016-09-07 17:40:12 -07002556 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2557 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002559 if (ix == DKIX_EMPTY || *value_addr == NULL)
2560 Py_RETURN_FALSE;
2561 Py_RETURN_TRUE;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002562}
2563
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002564static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002565dict_get(PyDictObject *mp, PyObject *args)
Barry Warsawc38c5da1997-10-06 17:49:20 +00002566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 PyObject *key;
2568 PyObject *failobj = Py_None;
2569 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002570 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002571 Py_ssize_t ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002572 PyObject **value_addr;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
2575 return NULL;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002578 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 hash = PyObject_Hash(key);
2580 if (hash == -1)
2581 return NULL;
2582 }
Victor Stinner742da042016-09-07 17:40:12 -07002583 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2584 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002586 if (ix == DKIX_EMPTY || *value_addr == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 val = failobj;
Victor Stinner742da042016-09-07 17:40:12 -07002588 else
2589 val = *value_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 Py_INCREF(val);
2591 return val;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002592}
2593
Benjamin Peterson00e98862013-03-07 22:16:29 -05002594PyObject *
2595PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
Guido van Rossum164452c2000-08-08 16:12:54 +00002596{
Benjamin Peterson00e98862013-03-07 22:16:29 -05002597 PyDictObject *mp = (PyDictObject *)d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002599 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002600 Py_ssize_t hashpos, ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002601 PyDictKeyEntry *ep;
2602 PyObject **value_addr;
Guido van Rossum164452c2000-08-08 16:12:54 +00002603
Benjamin Peterson00e98862013-03-07 22:16:29 -05002604 if (!PyDict_Check(d)) {
2605 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 return NULL;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002607 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002609 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 hash = PyObject_Hash(key);
2611 if (hash == -1)
2612 return NULL;
2613 }
Victor Stinner742da042016-09-07 17:40:12 -07002614 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
2615 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002617 if (ix == DKIX_EMPTY || *value_addr == NULL) {
2618 val = defaultobj;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002619 if (mp->ma_keys->dk_usable <= 0) {
2620 /* Need to resize. */
2621 if (insertion_resize(mp) < 0)
2622 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002623 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002624 }
Victor Stinner742da042016-09-07 17:40:12 -07002625 ix = mp->ma_keys->dk_nentries;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002626 Py_INCREF(defaultobj);
Benjamin Petersonb1efa532013-03-04 09:47:50 -05002627 Py_INCREF(key);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002628 MAINTAIN_TRACKING(mp, key, defaultobj);
Victor Stinner742da042016-09-07 17:40:12 -07002629 dk_set_index(mp->ma_keys, hashpos, ix);
2630 ep = &DK_ENTRIES(mp->ma_keys)[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002631 ep->me_key = key;
2632 ep->me_hash = hash;
Victor Stinner742da042016-09-07 17:40:12 -07002633 if (mp->ma_values) {
2634 mp->ma_values[ix] = val;
2635 }
2636 else {
2637 ep->me_value = val;
2638 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002639 mp->ma_keys->dk_usable--;
Victor Stinner742da042016-09-07 17:40:12 -07002640 mp->ma_keys->dk_nentries++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002641 mp->ma_used++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 }
Victor Stinner742da042016-09-07 17:40:12 -07002643 else
2644 val = *value_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 return val;
Guido van Rossum164452c2000-08-08 16:12:54 +00002646}
2647
Benjamin Peterson00e98862013-03-07 22:16:29 -05002648static PyObject *
2649dict_setdefault(PyDictObject *mp, PyObject *args)
2650{
2651 PyObject *key, *val;
2652 PyObject *defaultobj = Py_None;
2653
2654 if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &defaultobj))
2655 return NULL;
2656
Benjamin Peterson55898502013-03-08 08:36:49 -05002657 val = PyDict_SetDefault((PyObject *)mp, key, defaultobj);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002658 Py_XINCREF(val);
2659 return val;
2660}
Guido van Rossum164452c2000-08-08 16:12:54 +00002661
2662static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002663dict_clear(PyDictObject *mp)
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 PyDict_Clear((PyObject *)mp);
2666 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002667}
2668
Guido van Rossumba6ab842000-12-12 22:02:18 +00002669static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002670dict_pop(PyDictObject *mp, PyObject *args)
Guido van Rossume027d982002-04-12 15:11:59 +00002671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 PyObject *key, *deflt = NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00002673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
2675 return NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06002676
2677 return _PyDict_Pop(mp, key, deflt);
Guido van Rossume027d982002-04-12 15:11:59 +00002678}
2679
2680static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002681dict_popitem(PyDictObject *mp)
Guido van Rossumba6ab842000-12-12 22:02:18 +00002682{
Victor Stinner742da042016-09-07 17:40:12 -07002683 Py_ssize_t i, j;
2684 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 PyObject *res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 /* Allocate the result tuple before checking the size. Believe it
2688 * or not, this allocation could trigger a garbage collection which
2689 * could empty the dict, so if we checked the size first and that
2690 * happened, the result would be an infinite loop (searching for an
2691 * entry that no longer exists). Note that the usual popitem()
2692 * idiom is "while d: k, v = d.popitem()". so needing to throw the
2693 * tuple away if the dict *is* empty isn't a significant
2694 * inefficiency -- possible, but unlikely in practice.
2695 */
2696 res = PyTuple_New(2);
2697 if (res == NULL)
2698 return NULL;
2699 if (mp->ma_used == 0) {
2700 Py_DECREF(res);
2701 PyErr_SetString(PyExc_KeyError,
2702 "popitem(): dictionary is empty");
2703 return NULL;
2704 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002705 /* Convert split table to combined table */
2706 if (mp->ma_keys->dk_lookup == lookdict_split) {
2707 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
2708 Py_DECREF(res);
2709 return NULL;
2710 }
2711 }
2712 ENSURE_ALLOWS_DELETIONS(mp);
Victor Stinner742da042016-09-07 17:40:12 -07002713
2714 /* Pop last item */
2715 ep0 = DK_ENTRIES(mp->ma_keys);
2716 i = mp->ma_keys->dk_nentries - 1;
2717 while (i >= 0 && ep0[i].me_value == NULL) {
2718 i--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 }
Victor Stinner742da042016-09-07 17:40:12 -07002720 assert(i >= 0);
2721
2722 ep = &ep0[i];
2723 j = lookdict_index(mp->ma_keys, ep->me_hash, i);
2724 assert(j >= 0);
2725 assert(dk_get_index(mp->ma_keys, j) == i);
2726 dk_set_index(mp->ma_keys, j, DKIX_DUMMY);
2727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 PyTuple_SET_ITEM(res, 0, ep->me_key);
2729 PyTuple_SET_ITEM(res, 1, ep->me_value);
Victor Stinner742da042016-09-07 17:40:12 -07002730 ep->me_key = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 ep->me_value = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002732 /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
2733 mp->ma_keys->dk_nentries = i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 mp->ma_used--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 return res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002736}
2737
Jeremy Hylton8caad492000-06-23 14:18:11 +00002738static int
2739dict_traverse(PyObject *op, visitproc visit, void *arg)
2740{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002741 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson55f44522016-09-05 12:12:59 -07002742 PyDictKeysObject *keys = mp->ma_keys;
Victor Stinner742da042016-09-07 17:40:12 -07002743 PyDictKeyEntry *entries = DK_ENTRIES(mp->ma_keys);
2744 Py_ssize_t i, n = keys->dk_nentries;
2745
Benjamin Peterson55f44522016-09-05 12:12:59 -07002746 if (keys->dk_lookup == lookdict) {
2747 for (i = 0; i < n; i++) {
2748 if (entries[i].me_value != NULL) {
2749 Py_VISIT(entries[i].me_value);
2750 Py_VISIT(entries[i].me_key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002751 }
2752 }
Victor Stinner742da042016-09-07 17:40:12 -07002753 }
2754 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002755 if (mp->ma_values != NULL) {
Benjamin Peterson55f44522016-09-05 12:12:59 -07002756 for (i = 0; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002757 Py_VISIT(mp->ma_values[i]);
2758 }
2759 }
2760 else {
Benjamin Peterson55f44522016-09-05 12:12:59 -07002761 for (i = 0; i < n; i++) {
2762 Py_VISIT(entries[i].me_value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002763 }
2764 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 }
2766 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002767}
2768
2769static int
2770dict_tp_clear(PyObject *op)
2771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 PyDict_Clear(op);
2773 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002774}
2775
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002776static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00002777
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002778Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06002779_PyDict_SizeOf(PyDictObject *mp)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002780{
Victor Stinner742da042016-09-07 17:40:12 -07002781 Py_ssize_t size, usable, res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002782
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002783 size = DK_SIZE(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002784 usable = USABLE_FRACTION(size);
2785
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002786 res = _PyObject_SIZE(Py_TYPE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002787 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07002788 res += usable * sizeof(PyObject*);
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002789 /* If the dictionary is split, the keys portion is accounted-for
2790 in the type object. */
2791 if (mp->ma_keys->dk_refcnt == 1)
Victor Stinner98ee9d52016-09-08 09:33:56 -07002792 res += (sizeof(PyDictKeysObject)
2793 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
2794 + DK_IXSIZE(mp->ma_keys) * size
2795 + sizeof(PyDictKeyEntry) * usable);
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002796 return res;
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002797}
2798
2799Py_ssize_t
2800_PyDict_KeysSize(PyDictKeysObject *keys)
2801{
Victor Stinner98ee9d52016-09-08 09:33:56 -07002802 return (sizeof(PyDictKeysObject)
2803 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
2804 + DK_IXSIZE(keys) * DK_SIZE(keys)
2805 + USABLE_FRACTION(DK_SIZE(keys)) * sizeof(PyDictKeyEntry));
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002806}
2807
doko@ubuntu.com17210f52016-01-14 14:04:59 +01002808static PyObject *
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002809dict_sizeof(PyDictObject *mp)
2810{
2811 return PyLong_FromSsize_t(_PyDict_SizeOf(mp));
2812}
2813
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002814PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
2815
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002816PyDoc_STRVAR(sizeof__doc__,
2817"D.__sizeof__() -> size of D in memory, in bytes");
2818
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002819PyDoc_STRVAR(get__doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00002820"D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002821
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002822PyDoc_STRVAR(setdefault_doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00002823"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 +00002824
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002825PyDoc_STRVAR(pop__doc__,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002826"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00002827If key is not found, d is returned if given, otherwise KeyError is raised");
Guido van Rossume027d982002-04-12 15:11:59 +00002828
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002829PyDoc_STRVAR(popitem__doc__,
Tim Petersf7f88b12000-12-13 23:18:45 +00002830"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000028312-tuple; but raise KeyError if D is empty.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002832
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002833PyDoc_STRVAR(update__doc__,
Brett Cannonf2754162013-05-11 14:46:48 -04002834"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n\
2835If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]\n\
2836If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n\
2837In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00002838
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002839PyDoc_STRVAR(clear__doc__,
2840"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002841
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002842PyDoc_STRVAR(copy__doc__,
2843"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00002844
Guido van Rossumb90c8482007-02-10 01:11:45 +00002845/* Forward */
2846static PyObject *dictkeys_new(PyObject *);
2847static PyObject *dictitems_new(PyObject *);
2848static PyObject *dictvalues_new(PyObject *);
2849
Guido van Rossum45c85d12007-07-27 16:31:40 +00002850PyDoc_STRVAR(keys__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 "D.keys() -> a set-like object providing a view on D's keys");
Guido van Rossum45c85d12007-07-27 16:31:40 +00002852PyDoc_STRVAR(items__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 "D.items() -> a set-like object providing a view on D's items");
Guido van Rossum45c85d12007-07-27 16:31:40 +00002854PyDoc_STRVAR(values__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 "D.values() -> an object providing a view on D's values");
Guido van Rossumb90c8482007-02-10 01:11:45 +00002856
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002857static PyMethodDef mapp_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -07002858 DICT___CONTAINS___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
2860 getitem__doc__},
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002861 {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 sizeof__doc__},
2863 {"get", (PyCFunction)dict_get, METH_VARARGS,
2864 get__doc__},
2865 {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS,
2866 setdefault_doc__},
2867 {"pop", (PyCFunction)dict_pop, METH_VARARGS,
2868 pop__doc__},
2869 {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
2870 popitem__doc__},
2871 {"keys", (PyCFunction)dictkeys_new, METH_NOARGS,
2872 keys__doc__},
2873 {"items", (PyCFunction)dictitems_new, METH_NOARGS,
2874 items__doc__},
2875 {"values", (PyCFunction)dictvalues_new, METH_NOARGS,
2876 values__doc__},
2877 {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
2878 update__doc__},
Larry Hastings5c661892014-01-24 06:17:25 -08002879 DICT_FROMKEYS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
2881 clear__doc__},
2882 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
2883 copy__doc__},
2884 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002885};
2886
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002887/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00002888int
2889PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002890{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002891 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002892 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002894 PyObject **value_addr;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002897 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 hash = PyObject_Hash(key);
2899 if (hash == -1)
2900 return -1;
2901 }
Victor Stinner742da042016-09-07 17:40:12 -07002902 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2903 if (ix == DKIX_ERROR)
2904 return -1;
2905 return (ix != DKIX_EMPTY && *value_addr != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002906}
2907
Thomas Wouterscf297e42007-02-23 15:07:44 +00002908/* Internal version of PyDict_Contains used when the hash value is already known */
2909int
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002910_PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00002911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002913 PyObject **value_addr;
Victor Stinner742da042016-09-07 17:40:12 -07002914 Py_ssize_t ix;
Thomas Wouterscf297e42007-02-23 15:07:44 +00002915
Victor Stinner742da042016-09-07 17:40:12 -07002916 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2917 if (ix == DKIX_ERROR)
2918 return -1;
2919 return (ix != DKIX_EMPTY && *value_addr != NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00002920}
2921
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002922/* Hack to implement "key in dict" */
2923static PySequenceMethods dict_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 0, /* sq_length */
2925 0, /* sq_concat */
2926 0, /* sq_repeat */
2927 0, /* sq_item */
2928 0, /* sq_slice */
2929 0, /* sq_ass_item */
2930 0, /* sq_ass_slice */
2931 PyDict_Contains, /* sq_contains */
2932 0, /* sq_inplace_concat */
2933 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002934};
2935
Guido van Rossum09e563a2001-05-01 12:10:21 +00002936static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002937dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 PyObject *self;
Victor Stinnera9f61a52013-07-16 22:17:26 +02002940 PyDictObject *d;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 assert(type != NULL && type->tp_alloc != NULL);
2943 self = type->tp_alloc(type, 0);
Victor Stinnera9f61a52013-07-16 22:17:26 +02002944 if (self == NULL)
2945 return NULL;
Victor Stinnera9f61a52013-07-16 22:17:26 +02002946 d = (PyDictObject *)self;
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02002947
Victor Stinnera9f61a52013-07-16 22:17:26 +02002948 /* The object has been implicitly tracked by tp_alloc */
2949 if (type == &PyDict_Type)
2950 _PyObject_GC_UNTRACK(d);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02002951
2952 d->ma_used = 0;
Victor Stinner742da042016-09-07 17:40:12 -07002953 d->ma_keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02002954 if (d->ma_keys == NULL) {
2955 Py_DECREF(self);
2956 return NULL;
2957 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 return self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002959}
2960
Tim Peters25786c02001-09-02 08:22:48 +00002961static int
2962dict_init(PyObject *self, PyObject *args, PyObject *kwds)
2963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00002965}
2966
Tim Peters6d6c1a32001-08-02 04:15:00 +00002967static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002968dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00002969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00002971}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002972
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002973PyDoc_STRVAR(dictionary_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00002974"dict() -> new empty dictionary\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00002975"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00002976" (key, value) pairs\n"
2977"dict(iterable) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00002978" d = {}\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00002979" for k, v in iterable:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00002980" d[k] = v\n"
2981"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
2982" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00002983
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002984PyTypeObject PyDict_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2986 "dict",
2987 sizeof(PyDictObject),
2988 0,
2989 (destructor)dict_dealloc, /* tp_dealloc */
2990 0, /* tp_print */
2991 0, /* tp_getattr */
2992 0, /* tp_setattr */
2993 0, /* tp_reserved */
2994 (reprfunc)dict_repr, /* tp_repr */
2995 0, /* tp_as_number */
2996 &dict_as_sequence, /* tp_as_sequence */
2997 &dict_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00002998 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 0, /* tp_call */
3000 0, /* tp_str */
3001 PyObject_GenericGetAttr, /* tp_getattro */
3002 0, /* tp_setattro */
3003 0, /* tp_as_buffer */
3004 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3005 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
3006 dictionary_doc, /* tp_doc */
3007 dict_traverse, /* tp_traverse */
3008 dict_tp_clear, /* tp_clear */
3009 dict_richcompare, /* tp_richcompare */
3010 0, /* tp_weaklistoffset */
3011 (getiterfunc)dict_iter, /* tp_iter */
3012 0, /* tp_iternext */
3013 mapp_methods, /* tp_methods */
3014 0, /* tp_members */
3015 0, /* tp_getset */
3016 0, /* tp_base */
3017 0, /* tp_dict */
3018 0, /* tp_descr_get */
3019 0, /* tp_descr_set */
3020 0, /* tp_dictoffset */
3021 dict_init, /* tp_init */
3022 PyType_GenericAlloc, /* tp_alloc */
3023 dict_new, /* tp_new */
3024 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003025};
3026
Victor Stinner3c1e4812012-03-26 22:10:51 +02003027PyObject *
3028_PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
3029{
3030 PyObject *kv;
3031 kv = _PyUnicode_FromId(key); /* borrowed */
Victor Stinner5b3b1002013-07-22 23:50:57 +02003032 if (kv == NULL) {
3033 PyErr_Clear();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003034 return NULL;
Victor Stinner5b3b1002013-07-22 23:50:57 +02003035 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003036 return PyDict_GetItem(dp, kv);
3037}
3038
Guido van Rossum3cca2451997-05-16 14:23:33 +00003039/* For backward compatibility with old dictionary interface */
3040
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003041PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003042PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 PyObject *kv, *rv;
3045 kv = PyUnicode_FromString(key);
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003046 if (kv == NULL) {
3047 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 return NULL;
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003049 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 rv = PyDict_GetItem(v, kv);
3051 Py_DECREF(kv);
3052 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003053}
3054
3055int
Victor Stinner3c1e4812012-03-26 22:10:51 +02003056_PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
3057{
3058 PyObject *kv;
3059 kv = _PyUnicode_FromId(key); /* borrowed */
3060 if (kv == NULL)
3061 return -1;
3062 return PyDict_SetItem(v, kv, item);
3063}
3064
3065int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003066PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 PyObject *kv;
3069 int err;
3070 kv = PyUnicode_FromString(key);
3071 if (kv == NULL)
3072 return -1;
3073 PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
3074 err = PyDict_SetItem(v, kv, item);
3075 Py_DECREF(kv);
3076 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003077}
3078
3079int
Victor Stinner5fd2e5a2013-11-06 18:58:22 +01003080_PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
3081{
3082 PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
3083 if (kv == NULL)
3084 return -1;
3085 return PyDict_DelItem(v, kv);
3086}
3087
3088int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003089PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 PyObject *kv;
3092 int err;
3093 kv = PyUnicode_FromString(key);
3094 if (kv == NULL)
3095 return -1;
3096 err = PyDict_DelItem(v, kv);
3097 Py_DECREF(kv);
3098 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003099}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003100
Raymond Hettinger019a1482004-03-18 02:41:19 +00003101/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003102
3103typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 PyObject_HEAD
3105 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
3106 Py_ssize_t di_used;
3107 Py_ssize_t di_pos;
3108 PyObject* di_result; /* reusable result tuple for iteritems */
3109 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003110} dictiterobject;
3111
3112static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003113dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 dictiterobject *di;
3116 di = PyObject_GC_New(dictiterobject, itertype);
3117 if (di == NULL)
3118 return NULL;
3119 Py_INCREF(dict);
3120 di->di_dict = dict;
3121 di->di_used = dict->ma_used;
3122 di->di_pos = 0;
3123 di->len = dict->ma_used;
3124 if (itertype == &PyDictIterItem_Type) {
3125 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
3126 if (di->di_result == NULL) {
3127 Py_DECREF(di);
3128 return NULL;
3129 }
3130 }
3131 else
3132 di->di_result = NULL;
3133 _PyObject_GC_TRACK(di);
3134 return (PyObject *)di;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003135}
3136
3137static void
3138dictiter_dealloc(dictiterobject *di)
3139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 Py_XDECREF(di->di_dict);
3141 Py_XDECREF(di->di_result);
3142 PyObject_GC_Del(di);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003143}
3144
3145static int
3146dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
3147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 Py_VISIT(di->di_dict);
3149 Py_VISIT(di->di_result);
3150 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003151}
3152
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003153static PyObject *
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003154dictiter_len(dictiterobject *di)
3155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 Py_ssize_t len = 0;
3157 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
3158 len = di->len;
3159 return PyLong_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003160}
3161
Guido van Rossumb90c8482007-02-10 01:11:45 +00003162PyDoc_STRVAR(length_hint_doc,
3163 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003164
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003165static PyObject *
3166dictiter_reduce(dictiterobject *di);
3167
3168PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3169
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003170static PyMethodDef dictiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS,
3172 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003173 {"__reduce__", (PyCFunction)dictiter_reduce, METH_NOARGS,
3174 reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003176};
3177
Raymond Hettinger019a1482004-03-18 02:41:19 +00003178static PyObject *dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00003179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 PyObject *key;
Victor Stinner742da042016-09-07 17:40:12 -07003181 Py_ssize_t i, n, offset;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003182 PyDictKeysObject *k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003184 PyObject **value_ptr;
Guido van Rossum213c7a62001-04-23 14:08:49 +00003185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 if (d == NULL)
3187 return NULL;
3188 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00003189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 if (di->di_used != d->ma_used) {
3191 PyErr_SetString(PyExc_RuntimeError,
3192 "dictionary changed size during iteration");
3193 di->di_used = -1; /* Make this state sticky */
3194 return NULL;
3195 }
Guido van Rossum2147df72002-07-16 20:30:22 +00003196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 i = di->di_pos;
3198 if (i < 0)
3199 goto fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003200 k = d->ma_keys;
3201 if (d->ma_values) {
3202 value_ptr = &d->ma_values[i];
3203 offset = sizeof(PyObject *);
3204 }
3205 else {
Victor Stinner742da042016-09-07 17:40:12 -07003206 value_ptr = &DK_ENTRIES(k)[i].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003207 offset = sizeof(PyDictKeyEntry);
3208 }
Victor Stinner742da042016-09-07 17:40:12 -07003209 n = k->dk_nentries - 1;
3210 while (i <= n && *value_ptr == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003211 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 i++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003213 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 di->di_pos = i+1;
Victor Stinner742da042016-09-07 17:40:12 -07003215 if (i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 goto fail;
3217 di->len--;
Victor Stinner742da042016-09-07 17:40:12 -07003218 key = DK_ENTRIES(k)[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 Py_INCREF(key);
3220 return key;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003221
3222fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003224 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003226}
3227
Raymond Hettinger019a1482004-03-18 02:41:19 +00003228PyTypeObject PyDictIterKey_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3230 "dict_keyiterator", /* tp_name */
3231 sizeof(dictiterobject), /* tp_basicsize */
3232 0, /* tp_itemsize */
3233 /* methods */
3234 (destructor)dictiter_dealloc, /* tp_dealloc */
3235 0, /* tp_print */
3236 0, /* tp_getattr */
3237 0, /* tp_setattr */
3238 0, /* tp_reserved */
3239 0, /* tp_repr */
3240 0, /* tp_as_number */
3241 0, /* tp_as_sequence */
3242 0, /* tp_as_mapping */
3243 0, /* tp_hash */
3244 0, /* tp_call */
3245 0, /* tp_str */
3246 PyObject_GenericGetAttr, /* tp_getattro */
3247 0, /* tp_setattro */
3248 0, /* tp_as_buffer */
3249 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3250 0, /* tp_doc */
3251 (traverseproc)dictiter_traverse, /* tp_traverse */
3252 0, /* tp_clear */
3253 0, /* tp_richcompare */
3254 0, /* tp_weaklistoffset */
3255 PyObject_SelfIter, /* tp_iter */
3256 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
3257 dictiter_methods, /* tp_methods */
3258 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003259};
3260
3261static PyObject *dictiter_iternextvalue(dictiterobject *di)
3262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -07003264 Py_ssize_t i, n, offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003266 PyObject **value_ptr;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 if (d == NULL)
3269 return NULL;
3270 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 if (di->di_used != d->ma_used) {
3273 PyErr_SetString(PyExc_RuntimeError,
3274 "dictionary changed size during iteration");
3275 di->di_used = -1; /* Make this state sticky */
3276 return NULL;
3277 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 i = di->di_pos;
Victor Stinner742da042016-09-07 17:40:12 -07003280 n = d->ma_keys->dk_nentries - 1;
3281 if (i < 0 || i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 goto fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003283 if (d->ma_values) {
3284 value_ptr = &d->ma_values[i];
3285 offset = sizeof(PyObject *);
3286 }
3287 else {
Victor Stinner742da042016-09-07 17:40:12 -07003288 value_ptr = &DK_ENTRIES(d->ma_keys)[i].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003289 offset = sizeof(PyDictKeyEntry);
3290 }
Victor Stinner742da042016-09-07 17:40:12 -07003291 while (i <= n && *value_ptr == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003292 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003293 i++;
Victor Stinner742da042016-09-07 17:40:12 -07003294 if (i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 goto fail;
3296 }
3297 di->di_pos = i+1;
3298 di->len--;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003299 value = *value_ptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 Py_INCREF(value);
3301 return value;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003302
3303fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003305 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003307}
3308
3309PyTypeObject PyDictIterValue_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3311 "dict_valueiterator", /* tp_name */
3312 sizeof(dictiterobject), /* tp_basicsize */
3313 0, /* tp_itemsize */
3314 /* methods */
3315 (destructor)dictiter_dealloc, /* tp_dealloc */
3316 0, /* tp_print */
3317 0, /* tp_getattr */
3318 0, /* tp_setattr */
3319 0, /* tp_reserved */
3320 0, /* tp_repr */
3321 0, /* tp_as_number */
3322 0, /* tp_as_sequence */
3323 0, /* tp_as_mapping */
3324 0, /* tp_hash */
3325 0, /* tp_call */
3326 0, /* tp_str */
3327 PyObject_GenericGetAttr, /* tp_getattro */
3328 0, /* tp_setattro */
3329 0, /* tp_as_buffer */
3330 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3331 0, /* tp_doc */
3332 (traverseproc)dictiter_traverse, /* tp_traverse */
3333 0, /* tp_clear */
3334 0, /* tp_richcompare */
3335 0, /* tp_weaklistoffset */
3336 PyObject_SelfIter, /* tp_iter */
3337 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
3338 dictiter_methods, /* tp_methods */
3339 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003340};
3341
3342static PyObject *dictiter_iternextitem(dictiterobject *di)
3343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 PyObject *key, *value, *result = di->di_result;
Victor Stinner742da042016-09-07 17:40:12 -07003345 Py_ssize_t i, n, offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003347 PyObject **value_ptr;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 if (d == NULL)
3350 return NULL;
3351 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 if (di->di_used != d->ma_used) {
3354 PyErr_SetString(PyExc_RuntimeError,
3355 "dictionary changed size during iteration");
3356 di->di_used = -1; /* Make this state sticky */
3357 return NULL;
3358 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 i = di->di_pos;
3361 if (i < 0)
3362 goto fail;
Victor Stinner742da042016-09-07 17:40:12 -07003363 n = d->ma_keys->dk_nentries - 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003364 if (d->ma_values) {
3365 value_ptr = &d->ma_values[i];
3366 offset = sizeof(PyObject *);
3367 }
3368 else {
Victor Stinner742da042016-09-07 17:40:12 -07003369 value_ptr = &DK_ENTRIES(d->ma_keys)[i].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003370 offset = sizeof(PyDictKeyEntry);
3371 }
Victor Stinner742da042016-09-07 17:40:12 -07003372 while (i <= n && *value_ptr == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003373 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 i++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003375 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 di->di_pos = i+1;
Victor Stinner742da042016-09-07 17:40:12 -07003377 if (i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 goto fail;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 if (result->ob_refcnt == 1) {
3381 Py_INCREF(result);
3382 Py_DECREF(PyTuple_GET_ITEM(result, 0));
3383 Py_DECREF(PyTuple_GET_ITEM(result, 1));
3384 } else {
3385 result = PyTuple_New(2);
3386 if (result == NULL)
3387 return NULL;
3388 }
3389 di->len--;
Victor Stinner742da042016-09-07 17:40:12 -07003390 key = DK_ENTRIES(d->ma_keys)[i].me_key;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003391 value = *value_ptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 Py_INCREF(key);
3393 Py_INCREF(value);
Eric Snow96c6af92015-05-29 22:21:39 -06003394 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3395 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003397
3398fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003400 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003402}
3403
3404PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3406 "dict_itemiterator", /* tp_name */
3407 sizeof(dictiterobject), /* tp_basicsize */
3408 0, /* tp_itemsize */
3409 /* methods */
3410 (destructor)dictiter_dealloc, /* tp_dealloc */
3411 0, /* tp_print */
3412 0, /* tp_getattr */
3413 0, /* tp_setattr */
3414 0, /* tp_reserved */
3415 0, /* tp_repr */
3416 0, /* tp_as_number */
3417 0, /* tp_as_sequence */
3418 0, /* tp_as_mapping */
3419 0, /* tp_hash */
3420 0, /* tp_call */
3421 0, /* tp_str */
3422 PyObject_GenericGetAttr, /* tp_getattro */
3423 0, /* tp_setattro */
3424 0, /* tp_as_buffer */
3425 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3426 0, /* tp_doc */
3427 (traverseproc)dictiter_traverse, /* tp_traverse */
3428 0, /* tp_clear */
3429 0, /* tp_richcompare */
3430 0, /* tp_weaklistoffset */
3431 PyObject_SelfIter, /* tp_iter */
3432 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
3433 dictiter_methods, /* tp_methods */
3434 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003435};
Guido van Rossumb90c8482007-02-10 01:11:45 +00003436
3437
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003438static PyObject *
3439dictiter_reduce(dictiterobject *di)
3440{
3441 PyObject *list;
3442 dictiterobject tmp;
3443
3444 list = PyList_New(0);
3445 if (!list)
3446 return NULL;
3447
3448 /* copy the itertor state */
3449 tmp = *di;
3450 Py_XINCREF(tmp.di_dict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003451
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003452 /* iterate the temporary into a list */
3453 for(;;) {
3454 PyObject *element = 0;
3455 if (Py_TYPE(di) == &PyDictIterItem_Type)
3456 element = dictiter_iternextitem(&tmp);
3457 else if (Py_TYPE(di) == &PyDictIterKey_Type)
3458 element = dictiter_iternextkey(&tmp);
3459 else if (Py_TYPE(di) == &PyDictIterValue_Type)
3460 element = dictiter_iternextvalue(&tmp);
3461 else
3462 assert(0);
3463 if (element) {
3464 if (PyList_Append(list, element)) {
3465 Py_DECREF(element);
3466 Py_DECREF(list);
3467 Py_XDECREF(tmp.di_dict);
3468 return NULL;
3469 }
3470 Py_DECREF(element);
3471 } else
3472 break;
3473 }
3474 Py_XDECREF(tmp.di_dict);
3475 /* check for error */
3476 if (tmp.di_dict != NULL) {
3477 /* we have an error */
3478 Py_DECREF(list);
3479 return NULL;
3480 }
Antoine Pitroua7013882012-04-05 00:04:20 +02003481 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003482}
3483
Guido van Rossum3ac67412007-02-10 18:55:06 +00003484/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003485/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00003486/***********************************************/
3487
Guido van Rossumb90c8482007-02-10 01:11:45 +00003488/* The instance lay-out is the same for all three; but the type differs. */
3489
Guido van Rossumb90c8482007-02-10 01:11:45 +00003490static void
Eric Snow96c6af92015-05-29 22:21:39 -06003491dictview_dealloc(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 Py_XDECREF(dv->dv_dict);
3494 PyObject_GC_Del(dv);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003495}
3496
3497static int
Eric Snow96c6af92015-05-29 22:21:39 -06003498dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 Py_VISIT(dv->dv_dict);
3501 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003502}
3503
Guido van Rossum83825ac2007-02-10 04:54:19 +00003504static Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003505dictview_len(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 Py_ssize_t len = 0;
3508 if (dv->dv_dict != NULL)
3509 len = dv->dv_dict->ma_used;
3510 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003511}
3512
Eric Snow96c6af92015-05-29 22:21:39 -06003513PyObject *
3514_PyDictView_New(PyObject *dict, PyTypeObject *type)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003515{
Eric Snow96c6af92015-05-29 22:21:39 -06003516 _PyDictViewObject *dv;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 if (dict == NULL) {
3518 PyErr_BadInternalCall();
3519 return NULL;
3520 }
3521 if (!PyDict_Check(dict)) {
3522 /* XXX Get rid of this restriction later */
3523 PyErr_Format(PyExc_TypeError,
3524 "%s() requires a dict argument, not '%s'",
3525 type->tp_name, dict->ob_type->tp_name);
3526 return NULL;
3527 }
Eric Snow96c6af92015-05-29 22:21:39 -06003528 dv = PyObject_GC_New(_PyDictViewObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 if (dv == NULL)
3530 return NULL;
3531 Py_INCREF(dict);
3532 dv->dv_dict = (PyDictObject *)dict;
3533 _PyObject_GC_TRACK(dv);
3534 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003535}
3536
Neal Norwitze36f2ba2007-02-26 23:12:28 +00003537/* TODO(guido): The views objects are not complete:
3538
3539 * support more set operations
3540 * support arbitrary mappings?
3541 - either these should be static or exported in dictobject.h
3542 - if public then they should probably be in builtins
3543*/
3544
Guido van Rossumaac530c2007-08-24 22:33:45 +00003545/* Return 1 if self is a subset of other, iterating over self;
3546 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00003547static int
3548all_contained_in(PyObject *self, PyObject *other)
3549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 PyObject *iter = PyObject_GetIter(self);
3551 int ok = 1;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 if (iter == NULL)
3554 return -1;
3555 for (;;) {
3556 PyObject *next = PyIter_Next(iter);
3557 if (next == NULL) {
3558 if (PyErr_Occurred())
3559 ok = -1;
3560 break;
3561 }
3562 ok = PySequence_Contains(other, next);
3563 Py_DECREF(next);
3564 if (ok <= 0)
3565 break;
3566 }
3567 Py_DECREF(iter);
3568 return ok;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003569}
3570
3571static PyObject *
3572dictview_richcompare(PyObject *self, PyObject *other, int op)
3573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 Py_ssize_t len_self, len_other;
3575 int ok;
3576 PyObject *result;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 assert(self != NULL);
3579 assert(PyDictViewSet_Check(self));
3580 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00003581
Brian Curtindfc80e32011-08-10 20:28:54 -05003582 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
3583 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 len_self = PyObject_Size(self);
3586 if (len_self < 0)
3587 return NULL;
3588 len_other = PyObject_Size(other);
3589 if (len_other < 0)
3590 return NULL;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003592 ok = 0;
3593 switch(op) {
Guido van Rossumaac530c2007-08-24 22:33:45 +00003594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 case Py_NE:
3596 case Py_EQ:
3597 if (len_self == len_other)
3598 ok = all_contained_in(self, other);
3599 if (op == Py_NE && ok >= 0)
3600 ok = !ok;
3601 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 case Py_LT:
3604 if (len_self < len_other)
3605 ok = all_contained_in(self, other);
3606 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 case Py_LE:
3609 if (len_self <= len_other)
3610 ok = all_contained_in(self, other);
3611 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 case Py_GT:
3614 if (len_self > len_other)
3615 ok = all_contained_in(other, self);
3616 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 case Py_GE:
3619 if (len_self >= len_other)
3620 ok = all_contained_in(other, self);
3621 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003623 }
3624 if (ok < 0)
3625 return NULL;
3626 result = ok ? Py_True : Py_False;
3627 Py_INCREF(result);
3628 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003629}
3630
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003631static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003632dictview_repr(_PyDictViewObject *dv)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 PyObject *seq;
3635 PyObject *result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 seq = PySequence_List((PyObject *)dv);
3638 if (seq == NULL)
3639 return NULL;
3640
3641 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
3642 Py_DECREF(seq);
3643 return result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003644}
3645
Guido van Rossum3ac67412007-02-10 18:55:06 +00003646/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003647
3648static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003649dictkeys_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 if (dv->dv_dict == NULL) {
3652 Py_RETURN_NONE;
3653 }
3654 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003655}
3656
3657static int
Eric Snow96c6af92015-05-29 22:21:39 -06003658dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00003659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 if (dv->dv_dict == NULL)
3661 return 0;
3662 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003663}
3664
Guido van Rossum83825ac2007-02-10 04:54:19 +00003665static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 (lenfunc)dictview_len, /* sq_length */
3667 0, /* sq_concat */
3668 0, /* sq_repeat */
3669 0, /* sq_item */
3670 0, /* sq_slice */
3671 0, /* sq_ass_item */
3672 0, /* sq_ass_slice */
3673 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003674};
3675
Guido van Rossum523259b2007-08-24 23:41:22 +00003676static PyObject*
3677dictviews_sub(PyObject* self, PyObject *other)
3678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003679 PyObject *result = PySet_New(self);
3680 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003681 _Py_IDENTIFIER(difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 if (result == NULL)
3684 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003685
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003686 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 if (tmp == NULL) {
3688 Py_DECREF(result);
3689 return NULL;
3690 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692 Py_DECREF(tmp);
3693 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003694}
3695
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003696PyObject*
3697_PyDictView_Intersect(PyObject* self, PyObject *other)
Guido van Rossum523259b2007-08-24 23:41:22 +00003698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 PyObject *result = PySet_New(self);
3700 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003701 _Py_IDENTIFIER(intersection_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003703 if (result == NULL)
3704 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003705
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003706 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_intersection_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003707 if (tmp == NULL) {
3708 Py_DECREF(result);
3709 return NULL;
3710 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003712 Py_DECREF(tmp);
3713 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003714}
3715
3716static PyObject*
3717dictviews_or(PyObject* self, PyObject *other)
3718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 PyObject *result = PySet_New(self);
3720 PyObject *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02003721 _Py_IDENTIFIER(update);
Victor Stinnerd1a9cc22011-10-13 22:51:17 +02003722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003723 if (result == NULL)
3724 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003725
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003726 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 if (tmp == NULL) {
3728 Py_DECREF(result);
3729 return NULL;
3730 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 Py_DECREF(tmp);
3733 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003734}
3735
3736static PyObject*
3737dictviews_xor(PyObject* self, PyObject *other)
3738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 PyObject *result = PySet_New(self);
3740 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003741 _Py_IDENTIFIER(symmetric_difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 if (result == NULL)
3744 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003745
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003746 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_symmetric_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003747 if (tmp == NULL) {
3748 Py_DECREF(result);
3749 return NULL;
3750 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 Py_DECREF(tmp);
3753 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003754}
3755
3756static PyNumberMethods dictviews_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 0, /*nb_add*/
3758 (binaryfunc)dictviews_sub, /*nb_subtract*/
3759 0, /*nb_multiply*/
3760 0, /*nb_remainder*/
3761 0, /*nb_divmod*/
3762 0, /*nb_power*/
3763 0, /*nb_negative*/
3764 0, /*nb_positive*/
3765 0, /*nb_absolute*/
3766 0, /*nb_bool*/
3767 0, /*nb_invert*/
3768 0, /*nb_lshift*/
3769 0, /*nb_rshift*/
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003770 (binaryfunc)_PyDictView_Intersect, /*nb_and*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 (binaryfunc)dictviews_xor, /*nb_xor*/
3772 (binaryfunc)dictviews_or, /*nb_or*/
Guido van Rossum523259b2007-08-24 23:41:22 +00003773};
3774
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003775static PyObject*
3776dictviews_isdisjoint(PyObject *self, PyObject *other)
3777{
3778 PyObject *it;
3779 PyObject *item = NULL;
3780
3781 if (self == other) {
Eric Snow96c6af92015-05-29 22:21:39 -06003782 if (dictview_len((_PyDictViewObject *)self) == 0)
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003783 Py_RETURN_TRUE;
3784 else
3785 Py_RETURN_FALSE;
3786 }
3787
3788 /* Iterate over the shorter object (only if other is a set,
3789 * because PySequence_Contains may be expensive otherwise): */
3790 if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
Eric Snow96c6af92015-05-29 22:21:39 -06003791 Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003792 Py_ssize_t len_other = PyObject_Size(other);
3793 if (len_other == -1)
3794 return NULL;
3795
3796 if ((len_other > len_self)) {
3797 PyObject *tmp = other;
3798 other = self;
3799 self = tmp;
3800 }
3801 }
3802
3803 it = PyObject_GetIter(other);
3804 if (it == NULL)
3805 return NULL;
3806
3807 while ((item = PyIter_Next(it)) != NULL) {
3808 int contains = PySequence_Contains(self, item);
3809 Py_DECREF(item);
3810 if (contains == -1) {
3811 Py_DECREF(it);
3812 return NULL;
3813 }
3814
3815 if (contains) {
3816 Py_DECREF(it);
3817 Py_RETURN_FALSE;
3818 }
3819 }
3820 Py_DECREF(it);
3821 if (PyErr_Occurred())
3822 return NULL; /* PyIter_Next raised an exception. */
3823 Py_RETURN_TRUE;
3824}
3825
3826PyDoc_STRVAR(isdisjoint_doc,
3827"Return True if the view and the given iterable have a null intersection.");
3828
Guido van Rossumb90c8482007-02-10 01:11:45 +00003829static PyMethodDef dictkeys_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003830 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
3831 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00003833};
3834
3835PyTypeObject PyDictKeys_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3837 "dict_keys", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06003838 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 0, /* tp_itemsize */
3840 /* methods */
3841 (destructor)dictview_dealloc, /* tp_dealloc */
3842 0, /* tp_print */
3843 0, /* tp_getattr */
3844 0, /* tp_setattr */
3845 0, /* tp_reserved */
3846 (reprfunc)dictview_repr, /* tp_repr */
3847 &dictviews_as_number, /* tp_as_number */
3848 &dictkeys_as_sequence, /* tp_as_sequence */
3849 0, /* tp_as_mapping */
3850 0, /* tp_hash */
3851 0, /* tp_call */
3852 0, /* tp_str */
3853 PyObject_GenericGetAttr, /* tp_getattro */
3854 0, /* tp_setattro */
3855 0, /* tp_as_buffer */
3856 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3857 0, /* tp_doc */
3858 (traverseproc)dictview_traverse, /* tp_traverse */
3859 0, /* tp_clear */
3860 dictview_richcompare, /* tp_richcompare */
3861 0, /* tp_weaklistoffset */
3862 (getiterfunc)dictkeys_iter, /* tp_iter */
3863 0, /* tp_iternext */
3864 dictkeys_methods, /* tp_methods */
3865 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00003866};
3867
3868static PyObject *
3869dictkeys_new(PyObject *dict)
3870{
Eric Snow96c6af92015-05-29 22:21:39 -06003871 return _PyDictView_New(dict, &PyDictKeys_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003872}
3873
Guido van Rossum3ac67412007-02-10 18:55:06 +00003874/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003875
3876static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003877dictitems_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 if (dv->dv_dict == NULL) {
3880 Py_RETURN_NONE;
3881 }
3882 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003883}
3884
3885static int
Eric Snow96c6af92015-05-29 22:21:39 -06003886dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00003887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 PyObject *key, *value, *found;
3889 if (dv->dv_dict == NULL)
3890 return 0;
3891 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
3892 return 0;
3893 key = PyTuple_GET_ITEM(obj, 0);
3894 value = PyTuple_GET_ITEM(obj, 1);
3895 found = PyDict_GetItem((PyObject *)dv->dv_dict, key);
3896 if (found == NULL) {
3897 if (PyErr_Occurred())
3898 return -1;
3899 return 0;
3900 }
3901 return PyObject_RichCompareBool(value, found, Py_EQ);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003902}
3903
Guido van Rossum83825ac2007-02-10 04:54:19 +00003904static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 (lenfunc)dictview_len, /* sq_length */
3906 0, /* sq_concat */
3907 0, /* sq_repeat */
3908 0, /* sq_item */
3909 0, /* sq_slice */
3910 0, /* sq_ass_item */
3911 0, /* sq_ass_slice */
3912 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003913};
3914
Guido van Rossumb90c8482007-02-10 01:11:45 +00003915static PyMethodDef dictitems_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003916 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
3917 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003918 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00003919};
3920
3921PyTypeObject PyDictItems_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3923 "dict_items", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06003924 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003925 0, /* tp_itemsize */
3926 /* methods */
3927 (destructor)dictview_dealloc, /* tp_dealloc */
3928 0, /* tp_print */
3929 0, /* tp_getattr */
3930 0, /* tp_setattr */
3931 0, /* tp_reserved */
3932 (reprfunc)dictview_repr, /* tp_repr */
3933 &dictviews_as_number, /* tp_as_number */
3934 &dictitems_as_sequence, /* tp_as_sequence */
3935 0, /* tp_as_mapping */
3936 0, /* tp_hash */
3937 0, /* tp_call */
3938 0, /* tp_str */
3939 PyObject_GenericGetAttr, /* tp_getattro */
3940 0, /* tp_setattro */
3941 0, /* tp_as_buffer */
3942 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3943 0, /* tp_doc */
3944 (traverseproc)dictview_traverse, /* tp_traverse */
3945 0, /* tp_clear */
3946 dictview_richcompare, /* tp_richcompare */
3947 0, /* tp_weaklistoffset */
3948 (getiterfunc)dictitems_iter, /* tp_iter */
3949 0, /* tp_iternext */
3950 dictitems_methods, /* tp_methods */
3951 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00003952};
3953
3954static PyObject *
3955dictitems_new(PyObject *dict)
3956{
Eric Snow96c6af92015-05-29 22:21:39 -06003957 return _PyDictView_New(dict, &PyDictItems_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003958}
3959
Guido van Rossum3ac67412007-02-10 18:55:06 +00003960/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003961
3962static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003963dictvalues_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 if (dv->dv_dict == NULL) {
3966 Py_RETURN_NONE;
3967 }
3968 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003969}
3970
Guido van Rossum83825ac2007-02-10 04:54:19 +00003971static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 (lenfunc)dictview_len, /* sq_length */
3973 0, /* sq_concat */
3974 0, /* sq_repeat */
3975 0, /* sq_item */
3976 0, /* sq_slice */
3977 0, /* sq_ass_item */
3978 0, /* sq_ass_slice */
3979 (objobjproc)0, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003980};
3981
Guido van Rossumb90c8482007-02-10 01:11:45 +00003982static PyMethodDef dictvalues_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003983 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00003984};
3985
3986PyTypeObject PyDictValues_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3988 "dict_values", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06003989 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003990 0, /* tp_itemsize */
3991 /* methods */
3992 (destructor)dictview_dealloc, /* tp_dealloc */
3993 0, /* tp_print */
3994 0, /* tp_getattr */
3995 0, /* tp_setattr */
3996 0, /* tp_reserved */
3997 (reprfunc)dictview_repr, /* tp_repr */
3998 0, /* tp_as_number */
3999 &dictvalues_as_sequence, /* tp_as_sequence */
4000 0, /* tp_as_mapping */
4001 0, /* tp_hash */
4002 0, /* tp_call */
4003 0, /* tp_str */
4004 PyObject_GenericGetAttr, /* tp_getattro */
4005 0, /* tp_setattro */
4006 0, /* tp_as_buffer */
4007 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4008 0, /* tp_doc */
4009 (traverseproc)dictview_traverse, /* tp_traverse */
4010 0, /* tp_clear */
4011 0, /* tp_richcompare */
4012 0, /* tp_weaklistoffset */
4013 (getiterfunc)dictvalues_iter, /* tp_iter */
4014 0, /* tp_iternext */
4015 dictvalues_methods, /* tp_methods */
4016 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004017};
4018
4019static PyObject *
4020dictvalues_new(PyObject *dict)
4021{
Eric Snow96c6af92015-05-29 22:21:39 -06004022 return _PyDictView_New(dict, &PyDictValues_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004023}
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004024
4025/* Returns NULL if cannot allocate a new PyDictKeysObject,
4026 but does not set an error */
4027PyDictKeysObject *
4028_PyDict_NewKeysForClass(void)
4029{
Victor Stinner742da042016-09-07 17:40:12 -07004030 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004031 if (keys == NULL)
4032 PyErr_Clear();
4033 else
4034 keys->dk_lookup = lookdict_split;
4035 return keys;
4036}
4037
4038#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
4039
4040PyObject *
4041PyObject_GenericGetDict(PyObject *obj, void *context)
4042{
4043 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
4044 if (dictptr == NULL) {
4045 PyErr_SetString(PyExc_AttributeError,
4046 "This object has no __dict__");
4047 return NULL;
4048 }
4049 dict = *dictptr;
4050 if (dict == NULL) {
4051 PyTypeObject *tp = Py_TYPE(obj);
4052 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
4053 DK_INCREF(CACHED_KEYS(tp));
4054 *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
4055 }
4056 else {
4057 *dictptr = dict = PyDict_New();
4058 }
4059 }
4060 Py_XINCREF(dict);
4061 return dict;
4062}
4063
4064int
4065_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
Victor Stinner742da042016-09-07 17:40:12 -07004066 PyObject *key, PyObject *value)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004067{
4068 PyObject *dict;
4069 int res;
4070 PyDictKeysObject *cached;
4071
4072 assert(dictptr != NULL);
4073 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
4074 assert(dictptr != NULL);
4075 dict = *dictptr;
4076 if (dict == NULL) {
4077 DK_INCREF(cached);
4078 dict = new_dict_with_shared_keys(cached);
4079 if (dict == NULL)
4080 return -1;
4081 *dictptr = dict;
4082 }
4083 if (value == NULL) {
4084 res = PyDict_DelItem(dict, key);
4085 if (cached != ((PyDictObject *)dict)->ma_keys) {
4086 CACHED_KEYS(tp) = NULL;
4087 DK_DECREF(cached);
4088 }
4089 } else {
4090 res = PyDict_SetItem(dict, key, value);
4091 if (cached != ((PyDictObject *)dict)->ma_keys) {
4092 /* Either update tp->ht_cached_keys or delete it */
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004093 if (cached->dk_refcnt == 1) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004094 CACHED_KEYS(tp) = make_keys_shared(dict);
Victor Stinner742da042016-09-07 17:40:12 -07004095 }
4096 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004097 CACHED_KEYS(tp) = NULL;
4098 }
4099 DK_DECREF(cached);
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004100 if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
4101 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004102 }
4103 }
4104 } else {
4105 dict = *dictptr;
4106 if (dict == NULL) {
4107 dict = PyDict_New();
4108 if (dict == NULL)
4109 return -1;
4110 *dictptr = dict;
4111 }
4112 if (value == NULL) {
4113 res = PyDict_DelItem(dict, key);
4114 } else {
4115 res = PyDict_SetItem(dict, key, value);
4116 }
4117 }
4118 return res;
4119}
4120
4121void
4122_PyDictKeys_DecRef(PyDictKeysObject *keys)
4123{
4124 DK_DECREF(keys);
4125}