blob: 8e5fe82d5ea31d98819a2e08afff0da6d87e4265 [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.
14https://morepypy.blogspot.jp/2015/01/faster-more-memory-efficient-and-more.html
15
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 */
303Py_LOCAL_INLINE(Py_ssize_t)
304dk_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. */
324Py_LOCAL_INLINE(void)
325dk_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 {
434 dk = PyObject_MALLOC(sizeof(PyDictKeysObject) - 8 +
435 es * size +
436 sizeof(PyDictKeyEntry) * usable);
437 if (dk == NULL) {
438 PyErr_NoMemory();
439 return NULL;
440 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400441 }
Antoine Pitrou2d169b22012-05-12 23:43:44 +0200442 DK_DEBUG_INCREF dk->dk_refcnt = 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400443 dk->dk_size = size;
Victor Stinner742da042016-09-07 17:40:12 -0700444 dk->dk_usable = usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400445 dk->dk_lookup = lookdict_unicode_nodummy;
Victor Stinner742da042016-09-07 17:40:12 -0700446 dk->dk_nentries = 0;
447 memset(&dk->dk_indices[0], 0xff, es * size);
448 memset(DK_ENTRIES(dk), 0, sizeof(PyDictKeyEntry) * usable);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400449 return dk;
450}
451
452static void
453free_keys_object(PyDictKeysObject *keys)
454{
Victor Stinner742da042016-09-07 17:40:12 -0700455 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400456 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -0700457 for (i = 0, n = keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400458 Py_XDECREF(entries[i].me_key);
459 Py_XDECREF(entries[i].me_value);
460 }
Victor Stinner742da042016-09-07 17:40:12 -0700461 if (keys->dk_size == PyDict_MINSIZE && numfreekeys < PyDict_MAXFREELIST) {
462 keys_free_list[numfreekeys++] = keys;
463 return;
464 }
Raymond Hettingerce5179f2016-01-31 08:56:21 -0800465 PyObject_FREE(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400466}
467
468#define new_values(size) PyMem_NEW(PyObject *, size)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400469#define free_values(values) PyMem_FREE(values)
470
471/* Consumes a reference to the keys object */
472static PyObject *
473new_dict(PyDictKeysObject *keys, PyObject **values)
474{
475 PyDictObject *mp;
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200476 assert(keys != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 if (numfree) {
478 mp = free_list[--numfree];
479 assert (mp != NULL);
480 assert (Py_TYPE(mp) == &PyDict_Type);
481 _Py_NewReference((PyObject *)mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400483 else {
484 mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
485 if (mp == NULL) {
486 DK_DECREF(keys);
487 free_values(values);
488 return NULL;
489 }
490 }
491 mp->ma_keys = keys;
492 mp->ma_values = values;
493 mp->ma_used = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000495}
496
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400497/* Consumes a reference to the keys object */
498static PyObject *
499new_dict_with_shared_keys(PyDictKeysObject *keys)
500{
501 PyObject **values;
502 Py_ssize_t i, size;
503
Victor Stinner742da042016-09-07 17:40:12 -0700504 size = USABLE_FRACTION(DK_SIZE(keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400505 values = new_values(size);
506 if (values == NULL) {
507 DK_DECREF(keys);
508 return PyErr_NoMemory();
509 }
510 for (i = 0; i < size; i++) {
511 values[i] = NULL;
512 }
513 return new_dict(keys, values);
514}
515
516PyObject *
517PyDict_New(void)
518{
Victor Stinner742da042016-09-07 17:40:12 -0700519 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200520 if (keys == NULL)
521 return NULL;
522 return new_dict(keys, NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400523}
524
Victor Stinner742da042016-09-07 17:40:12 -0700525/* Search index of hash table from offset of entry table */
526static Py_ssize_t
527lookdict_index(PyDictKeysObject *k, Py_hash_t hash, Py_ssize_t index)
528{
529 size_t i, perturb;
530 size_t mask = DK_MASK(k);
531 Py_ssize_t ix;
532
533 i = (size_t)hash & mask;
534 ix = dk_get_index(k, i);
535 if (ix == index) {
536 return i;
537 }
538 if (ix == DKIX_EMPTY) {
539 return DKIX_EMPTY;
540 }
541
542 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
543 i = mask & ((i << 2) + i + perturb + 1);
544 ix = dk_get_index(k, i);
545 if (ix == index) {
546 return i;
547 }
548 if (ix == DKIX_EMPTY) {
549 return DKIX_EMPTY;
550 }
551 }
552 assert(0); /* NOT REACHED */
553 return DKIX_ERROR;
554}
555
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000556/*
557The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000558This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000559Open addressing is preferred over chaining since the link overhead for
560chaining would be substantial (100% with typical malloc overhead).
561
Tim Peterseb28ef22001-06-02 05:27:19 +0000562The initial probe index is computed as hash mod the table size. Subsequent
563probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000564
565All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000566
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000567The details in this version are due to Tim Peters, building on many past
Tim Peterseb28ef22001-06-02 05:27:19 +0000568contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000569Christian Tismer.
Fred Drake1bff34a2000-08-31 19:31:38 +0000570
Victor Stinner742da042016-09-07 17:40:12 -0700571lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000572comparison raises an exception (this was new in Python 2.5).
Guido van Rossum89d8c602007-09-18 17:26:56 +0000573lookdict_unicode() below is specialized to string keys, comparison of which can
Victor Stinner742da042016-09-07 17:40:12 -0700574never raise an exception; that function can never return DKIX_ERROR.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400575lookdict_unicode_nodummy is further specialized for string keys that cannot be
576the <dummy> value.
Victor Stinner742da042016-09-07 17:40:12 -0700577For both, when the key isn't found a DKIX_EMPTY is returned. hashpos returns
578where the key index should be inserted.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000579*/
Victor Stinner742da042016-09-07 17:40:12 -0700580static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400581lookdict(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700582 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000583{
Victor Stinner742da042016-09-07 17:40:12 -0700584 size_t i, perturb, mask;
585 Py_ssize_t ix, freeslot;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200586 int cmp;
Victor Stinner742da042016-09-07 17:40:12 -0700587 PyDictKeysObject *dk;
588 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 PyObject *startkey;
Tim Peterseb28ef22001-06-02 05:27:19 +0000590
Antoine Pitrou9a234902012-05-13 20:48:01 +0200591top:
Victor Stinner742da042016-09-07 17:40:12 -0700592 dk = mp->ma_keys;
593 mask = DK_MASK(dk);
594 ep0 = DK_ENTRIES(dk);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700596
597 ix = dk_get_index(dk, i);
598 if (ix == DKIX_EMPTY) {
599 if (hashpos != NULL)
600 *hashpos = i;
601 *value_addr = NULL;
602 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400603 }
Victor Stinner742da042016-09-07 17:40:12 -0700604 if (ix == DKIX_DUMMY) {
605 freeslot = i;
606 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 else {
Victor Stinner742da042016-09-07 17:40:12 -0700608 ep = &ep0[ix];
609 if (ep->me_key == key) {
610 *value_addr = &ep->me_value;
611 if (hashpos != NULL)
612 *hashpos = i;
613 return ix;
614 }
615 if (ep->me_key != NULL && ep->me_hash == hash) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 startkey = ep->me_key;
617 Py_INCREF(startkey);
618 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
619 Py_DECREF(startkey);
620 if (cmp < 0)
Victor Stinner742da042016-09-07 17:40:12 -0700621 return DKIX_ERROR;
622 if (dk == mp->ma_keys && ep->me_key == startkey) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400623 if (cmp > 0) {
624 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700625 if (hashpos != NULL)
626 *hashpos = i;
627 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400628 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 }
630 else {
Antoine Pitrou9a234902012-05-13 20:48:01 +0200631 /* The dict was mutated, restart */
632 goto top;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 }
634 }
Victor Stinner742da042016-09-07 17:40:12 -0700635 freeslot = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 }
Tim Peters15d49292001-05-27 07:39:22 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700639 i = ((i << 2) + i + perturb + 1) & mask;
640 ix = dk_get_index(dk, i);
641 if (ix == DKIX_EMPTY) {
642 if (hashpos != NULL) {
643 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400644 }
Victor Stinner742da042016-09-07 17:40:12 -0700645 *value_addr = NULL;
646 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400647 }
Victor Stinner742da042016-09-07 17:40:12 -0700648 if (ix == DKIX_DUMMY) {
649 if (freeslot == -1)
650 freeslot = i;
651 continue;
652 }
653 ep = &ep0[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400654 if (ep->me_key == key) {
Victor Stinner742da042016-09-07 17:40:12 -0700655 if (hashpos != NULL) {
656 *hashpos = i;
657 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400658 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700659 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400660 }
Victor Stinner742da042016-09-07 17:40:12 -0700661 if (ep->me_hash == hash && ep->me_key != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 startkey = ep->me_key;
663 Py_INCREF(startkey);
664 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
665 Py_DECREF(startkey);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400666 if (cmp < 0) {
667 *value_addr = NULL;
Victor Stinner742da042016-09-07 17:40:12 -0700668 return DKIX_ERROR;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400669 }
Victor Stinner742da042016-09-07 17:40:12 -0700670 if (dk == mp->ma_keys && ep->me_key == startkey) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400671 if (cmp > 0) {
Victor Stinner742da042016-09-07 17:40:12 -0700672 if (hashpos != NULL) {
673 *hashpos = i;
674 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400675 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700676 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400677 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 }
679 else {
Antoine Pitrou9a234902012-05-13 20:48:01 +0200680 /* The dict was mutated, restart */
681 goto top;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 }
683 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 }
685 assert(0); /* NOT REACHED */
686 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000687}
688
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400689/* Specialized version for string-only keys */
Victor Stinner742da042016-09-07 17:40:12 -0700690static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400691lookdict_unicode(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700692 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Fred Drake1bff34a2000-08-31 19:31:38 +0000693{
Victor Stinner742da042016-09-07 17:40:12 -0700694 size_t i, perturb;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200695 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700696 Py_ssize_t ix, freeslot;
697 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Fred Drake1bff34a2000-08-31 19:31:38 +0000698
Victor Stinner742da042016-09-07 17:40:12 -0700699 assert(mp->ma_values == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 /* Make sure this function doesn't have to handle non-unicode keys,
701 including subclasses of str; e.g., one reason to subclass
702 unicodes is to override __eq__, and for speed we don't cater to
703 that here. */
704 if (!PyUnicode_CheckExact(key)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400705 mp->ma_keys->dk_lookup = lookdict;
Victor Stinner742da042016-09-07 17:40:12 -0700706 return lookdict(mp, key, hash, value_addr, hashpos);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 }
Mark Dickinson57e683e2011-09-24 18:18:40 +0100708 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700709 ix = dk_get_index(mp->ma_keys, i);
710 if (ix == DKIX_EMPTY) {
711 if (hashpos != NULL)
712 *hashpos = i;
713 *value_addr = NULL;
714 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400715 }
Victor Stinner742da042016-09-07 17:40:12 -0700716 if (ix == DKIX_DUMMY) {
717 freeslot = i;
718 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 else {
Victor Stinner742da042016-09-07 17:40:12 -0700720 ep = &ep0[ix];
721 /* only split table can be ix != DKIX_DUMMY && me_key == NULL */
722 assert(ep->me_key != NULL);
723 if (ep->me_key == key || (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
724 if (hashpos != NULL)
725 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400726 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700727 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400728 }
Victor Stinner742da042016-09-07 17:40:12 -0700729 freeslot = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 }
Tim Peters15d49292001-05-27 07:39:22 +0000731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700733 i = mask & ((i << 2) + i + perturb + 1);
734 ix = dk_get_index(mp->ma_keys, i);
735 if (ix == DKIX_EMPTY) {
736 if (hashpos != NULL) {
737 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400738 }
Victor Stinner742da042016-09-07 17:40:12 -0700739 *value_addr = NULL;
740 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400741 }
Victor Stinner742da042016-09-07 17:40:12 -0700742 if (ix == DKIX_DUMMY) {
743 if (freeslot == -1)
744 freeslot = i;
745 continue;
746 }
747 ep = &ep0[ix];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 if (ep->me_key == key
749 || (ep->me_hash == hash
Victor Stinner742da042016-09-07 17:40:12 -0700750 && ep->me_key != NULL
751 && unicode_eq(ep->me_key, key))) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400752 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700753 if (hashpos != NULL) {
754 *hashpos = i;
755 }
756 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400757 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 }
759 assert(0); /* NOT REACHED */
760 return 0;
Fred Drake1bff34a2000-08-31 19:31:38 +0000761}
762
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400763/* Faster version of lookdict_unicode when it is known that no <dummy> keys
764 * will be present. */
Victor Stinner742da042016-09-07 17:40:12 -0700765static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400766lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700767 Py_hash_t hash, PyObject ***value_addr,
768 Py_ssize_t *hashpos)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400769{
Victor Stinner742da042016-09-07 17:40:12 -0700770 size_t i, perturb;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200771 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700772 Py_ssize_t ix;
773 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400774
Victor Stinner742da042016-09-07 17:40:12 -0700775 assert(mp->ma_values == NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400776 /* Make sure this function doesn't have to handle non-unicode keys,
777 including subclasses of str; e.g., one reason to subclass
778 unicodes is to override __eq__, and for speed we don't cater to
779 that here. */
780 if (!PyUnicode_CheckExact(key)) {
781 mp->ma_keys->dk_lookup = lookdict;
Victor Stinner742da042016-09-07 17:40:12 -0700782 return lookdict(mp, key, hash, value_addr, hashpos);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400783 }
784 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700785 ix = dk_get_index(mp->ma_keys, i);
786 assert (ix != DKIX_DUMMY);
787 if (ix == DKIX_EMPTY) {
788 if (hashpos != NULL)
789 *hashpos = i;
790 *value_addr = NULL;
791 return DKIX_EMPTY;
792 }
793 ep = &ep0[ix];
794 assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
795 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400796 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700797 if (hashpos != NULL)
798 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400799 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700800 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400801 }
802 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700803 i = mask & ((i << 2) + i + perturb + 1);
804 ix = dk_get_index(mp->ma_keys, i);
805 assert (ix != DKIX_DUMMY);
806 if (ix == DKIX_EMPTY) {
807 if (hashpos != NULL)
808 *hashpos = i;
809 *value_addr = NULL;
810 return DKIX_EMPTY;
811 }
812 ep = &ep0[ix];
813 assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
814 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400815 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700816 if (hashpos != NULL)
817 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400818 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700819 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400820 }
821 }
822 assert(0); /* NOT REACHED */
823 return 0;
824}
825
826/* Version of lookdict for split tables.
827 * All split tables and only split tables use this lookup function.
828 * Split tables only contain unicode keys and no dummy keys,
829 * so algorithm is the same as lookdict_unicode_nodummy.
830 */
Victor Stinner742da042016-09-07 17:40:12 -0700831static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400832lookdict_split(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700833 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400834{
Victor Stinner742da042016-09-07 17:40:12 -0700835 size_t i, perturb;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200836 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700837 Py_ssize_t ix;
838 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400839
Victor Stinner742da042016-09-07 17:40:12 -0700840 /* mp must split table */
841 assert(mp->ma_values != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400842 if (!PyUnicode_CheckExact(key)) {
Victor Stinner742da042016-09-07 17:40:12 -0700843 ix = lookdict(mp, key, hash, value_addr, hashpos);
844 if (ix >= 0) {
845 *value_addr = &mp->ma_values[ix];
846 }
847 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400848 }
Victor Stinner742da042016-09-07 17:40:12 -0700849
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400850 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700851 ix = dk_get_index(mp->ma_keys, i);
852 if (ix == DKIX_EMPTY) {
853 if (hashpos != NULL)
854 *hashpos = i;
855 *value_addr = NULL;
856 return DKIX_EMPTY;
857 }
858 assert(ix >= 0);
859 ep = &ep0[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400860 assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700861 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400862 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700863 if (hashpos != NULL)
864 *hashpos = i;
865 *value_addr = &mp->ma_values[ix];
866 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400867 }
868 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700869 i = mask & ((i << 2) + i + perturb + 1);
870 ix = dk_get_index(mp->ma_keys, i);
871 if (ix == DKIX_EMPTY) {
872 if (hashpos != NULL)
873 *hashpos = i;
874 *value_addr = NULL;
875 return DKIX_EMPTY;
876 }
877 assert(ix >= 0);
878 ep = &ep0[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400879 assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700880 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400881 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700882 if (hashpos != NULL)
883 *hashpos = i;
884 *value_addr = &mp->ma_values[ix];
885 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400886 }
887 }
888 assert(0); /* NOT REACHED */
889 return 0;
890}
891
Benjamin Petersonfb886362010-04-24 18:21:17 +0000892int
893_PyDict_HasOnlyStringKeys(PyObject *dict)
894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 Py_ssize_t pos = 0;
896 PyObject *key, *value;
Benjamin Petersonf6096542010-11-17 22:33:12 +0000897 assert(PyDict_Check(dict));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 /* Shortcut */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400899 if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 return 1;
901 while (PyDict_Next(dict, &pos, &key, &value))
902 if (!PyUnicode_Check(key))
903 return 0;
904 return 1;
Benjamin Petersonfb886362010-04-24 18:21:17 +0000905}
906
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000907#define MAINTAIN_TRACKING(mp, key, value) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 do { \
909 if (!_PyObject_GC_IS_TRACKED(mp)) { \
910 if (_PyObject_GC_MAY_BE_TRACKED(key) || \
911 _PyObject_GC_MAY_BE_TRACKED(value)) { \
912 _PyObject_GC_TRACK(mp); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 } \
914 } \
915 } while(0)
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000916
917void
918_PyDict_MaybeUntrack(PyObject *op)
919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 PyDictObject *mp;
921 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -0700922 Py_ssize_t i, numentries;
923 PyDictKeyEntry *ep0;
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
926 return;
927
928 mp = (PyDictObject *) op;
Victor Stinner742da042016-09-07 17:40:12 -0700929 ep0 = DK_ENTRIES(mp->ma_keys);
930 numentries = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400931 if (_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -0700932 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400933 if ((value = mp->ma_values[i]) == NULL)
934 continue;
935 if (_PyObject_GC_MAY_BE_TRACKED(value)) {
Victor Stinner742da042016-09-07 17:40:12 -0700936 assert(!_PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400937 return;
938 }
939 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400941 else {
Victor Stinner742da042016-09-07 17:40:12 -0700942 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400943 if ((value = ep0[i].me_value) == NULL)
944 continue;
945 if (_PyObject_GC_MAY_BE_TRACKED(value) ||
946 _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
947 return;
948 }
949 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 _PyObject_GC_UNTRACK(op);
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000951}
952
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400953/* Internal function to find slot for an item from its hash
954 * when it is known that the key is not present in the dict.
955 */
Victor Stinner742da042016-09-07 17:40:12 -0700956static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400957find_empty_slot(PyDictObject *mp, PyObject *key, Py_hash_t hash,
Victor Stinner742da042016-09-07 17:40:12 -0700958 PyObject ***value_addr, Py_ssize_t *hashpos)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000959{
Victor Stinner742da042016-09-07 17:40:12 -0700960 size_t i, perturb;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400961 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700962 Py_ssize_t ix;
963 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000964
Victor Stinner742da042016-09-07 17:40:12 -0700965 assert(hashpos != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400966 assert(key != NULL);
967 if (!PyUnicode_CheckExact(key))
968 mp->ma_keys->dk_lookup = lookdict;
969 i = hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700970 ix = dk_get_index(mp->ma_keys, i);
971 for (perturb = hash; ix != DKIX_EMPTY; perturb >>= PERTURB_SHIFT) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400972 i = (i << 2) + i + perturb + 1;
Victor Stinner742da042016-09-07 17:40:12 -0700973 ix = dk_get_index(mp->ma_keys, i & mask);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 }
Victor Stinner742da042016-09-07 17:40:12 -0700975 ep = &ep0[mp->ma_keys->dk_nentries];
976 *hashpos = i & mask;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400977 assert(ep->me_value == NULL);
978 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -0700979 *value_addr = &mp->ma_values[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400980 else
981 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700982 return ix;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000983}
984
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400985static int
986insertion_resize(PyDictObject *mp)
987{
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700988 return dictresize(mp, GROWTH_RATE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400989}
Antoine Pitroue965d972012-02-27 00:45:12 +0100990
991/*
992Internal routine to insert a new item into the table.
993Used both by the internal resize routine and by the public insert routine.
Antoine Pitroue965d972012-02-27 00:45:12 +0100994Returns -1 if an error occurred, or 0 on success.
995*/
996static int
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400997insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +0100998{
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400999 PyObject *old_value;
1000 PyObject **value_addr;
Victor Stinner742da042016-09-07 17:40:12 -07001001 PyDictKeyEntry *ep, *ep0;
1002 Py_ssize_t hashpos, ix;
Antoine Pitroue965d972012-02-27 00:45:12 +01001003
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001004 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
1005 if (insertion_resize(mp) < 0)
1006 return -1;
1007 }
1008
Victor Stinner742da042016-09-07 17:40:12 -07001009 ix = mp->ma_keys->dk_lookup(mp, key, hash, &value_addr, &hashpos);
1010 if (ix == DKIX_ERROR) {
Antoine Pitroue965d972012-02-27 00:45:12 +01001011 return -1;
1012 }
Victor Stinner742da042016-09-07 17:40:12 -07001013
Antoine Pitroud6967322014-10-18 00:35:00 +02001014 assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
Benjamin Petersona6f195e2012-04-30 10:23:40 -04001015 Py_INCREF(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001016 MAINTAIN_TRACKING(mp, key, value);
Victor Stinner742da042016-09-07 17:40:12 -07001017
1018 /* When insertion order is different from shared key, we can't share
1019 * the key anymore. Convert this instance to combine table.
1020 */
1021 if (_PyDict_HasSplitTable(mp) &&
1022 ((ix >= 0 && *value_addr == NULL && mp->ma_used != ix) ||
1023 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
1024 if (insertion_resize(mp) < 0) {
1025 Py_DECREF(value);
1026 return -1;
1027 }
1028 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
1029 ix = DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001030 }
Victor Stinner742da042016-09-07 17:40:12 -07001031
1032 if (ix == DKIX_EMPTY) {
1033 /* Insert into new slot. */
1034 if (mp->ma_keys->dk_usable <= 0) {
1035 /* Need to resize. */
1036 if (insertion_resize(mp) < 0) {
1037 Py_DECREF(value);
1038 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001039 }
Victor Stinner742da042016-09-07 17:40:12 -07001040 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
1041 }
1042 ep0 = DK_ENTRIES(mp->ma_keys);
1043 ep = &ep0[mp->ma_keys->dk_nentries];
1044 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
1045 Py_INCREF(key);
1046 ep->me_key = key;
1047 ep->me_hash = hash;
1048 if (mp->ma_values) {
1049 assert (mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
1050 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001051 }
1052 else {
Victor Stinner742da042016-09-07 17:40:12 -07001053 ep->me_value = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001054 }
1055 mp->ma_used++;
Victor Stinner742da042016-09-07 17:40:12 -07001056 mp->ma_keys->dk_usable--;
1057 mp->ma_keys->dk_nentries++;
1058 assert(mp->ma_keys->dk_usable >= 0);
1059 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001060 }
Victor Stinner742da042016-09-07 17:40:12 -07001061
1062 assert(value_addr != NULL);
1063
1064 old_value = *value_addr;
1065 if (old_value != NULL) {
1066 *value_addr = value;
1067 Py_DECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
1068 return 0;
1069 }
1070
1071 /* pending state */
1072 assert(_PyDict_HasSplitTable(mp));
1073 assert(ix == mp->ma_used);
1074 *value_addr = value;
1075 mp->ma_used++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001076 return 0;
Antoine Pitroue965d972012-02-27 00:45:12 +01001077}
1078
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001079/*
1080Internal routine used by dictresize() to insert an item which is
1081known to be absent from the dict. This routine also assumes that
1082the dict contains no deleted entries. Besides the performance benefit,
1083using insertdict() in dictresize() is dangerous (SF bug #1456209).
1084Note that no refcounts are changed by this routine; if needed, the caller
1085is responsible for incref'ing `key` and `value`.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001086Neither mp->ma_used nor k->dk_usable are modified by this routine; the caller
1087must set them correctly
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001088*/
1089static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001090insertdict_clean(PyDictObject *mp, PyObject *key, Py_hash_t hash,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 PyObject *value)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001092{
Victor Stinner742da042016-09-07 17:40:12 -07001093 size_t i, perturb;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001094 PyDictKeysObject *k = mp->ma_keys;
1095 size_t mask = (size_t)DK_SIZE(k)-1;
Victor Stinner742da042016-09-07 17:40:12 -07001096 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001097 PyDictKeyEntry *ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001098
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001099 assert(k->dk_lookup != NULL);
1100 assert(value != NULL);
1101 assert(key != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001102 assert(PyUnicode_CheckExact(key) || k->dk_lookup == lookdict);
1103 i = hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -07001104 for (perturb = hash; dk_get_index(k, i) != DKIX_EMPTY;
1105 perturb >>= PERTURB_SHIFT) {
1106 i = mask & ((i << 2) + i + perturb + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 }
Victor Stinner742da042016-09-07 17:40:12 -07001108 ep = &ep0[k->dk_nentries];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 assert(ep->me_value == NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001110 dk_set_index(k, i, k->dk_nentries);
1111 k->dk_nentries++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 ep->me_key = key;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001113 ep->me_hash = hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 ep->me_value = value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001115}
1116
1117/*
1118Restructure the table by allocating a new table and reinserting all
1119items again. When entries have been deleted, the new table may
1120actually be smaller than the old one.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001121If a table is split (its keys and hashes are shared, its values are not),
1122then the values are temporarily copied into the table, it is resized as
1123a combined table, then the me_value slots in the old table are NULLed out.
1124After resizing a table is always combined,
1125but can be resplit by make_keys_shared().
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001126*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001127static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001128dictresize(PyDictObject *mp, Py_ssize_t minused)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001129{
Victor Stinner742da042016-09-07 17:40:12 -07001130 Py_ssize_t i, newsize;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001131 PyDictKeysObject *oldkeys;
1132 PyObject **oldvalues;
Victor Stinner742da042016-09-07 17:40:12 -07001133 PyDictKeyEntry *ep0;
Tim Peters91a364d2001-05-19 07:04:38 +00001134
Victor Stinner742da042016-09-07 17:40:12 -07001135 /* Find the smallest table size > minused. */
1136 for (newsize = PyDict_MINSIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 newsize <= minused && newsize > 0;
1138 newsize <<= 1)
1139 ;
1140 if (newsize <= 0) {
1141 PyErr_NoMemory();
1142 return -1;
1143 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001144 oldkeys = mp->ma_keys;
1145 oldvalues = mp->ma_values;
1146 /* Allocate a new table. */
1147 mp->ma_keys = new_keys_object(newsize);
1148 if (mp->ma_keys == NULL) {
1149 mp->ma_keys = oldkeys;
1150 return -1;
1151 }
1152 if (oldkeys->dk_lookup == lookdict)
1153 mp->ma_keys->dk_lookup = lookdict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001154 mp->ma_values = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001155 ep0 = DK_ENTRIES(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001156 /* Main loop below assumes we can transfer refcount to new keys
1157 * and that value is stored in me_value.
1158 * Increment ref-counts and copy values here to compensate
1159 * This (resizing a split table) should be relatively rare */
1160 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001161 for (i = 0; i < oldkeys->dk_nentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001162 if (oldvalues[i] != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001163 Py_INCREF(ep0[i].me_key);
1164 ep0[i].me_value = oldvalues[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 }
1167 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001168 /* Main loop */
Victor Stinner742da042016-09-07 17:40:12 -07001169 for (i = 0; i < oldkeys->dk_nentries; i++) {
1170 PyDictKeyEntry *ep = &ep0[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001171 if (ep->me_value != NULL) {
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001172 insertdict_clean(mp, ep->me_key, ep->me_hash, ep->me_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001175 mp->ma_keys->dk_usable -= mp->ma_used;
1176 if (oldvalues != NULL) {
1177 /* NULL out me_value slot in oldkeys, in case it was shared */
Victor Stinner742da042016-09-07 17:40:12 -07001178 for (i = 0; i < oldkeys->dk_nentries; i++)
1179 ep0[i].me_value = NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001180 DK_DECREF(oldkeys);
Victor Stinner742da042016-09-07 17:40:12 -07001181 if (oldvalues != empty_values) {
1182 free_values(oldvalues);
1183 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001184 }
1185 else {
1186 assert(oldkeys->dk_lookup != lookdict_split);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001187 assert(oldkeys->dk_refcnt == 1);
Raymond Hettingerce5179f2016-01-31 08:56:21 -08001188 DK_DEBUG_DECREF PyObject_FREE(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001189 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001191}
1192
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001193/* Returns NULL if unable to split table.
1194 * A NULL return does not necessarily indicate an error */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001195static PyDictKeysObject *
1196make_keys_shared(PyObject *op)
1197{
1198 Py_ssize_t i;
1199 Py_ssize_t size;
1200 PyDictObject *mp = (PyDictObject *)op;
1201
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001202 if (!PyDict_CheckExact(op))
1203 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001204 if (!_PyDict_HasSplitTable(mp)) {
1205 PyDictKeyEntry *ep0;
1206 PyObject **values;
1207 assert(mp->ma_keys->dk_refcnt == 1);
1208 if (mp->ma_keys->dk_lookup == lookdict) {
1209 return NULL;
1210 }
1211 else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
1212 /* Remove dummy keys */
1213 if (dictresize(mp, DK_SIZE(mp->ma_keys)))
1214 return NULL;
1215 }
1216 assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
1217 /* Copy values into a new array */
Victor Stinner742da042016-09-07 17:40:12 -07001218 ep0 = DK_ENTRIES(mp->ma_keys);
1219 size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001220 values = new_values(size);
1221 if (values == NULL) {
1222 PyErr_SetString(PyExc_MemoryError,
1223 "Not enough memory to allocate new values array");
1224 return NULL;
1225 }
1226 for (i = 0; i < size; i++) {
1227 values[i] = ep0[i].me_value;
1228 ep0[i].me_value = NULL;
1229 }
1230 mp->ma_keys->dk_lookup = lookdict_split;
1231 mp->ma_values = values;
1232 }
1233 DK_INCREF(mp->ma_keys);
1234 return mp->ma_keys;
1235}
Christian Heimes99170a52007-12-19 02:07:34 +00001236
1237PyObject *
1238_PyDict_NewPresized(Py_ssize_t minused)
1239{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001240 Py_ssize_t newsize;
1241 PyDictKeysObject *new_keys;
Victor Stinner742da042016-09-07 17:40:12 -07001242 for (newsize = PyDict_MINSIZE;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001243 newsize <= minused && newsize > 0;
1244 newsize <<= 1)
1245 ;
1246 new_keys = new_keys_object(newsize);
1247 if (new_keys == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001249 return new_dict(new_keys, NULL);
Christian Heimes99170a52007-12-19 02:07:34 +00001250}
1251
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001252/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
1253 * that may occur (originally dicts supported only string keys, and exceptions
1254 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001255 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001256 * (suppressed) occurred while computing the key's hash, or that some error
1257 * (suppressed) occurred when comparing keys in the dict's internal probe
1258 * sequence. A nasty example of the latter is when a Python-coded comparison
1259 * function hits a stack-depth error, which can cause this to return NULL
1260 * even if the key is present.
1261 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001262PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001263PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001264{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001265 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001266 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 PyDictObject *mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 PyThreadState *tstate;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001269 PyObject **value_addr;
1270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 if (!PyDict_Check(op))
1272 return NULL;
1273 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001274 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 {
1276 hash = PyObject_Hash(key);
1277 if (hash == -1) {
1278 PyErr_Clear();
1279 return NULL;
1280 }
1281 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 /* We can arrive here with a NULL tstate during initialization: try
1284 running "python -Wi" for an example related to string interning.
1285 Let's just hope that no exception occurs then... This must be
1286 _PyThreadState_Current and not PyThreadState_GET() because in debug
1287 mode, the latter complains if tstate is NULL. */
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001288 tstate = _PyThreadState_UncheckedGet();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 if (tstate != NULL && tstate->curexc_type != NULL) {
1290 /* preserve the existing exception */
1291 PyObject *err_type, *err_value, *err_tb;
1292 PyErr_Fetch(&err_type, &err_value, &err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001293 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 /* ignore errors */
1295 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001296 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 return NULL;
1298 }
1299 else {
Victor Stinner742da042016-09-07 17:40:12 -07001300 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1301 if (ix < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 PyErr_Clear();
1303 return NULL;
1304 }
1305 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001306 return *value_addr;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001307}
1308
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001309PyObject *
1310_PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1311{
Victor Stinner742da042016-09-07 17:40:12 -07001312 Py_ssize_t ix;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001313 PyDictObject *mp = (PyDictObject *)op;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001314 PyThreadState *tstate;
1315 PyObject **value_addr;
1316
1317 if (!PyDict_Check(op))
1318 return NULL;
1319
1320 /* We can arrive here with a NULL tstate during initialization: try
1321 running "python -Wi" for an example related to string interning.
1322 Let's just hope that no exception occurs then... This must be
1323 _PyThreadState_Current and not PyThreadState_GET() because in debug
1324 mode, the latter complains if tstate is NULL. */
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001325 tstate = _PyThreadState_UncheckedGet();
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001326 if (tstate != NULL && tstate->curexc_type != NULL) {
1327 /* preserve the existing exception */
1328 PyObject *err_type, *err_value, *err_tb;
1329 PyErr_Fetch(&err_type, &err_value, &err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001330 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001331 /* ignore errors */
1332 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001333 if (ix == DKIX_EMPTY)
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001334 return NULL;
1335 }
1336 else {
Victor Stinner742da042016-09-07 17:40:12 -07001337 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1338 if (ix == DKIX_EMPTY) {
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001339 PyErr_Clear();
1340 return NULL;
1341 }
1342 }
1343 return *value_addr;
1344}
1345
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001346/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
1347 This returns NULL *with* an exception set if an exception occurred.
1348 It returns NULL *without* an exception set if the key wasn't present.
1349*/
1350PyObject *
1351PyDict_GetItemWithError(PyObject *op, PyObject *key)
1352{
Victor Stinner742da042016-09-07 17:40:12 -07001353 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001354 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 PyDictObject*mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001356 PyObject **value_addr;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 if (!PyDict_Check(op)) {
1359 PyErr_BadInternalCall();
1360 return NULL;
1361 }
1362 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001363 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 {
1365 hash = PyObject_Hash(key);
1366 if (hash == -1) {
1367 return NULL;
1368 }
1369 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001370
Victor Stinner742da042016-09-07 17:40:12 -07001371 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1372 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001374 return *value_addr;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001375}
1376
Brett Cannonfd074152012-04-14 14:10:13 -04001377PyObject *
1378_PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
1379{
1380 PyObject *kv;
1381 kv = _PyUnicode_FromId(key); /* borrowed */
1382 if (kv == NULL)
1383 return NULL;
1384 return PyDict_GetItemWithError(dp, kv);
1385}
1386
Victor Stinnerb4efc962015-11-20 09:24:02 +01001387/* Fast version of global value lookup (LOAD_GLOBAL).
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001388 * Lookup in globals, then builtins.
Victor Stinnerb4efc962015-11-20 09:24:02 +01001389 *
1390 * Raise an exception and return NULL if an error occurred (ex: computing the
1391 * key hash failed, key comparison failed, ...). Return NULL if the key doesn't
1392 * exist. Return the value if the key exists.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001393 */
1394PyObject *
1395_PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001396{
Victor Stinner742da042016-09-07 17:40:12 -07001397 Py_ssize_t ix;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001398 Py_hash_t hash;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001399 PyObject **value_addr;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001400
1401 if (!PyUnicode_CheckExact(key) ||
1402 (hash = ((PyASCIIObject *) key)->hash) == -1)
1403 {
1404 hash = PyObject_Hash(key);
1405 if (hash == -1)
1406 return NULL;
Antoine Pitroue965d972012-02-27 00:45:12 +01001407 }
Victor Stinnerb4efc962015-11-20 09:24:02 +01001408
1409 /* namespace 1: globals */
Victor Stinner742da042016-09-07 17:40:12 -07001410 ix = globals->ma_keys->dk_lookup(globals, key, hash, &value_addr, NULL);
1411 if (ix == DKIX_ERROR)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001412 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001413 if (ix != DKIX_EMPTY && *value_addr != NULL)
1414 return *value_addr;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001415
1416 /* namespace 2: builtins */
Victor Stinner742da042016-09-07 17:40:12 -07001417 ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value_addr, NULL);
1418 if (ix < 0)
Victor Stinnerb4efc962015-11-20 09:24:02 +01001419 return NULL;
1420 return *value_addr;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001421}
1422
Antoine Pitroue965d972012-02-27 00:45:12 +01001423/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
1424 * dictionary if it's merely replacing the value for an existing key.
1425 * This means that it's safe to loop over a dictionary with PyDict_Next()
1426 * and occasionally replace a value -- but you can't insert new keys or
1427 * remove them.
1428 */
1429int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001430PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001431{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001432 PyDictObject *mp;
1433 Py_hash_t hash;
Antoine Pitroue965d972012-02-27 00:45:12 +01001434 if (!PyDict_Check(op)) {
1435 PyErr_BadInternalCall();
1436 return -1;
1437 }
1438 assert(key);
1439 assert(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001440 mp = (PyDictObject *)op;
1441 if (!PyUnicode_CheckExact(key) ||
1442 (hash = ((PyASCIIObject *) key)->hash) == -1)
1443 {
Antoine Pitroue965d972012-02-27 00:45:12 +01001444 hash = PyObject_Hash(key);
1445 if (hash == -1)
1446 return -1;
1447 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001448
1449 /* insertdict() handles any resizing that might be necessary */
1450 return insertdict(mp, key, hash, value);
Antoine Pitroue965d972012-02-27 00:45:12 +01001451}
1452
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001453int
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001454_PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
1455 Py_hash_t hash)
1456{
1457 PyDictObject *mp;
1458
1459 if (!PyDict_Check(op)) {
1460 PyErr_BadInternalCall();
1461 return -1;
1462 }
1463 assert(key);
1464 assert(value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001465 assert(hash != -1);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001466 mp = (PyDictObject *)op;
1467
1468 /* insertdict() handles any resizing that might be necessary */
1469 return insertdict(mp, key, hash, value);
1470}
1471
1472int
Tim Peters1f5871e2000-07-04 17:44:48 +00001473PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001474{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001475 Py_hash_t hash;
Guido van Rossumd7047b31995-01-02 19:07:15 +00001476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 assert(key);
1478 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001479 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 hash = PyObject_Hash(key);
1481 if (hash == -1)
1482 return -1;
1483 }
Victor Stinner742da042016-09-07 17:40:12 -07001484
1485 return _PyDict_DelItem_KnownHash(op, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001486}
1487
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001488int
1489_PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1490{
Victor Stinner742da042016-09-07 17:40:12 -07001491 Py_ssize_t hashpos, ix;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001492 PyDictObject *mp;
1493 PyDictKeyEntry *ep;
1494 PyObject *old_key, *old_value;
1495 PyObject **value_addr;
1496
1497 if (!PyDict_Check(op)) {
1498 PyErr_BadInternalCall();
1499 return -1;
1500 }
1501 assert(key);
1502 assert(hash != -1);
1503 mp = (PyDictObject *)op;
Victor Stinner742da042016-09-07 17:40:12 -07001504 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1505 if (ix == DKIX_ERROR)
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001506 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07001507 if (ix == DKIX_EMPTY || *value_addr == NULL) {
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001508 _PyErr_SetKeyError(key);
1509 return -1;
1510 }
Victor Stinner742da042016-09-07 17:40:12 -07001511 assert(dk_get_index(mp->ma_keys, hashpos) == ix);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001512 old_value = *value_addr;
1513 *value_addr = NULL;
1514 mp->ma_used--;
Victor Stinner742da042016-09-07 17:40:12 -07001515 if (_PyDict_HasSplitTable(mp)) {
1516 mp->ma_keys->dk_usable = 0;
1517 }
1518 else {
1519 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1520 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001521 ENSURE_ALLOWS_DELETIONS(mp);
1522 old_key = ep->me_key;
Victor Stinner742da042016-09-07 17:40:12 -07001523 ep->me_key = NULL;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001524 Py_DECREF(old_key);
1525 }
1526 Py_DECREF(old_value);
1527 return 0;
1528}
1529
Guido van Rossum25831651993-05-19 14:50:45 +00001530void
Tim Peters1f5871e2000-07-04 17:44:48 +00001531PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 PyDictObject *mp;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001534 PyDictKeysObject *oldkeys;
1535 PyObject **oldvalues;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 if (!PyDict_Check(op))
1539 return;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001540 mp = ((PyDictObject *)op);
1541 oldkeys = mp->ma_keys;
1542 oldvalues = mp->ma_values;
1543 if (oldvalues == empty_values)
1544 return;
1545 /* Empty the dict... */
1546 DK_INCREF(Py_EMPTY_KEYS);
1547 mp->ma_keys = Py_EMPTY_KEYS;
1548 mp->ma_values = empty_values;
1549 mp->ma_used = 0;
1550 /* ...then clear the keys and values */
1551 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001552 n = oldkeys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001553 for (i = 0; i < n; i++)
1554 Py_CLEAR(oldvalues[i]);
1555 free_values(oldvalues);
1556 DK_DECREF(oldkeys);
1557 }
1558 else {
1559 assert(oldkeys->dk_refcnt == 1);
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001560 DK_DECREF(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001561 }
1562}
1563
1564/* Returns -1 if no more items (or op is not a dict),
1565 * index of item otherwise. Stores value in pvalue
1566 */
1567Py_LOCAL_INLINE(Py_ssize_t)
1568dict_next(PyObject *op, Py_ssize_t i, PyObject **pvalue)
1569{
Victor Stinner742da042016-09-07 17:40:12 -07001570 Py_ssize_t n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001571 PyDictObject *mp;
Victor Stinner742da042016-09-07 17:40:12 -07001572 PyObject **value_ptr = NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001573
1574 if (!PyDict_Check(op))
1575 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001577 if (i < 0)
1578 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07001579
1580 n = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001581 if (mp->ma_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001582 for (; i < n; i++) {
1583 value_ptr = &mp->ma_values[i];
1584 if (*value_ptr != NULL)
1585 break;
1586 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001588 else {
Victor Stinner742da042016-09-07 17:40:12 -07001589 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
1590 for (; i < n; i++) {
1591 value_ptr = &ep0[i].me_value;
1592 if (*value_ptr != NULL)
1593 break;
1594 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 }
Victor Stinner742da042016-09-07 17:40:12 -07001596 if (i >= n)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001597 return -1;
1598 if (pvalue)
1599 *pvalue = *value_ptr;
1600 return i;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001601}
1602
Tim Peters080c88b2003-02-15 03:01:11 +00001603/*
1604 * Iterate over a dict. Use like so:
1605 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001606 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +00001607 * PyObject *key, *value;
1608 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +00001609 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Tim Peters080c88b2003-02-15 03:01:11 +00001610 * Refer to borrowed references in key and value.
1611 * }
1612 *
1613 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +00001614 * mutates the dict. One exception: it is safe if the loop merely changes
1615 * the values associated with the keys (but doesn't insert new keys or
1616 * delete keys), via PyDict_SetItem().
1617 */
Guido van Rossum25831651993-05-19 14:50:45 +00001618int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001619PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001620{
Victor Stinner742da042016-09-07 17:40:12 -07001621 PyDictObject *mp = (PyDictObject*)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001622 Py_ssize_t i = dict_next(op, *ppos, pvalue);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 if (i < 0)
1624 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001625 mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 *ppos = i+1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 if (pkey)
Victor Stinner742da042016-09-07 17:40:12 -07001628 *pkey = DK_ENTRIES(mp->ma_keys)[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001630}
1631
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001632/* Internal version of PyDict_Next that returns a hash value in addition
1633 * to the key and value.
1634 */
Thomas Wouterscf297e42007-02-23 15:07:44 +00001635int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001636_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
1637 PyObject **pvalue, Py_hash_t *phash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001638{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001639 PyDictObject *mp;
Victor Stinner742da042016-09-07 17:40:12 -07001640 PyDictKeyEntry *ep0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001641 Py_ssize_t i = dict_next(op, *ppos, pvalue);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 if (i < 0)
1643 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001644 mp = (PyDictObject *)op;
Victor Stinner742da042016-09-07 17:40:12 -07001645 ep0 = DK_ENTRIES(mp->ma_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 *ppos = i+1;
Victor Stinner742da042016-09-07 17:40:12 -07001647 *phash = ep0[i].me_hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 if (pkey)
Victor Stinner742da042016-09-07 17:40:12 -07001649 *pkey = ep0[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 return 1;
Thomas Wouterscf297e42007-02-23 15:07:44 +00001651}
1652
Eric Snow96c6af92015-05-29 22:21:39 -06001653/* Internal version of dict.pop(). */
1654PyObject *
1655_PyDict_Pop(PyDictObject *mp, PyObject *key, PyObject *deflt)
1656{
1657 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001658 Py_ssize_t ix, hashpos;
Eric Snow96c6af92015-05-29 22:21:39 -06001659 PyObject *old_value, *old_key;
1660 PyDictKeyEntry *ep;
1661 PyObject **value_addr;
1662
1663 if (mp->ma_used == 0) {
1664 if (deflt) {
1665 Py_INCREF(deflt);
1666 return deflt;
1667 }
1668 _PyErr_SetKeyError(key);
1669 return NULL;
1670 }
1671 if (!PyUnicode_CheckExact(key) ||
1672 (hash = ((PyASCIIObject *) key)->hash) == -1) {
1673 hash = PyObject_Hash(key);
1674 if (hash == -1)
1675 return NULL;
1676 }
Victor Stinner742da042016-09-07 17:40:12 -07001677 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1678 if (ix == DKIX_ERROR)
Eric Snow96c6af92015-05-29 22:21:39 -06001679 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001680 if (ix == DKIX_EMPTY) {
Eric Snow96c6af92015-05-29 22:21:39 -06001681 if (deflt) {
1682 Py_INCREF(deflt);
1683 return deflt;
1684 }
1685 _PyErr_SetKeyError(key);
1686 return NULL;
1687 }
Victor Stinner742da042016-09-07 17:40:12 -07001688 old_value = *value_addr;
Eric Snow96c6af92015-05-29 22:21:39 -06001689 *value_addr = NULL;
1690 mp->ma_used--;
1691 if (!_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -07001692 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1693 ep = &DK_ENTRIES(mp->ma_keys)[ix];
Eric Snow96c6af92015-05-29 22:21:39 -06001694 ENSURE_ALLOWS_DELETIONS(mp);
1695 old_key = ep->me_key;
Victor Stinner742da042016-09-07 17:40:12 -07001696 ep->me_key = NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06001697 Py_DECREF(old_key);
1698 }
1699 return old_value;
1700}
1701
1702/* Internal version of dict.from_keys(). It is subclass-friendly. */
1703PyObject *
1704_PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
1705{
1706 PyObject *it; /* iter(iterable) */
1707 PyObject *key;
1708 PyObject *d;
1709 int status;
1710
1711 d = PyObject_CallObject(cls, NULL);
1712 if (d == NULL)
1713 return NULL;
1714
1715 if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
1716 if (PyDict_CheckExact(iterable)) {
1717 PyDictObject *mp = (PyDictObject *)d;
1718 PyObject *oldvalue;
1719 Py_ssize_t pos = 0;
1720 PyObject *key;
1721 Py_hash_t hash;
1722
Victor Stinner742da042016-09-07 17:40:12 -07001723 if (dictresize(mp, ESTIMATE_SIZE(Py_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001724 Py_DECREF(d);
1725 return NULL;
1726 }
1727
1728 while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
1729 if (insertdict(mp, key, hash, value)) {
1730 Py_DECREF(d);
1731 return NULL;
1732 }
1733 }
1734 return d;
1735 }
1736 if (PyAnySet_CheckExact(iterable)) {
1737 PyDictObject *mp = (PyDictObject *)d;
1738 Py_ssize_t pos = 0;
1739 PyObject *key;
1740 Py_hash_t hash;
1741
Victor Stinner742da042016-09-07 17:40:12 -07001742 if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001743 Py_DECREF(d);
1744 return NULL;
1745 }
1746
1747 while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
1748 if (insertdict(mp, key, hash, value)) {
1749 Py_DECREF(d);
1750 return NULL;
1751 }
1752 }
1753 return d;
1754 }
1755 }
1756
1757 it = PyObject_GetIter(iterable);
1758 if (it == NULL){
1759 Py_DECREF(d);
1760 return NULL;
1761 }
1762
1763 if (PyDict_CheckExact(d)) {
1764 while ((key = PyIter_Next(it)) != NULL) {
1765 status = PyDict_SetItem(d, key, value);
1766 Py_DECREF(key);
1767 if (status < 0)
1768 goto Fail;
1769 }
1770 } else {
1771 while ((key = PyIter_Next(it)) != NULL) {
1772 status = PyObject_SetItem(d, key, value);
1773 Py_DECREF(key);
1774 if (status < 0)
1775 goto Fail;
1776 }
1777 }
1778
1779 if (PyErr_Occurred())
1780 goto Fail;
1781 Py_DECREF(it);
1782 return d;
1783
1784Fail:
1785 Py_DECREF(it);
1786 Py_DECREF(d);
1787 return NULL;
1788}
1789
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001790/* Methods */
1791
1792static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001793dict_dealloc(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001794{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001795 PyObject **values = mp->ma_values;
1796 PyDictKeysObject *keys = mp->ma_keys;
1797 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 PyObject_GC_UnTrack(mp);
1799 Py_TRASHCAN_SAFE_BEGIN(mp)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001800 if (values != NULL) {
1801 if (values != empty_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001802 for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001803 Py_XDECREF(values[i]);
1804 }
1805 free_values(values);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001807 DK_DECREF(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 }
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02001809 else if (keys != NULL) {
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001810 assert(keys->dk_refcnt == 1);
1811 DK_DECREF(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001812 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
1814 free_list[numfree++] = mp;
1815 else
1816 Py_TYPE(mp)->tp_free((PyObject *)mp);
1817 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001818}
1819
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001820
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001821static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001822dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 Py_ssize_t i;
Victor Stinnerf91929b2013-11-19 13:07:38 +01001825 PyObject *key = NULL, *value = NULL;
1826 _PyUnicodeWriter writer;
1827 int first;
Guido van Rossum255443b1998-04-10 22:47:14 +00001828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 i = Py_ReprEnter((PyObject *)mp);
1830 if (i != 0) {
1831 return i > 0 ? PyUnicode_FromString("{...}") : NULL;
1832 }
Guido van Rossum255443b1998-04-10 22:47:14 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 if (mp->ma_used == 0) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01001835 Py_ReprLeave((PyObject *)mp);
1836 return PyUnicode_FromString("{}");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 }
Tim Petersa7259592001-06-16 05:11:17 +00001838
Victor Stinnerf91929b2013-11-19 13:07:38 +01001839 _PyUnicodeWriter_Init(&writer);
1840 writer.overallocate = 1;
1841 /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
1842 writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +00001843
Victor Stinnerf91929b2013-11-19 13:07:38 +01001844 if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
1845 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00001846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 /* Do repr() on each key+value pair, and insert ": " between them.
1848 Note that repr may mutate the dict. */
1849 i = 0;
Victor Stinnerf91929b2013-11-19 13:07:38 +01001850 first = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01001852 PyObject *s;
1853 int res;
1854
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001855 /* Prevent repr from deleting key or value during key format. */
1856 Py_INCREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 Py_INCREF(value);
Victor Stinnerf97dfd72013-07-18 01:00:45 +02001858
Victor Stinnerf91929b2013-11-19 13:07:38 +01001859 if (!first) {
1860 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
1861 goto error;
1862 }
1863 first = 0;
1864
1865 s = PyObject_Repr(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 if (s == NULL)
Victor Stinnerf91929b2013-11-19 13:07:38 +01001867 goto error;
1868 res = _PyUnicodeWriter_WriteStr(&writer, s);
1869 Py_DECREF(s);
1870 if (res < 0)
1871 goto error;
1872
1873 if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
1874 goto error;
1875
1876 s = PyObject_Repr(value);
1877 if (s == NULL)
1878 goto error;
1879 res = _PyUnicodeWriter_WriteStr(&writer, s);
1880 Py_DECREF(s);
1881 if (res < 0)
1882 goto error;
1883
1884 Py_CLEAR(key);
1885 Py_CLEAR(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 }
Tim Petersa7259592001-06-16 05:11:17 +00001887
Victor Stinnerf91929b2013-11-19 13:07:38 +01001888 writer.overallocate = 0;
1889 if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
1890 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 Py_ReprLeave((PyObject *)mp);
Victor Stinnerf91929b2013-11-19 13:07:38 +01001893
1894 return _PyUnicodeWriter_Finish(&writer);
1895
1896error:
1897 Py_ReprLeave((PyObject *)mp);
1898 _PyUnicodeWriter_Dealloc(&writer);
1899 Py_XDECREF(key);
1900 Py_XDECREF(value);
1901 return NULL;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001902}
1903
Martin v. Löwis18e16552006-02-15 17:27:45 +00001904static Py_ssize_t
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001905dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001906{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 return mp->ma_used;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001908}
1909
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001910static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001911dict_subscript(PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 PyObject *v;
Victor Stinner742da042016-09-07 17:40:12 -07001914 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001915 Py_hash_t hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001916 PyObject **value_addr;
1917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001919 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 hash = PyObject_Hash(key);
1921 if (hash == -1)
1922 return NULL;
1923 }
Victor Stinner742da042016-09-07 17:40:12 -07001924 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1925 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001927 if (ix == DKIX_EMPTY || *value_addr == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 if (!PyDict_CheckExact(mp)) {
1929 /* Look up __missing__ method if we're a subclass. */
1930 PyObject *missing, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05001931 _Py_IDENTIFIER(__missing__);
1932 missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 if (missing != NULL) {
1934 res = PyObject_CallFunctionObjArgs(missing,
1935 key, NULL);
1936 Py_DECREF(missing);
1937 return res;
1938 }
1939 else if (PyErr_Occurred())
1940 return NULL;
1941 }
Raymond Hettinger69492da2013-09-02 15:59:26 -07001942 _PyErr_SetKeyError(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 return NULL;
1944 }
Victor Stinner742da042016-09-07 17:40:12 -07001945 v = *value_addr;
1946 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001948}
1949
1950static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001951dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 if (w == NULL)
1954 return PyDict_DelItem((PyObject *)mp, v);
1955 else
1956 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001957}
1958
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001959static PyMappingMethods dict_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 (lenfunc)dict_length, /*mp_length*/
1961 (binaryfunc)dict_subscript, /*mp_subscript*/
1962 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001963};
1964
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001965static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001966dict_keys(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001967{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001968 PyObject *v;
1969 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001970 PyDictKeyEntry *ep;
1971 Py_ssize_t size, n, offset;
1972 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001973
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001974 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 n = mp->ma_used;
1976 v = PyList_New(n);
1977 if (v == NULL)
1978 return NULL;
1979 if (n != mp->ma_used) {
1980 /* Durnit. The allocations caused the dict to resize.
1981 * Just start over, this shouldn't normally happen.
1982 */
1983 Py_DECREF(v);
1984 goto again;
1985 }
Victor Stinner742da042016-09-07 17:40:12 -07001986 ep = DK_ENTRIES(mp->ma_keys);
1987 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001988 if (mp->ma_values) {
1989 value_ptr = mp->ma_values;
1990 offset = sizeof(PyObject *);
1991 }
1992 else {
1993 value_ptr = &ep[0].me_value;
1994 offset = sizeof(PyDictKeyEntry);
1995 }
1996 for (i = 0, j = 0; i < size; i++) {
1997 if (*value_ptr != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 PyObject *key = ep[i].me_key;
1999 Py_INCREF(key);
2000 PyList_SET_ITEM(v, j, key);
2001 j++;
2002 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002003 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 }
2005 assert(j == n);
2006 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002007}
2008
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002009static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002010dict_values(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002011{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002012 PyObject *v;
2013 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002014 Py_ssize_t size, n, offset;
2015 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002016
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002017 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 n = mp->ma_used;
2019 v = PyList_New(n);
2020 if (v == NULL)
2021 return NULL;
2022 if (n != mp->ma_used) {
2023 /* Durnit. The allocations caused the dict to resize.
2024 * Just start over, this shouldn't normally happen.
2025 */
2026 Py_DECREF(v);
2027 goto again;
2028 }
Victor Stinner742da042016-09-07 17:40:12 -07002029 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002030 if (mp->ma_values) {
2031 value_ptr = mp->ma_values;
2032 offset = sizeof(PyObject *);
2033 }
2034 else {
Victor Stinner742da042016-09-07 17:40:12 -07002035 value_ptr = &(DK_ENTRIES(mp->ma_keys)[0].me_value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002036 offset = sizeof(PyDictKeyEntry);
2037 }
2038 for (i = 0, j = 0; i < size; i++) {
2039 PyObject *value = *value_ptr;
2040 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2041 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 Py_INCREF(value);
2043 PyList_SET_ITEM(v, j, value);
2044 j++;
2045 }
2046 }
2047 assert(j == n);
2048 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002049}
2050
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002051static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002052dict_items(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002053{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002054 PyObject *v;
2055 Py_ssize_t i, j, n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002056 Py_ssize_t size, offset;
2057 PyObject *item, *key;
2058 PyDictKeyEntry *ep;
2059 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 /* Preallocate the list of tuples, to avoid allocations during
2062 * the loop over the items, which could trigger GC, which
2063 * could resize the dict. :-(
2064 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002065 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 n = mp->ma_used;
2067 v = PyList_New(n);
2068 if (v == NULL)
2069 return NULL;
2070 for (i = 0; i < n; i++) {
2071 item = PyTuple_New(2);
2072 if (item == NULL) {
2073 Py_DECREF(v);
2074 return NULL;
2075 }
2076 PyList_SET_ITEM(v, i, item);
2077 }
2078 if (n != mp->ma_used) {
2079 /* Durnit. The allocations caused the dict to resize.
2080 * Just start over, this shouldn't normally happen.
2081 */
2082 Py_DECREF(v);
2083 goto again;
2084 }
2085 /* Nothing we do below makes any function calls. */
Victor Stinner742da042016-09-07 17:40:12 -07002086 ep = DK_ENTRIES(mp->ma_keys);
2087 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002088 if (mp->ma_values) {
2089 value_ptr = mp->ma_values;
2090 offset = sizeof(PyObject *);
2091 }
2092 else {
2093 value_ptr = &ep[0].me_value;
2094 offset = sizeof(PyDictKeyEntry);
2095 }
2096 for (i = 0, j = 0; i < size; i++) {
2097 PyObject *value = *value_ptr;
2098 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2099 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 key = ep[i].me_key;
2101 item = PyList_GET_ITEM(v, j);
2102 Py_INCREF(key);
2103 PyTuple_SET_ITEM(item, 0, key);
2104 Py_INCREF(value);
2105 PyTuple_SET_ITEM(item, 1, value);
2106 j++;
2107 }
2108 }
2109 assert(j == n);
2110 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002111}
2112
Larry Hastings5c661892014-01-24 06:17:25 -08002113/*[clinic input]
2114@classmethod
2115dict.fromkeys
Larry Hastings5c661892014-01-24 06:17:25 -08002116 iterable: object
2117 value: object=None
2118 /
2119
2120Returns a new dict with keys from iterable and values equal to value.
2121[clinic start generated code]*/
2122
Larry Hastings5c661892014-01-24 06:17:25 -08002123static PyObject *
2124dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002125/*[clinic end generated code: output=8fb98e4b10384999 input=b85a667f9bf4669d]*/
Larry Hastings5c661892014-01-24 06:17:25 -08002126{
Eric Snow96c6af92015-05-29 22:21:39 -06002127 return _PyDict_FromKeys((PyObject *)type, iterable, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002128}
2129
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002130static int
Victor Stinner742da042016-09-07 17:40:12 -07002131dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
2132 const char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 PyObject *arg = NULL;
2135 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
2138 result = -1;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 else if (arg != NULL) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02002141 _Py_IDENTIFIER(keys);
2142 if (_PyObject_HasAttrId(arg, &PyId_keys))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 result = PyDict_Merge(self, arg, 1);
2144 else
2145 result = PyDict_MergeFromSeq2(self, arg, 1);
2146 }
2147 if (result == 0 && kwds != NULL) {
2148 if (PyArg_ValidateKeywordArguments(kwds))
2149 result = PyDict_Merge(self, kwds, 1);
2150 else
2151 result = -1;
2152 }
2153 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002154}
2155
2156static PyObject *
2157dict_update(PyObject *self, PyObject *args, PyObject *kwds)
2158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 if (dict_update_common(self, args, kwds, "update") != -1)
2160 Py_RETURN_NONE;
2161 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002162}
2163
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002164/* Update unconditionally replaces existing items.
2165 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00002166 otherwise it leaves existing items unchanged.
2167
2168 PyDict_{Update,Merge} update/merge from a mapping object.
2169
Tim Petersf582b822001-12-11 18:51:08 +00002170 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00002171 producing iterable objects of length 2.
2172*/
2173
Tim Petersf582b822001-12-11 18:51:08 +00002174int
Tim Peters1fc240e2001-10-26 05:06:50 +00002175PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
2176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 PyObject *it; /* iter(seq2) */
2178 Py_ssize_t i; /* index into seq2 of current element */
2179 PyObject *item; /* seq2[i] */
2180 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 assert(d != NULL);
2183 assert(PyDict_Check(d));
2184 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00002185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 it = PyObject_GetIter(seq2);
2187 if (it == NULL)
2188 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 for (i = 0; ; ++i) {
2191 PyObject *key, *value;
2192 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00002193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 fast = NULL;
2195 item = PyIter_Next(it);
2196 if (item == NULL) {
2197 if (PyErr_Occurred())
2198 goto Fail;
2199 break;
2200 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 /* Convert item to sequence, and verify length 2. */
2203 fast = PySequence_Fast(item, "");
2204 if (fast == NULL) {
2205 if (PyErr_ExceptionMatches(PyExc_TypeError))
2206 PyErr_Format(PyExc_TypeError,
2207 "cannot convert dictionary update "
2208 "sequence element #%zd to a sequence",
2209 i);
2210 goto Fail;
2211 }
2212 n = PySequence_Fast_GET_SIZE(fast);
2213 if (n != 2) {
2214 PyErr_Format(PyExc_ValueError,
2215 "dictionary update sequence element #%zd "
2216 "has length %zd; 2 is required",
2217 i, n);
2218 goto Fail;
2219 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 /* Update/merge with this (key, value) pair. */
2222 key = PySequence_Fast_GET_ITEM(fast, 0);
2223 value = PySequence_Fast_GET_ITEM(fast, 1);
2224 if (override || PyDict_GetItem(d, key) == NULL) {
2225 int status = PyDict_SetItem(d, key, value);
2226 if (status < 0)
2227 goto Fail;
2228 }
2229 Py_DECREF(fast);
2230 Py_DECREF(item);
2231 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 i = 0;
2234 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00002235Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 Py_XDECREF(item);
2237 Py_XDECREF(fast);
2238 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002239Return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 Py_DECREF(it);
2241 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00002242}
2243
Tim Peters6d6c1a32001-08-02 04:15:00 +00002244int
2245PyDict_Update(PyObject *a, PyObject *b)
2246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 return PyDict_Merge(a, b, 1);
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002248}
2249
2250int
2251PyDict_Merge(PyObject *a, PyObject *b, int override)
2252{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002253 PyDictObject *mp, *other;
2254 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -07002255 PyDictKeyEntry *entry, *ep0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 /* We accept for the argument either a concrete dictionary object,
2258 * or an abstract "mapping" object. For the former, we can do
2259 * things quite efficiently. For the latter, we only require that
2260 * PyMapping_Keys() and PyObject_GetItem() be supported.
2261 */
2262 if (a == NULL || !PyDict_Check(a) || b == NULL) {
2263 PyErr_BadInternalCall();
2264 return -1;
2265 }
2266 mp = (PyDictObject*)a;
2267 if (PyDict_Check(b)) {
2268 other = (PyDictObject*)b;
2269 if (other == mp || other->ma_used == 0)
2270 /* a.update(a) or a.update({}); nothing to do */
2271 return 0;
2272 if (mp->ma_used == 0)
2273 /* Since the target dict is empty, PyDict_GetItem()
2274 * always returns NULL. Setting override to 1
2275 * skips the unnecessary test.
2276 */
2277 override = 1;
2278 /* Do one big resize at the start, rather than
2279 * incrementally resizing as we insert new items. Expect
2280 * that there will be no (or few) overlapping keys.
2281 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002282 if (mp->ma_keys->dk_usable * 3 < other->ma_used * 2)
2283 if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07002285 ep0 = DK_ENTRIES(other->ma_keys);
2286 for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002287 PyObject *key, *value;
2288 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002289 entry = &ep0[i];
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002290 key = entry->me_key;
2291 hash = entry->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002292 if (other->ma_values)
2293 value = other->ma_values[i];
2294 else
2295 value = entry->me_value;
2296
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002297 if (value != NULL) {
2298 int err = 0;
2299 Py_INCREF(key);
2300 Py_INCREF(value);
2301 if (override || PyDict_GetItem(a, key) == NULL)
2302 err = insertdict(mp, key, hash, value);
2303 Py_DECREF(value);
2304 Py_DECREF(key);
2305 if (err != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 return -1;
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002307
Victor Stinner742da042016-09-07 17:40:12 -07002308 if (n != other->ma_keys->dk_nentries) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002309 PyErr_SetString(PyExc_RuntimeError,
2310 "dict mutated during update");
2311 return -1;
2312 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 }
2314 }
2315 }
2316 else {
2317 /* Do it the generic, slower way */
2318 PyObject *keys = PyMapping_Keys(b);
2319 PyObject *iter;
2320 PyObject *key, *value;
2321 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 if (keys == NULL)
2324 /* Docstring says this is equivalent to E.keys() so
2325 * if E doesn't have a .keys() method we want
2326 * AttributeError to percolate up. Might as well
2327 * do the same for any other error.
2328 */
2329 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 iter = PyObject_GetIter(keys);
2332 Py_DECREF(keys);
2333 if (iter == NULL)
2334 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
2337 if (!override && PyDict_GetItem(a, key) != NULL) {
2338 Py_DECREF(key);
2339 continue;
2340 }
2341 value = PyObject_GetItem(b, key);
2342 if (value == NULL) {
2343 Py_DECREF(iter);
2344 Py_DECREF(key);
2345 return -1;
2346 }
2347 status = PyDict_SetItem(a, key, value);
2348 Py_DECREF(key);
2349 Py_DECREF(value);
2350 if (status < 0) {
2351 Py_DECREF(iter);
2352 return -1;
2353 }
2354 }
2355 Py_DECREF(iter);
2356 if (PyErr_Occurred())
2357 /* Iterator completed, via error */
2358 return -1;
2359 }
2360 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002361}
2362
2363static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002364dict_copy(PyDictObject *mp)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002367}
2368
2369PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002370PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 PyObject *copy;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002373 PyDictObject *mp;
2374 Py_ssize_t i, n;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 if (o == NULL || !PyDict_Check(o)) {
2377 PyErr_BadInternalCall();
2378 return NULL;
2379 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002380 mp = (PyDictObject *)o;
2381 if (_PyDict_HasSplitTable(mp)) {
2382 PyDictObject *split_copy;
Victor Stinner742da042016-09-07 17:40:12 -07002383 Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
2384 PyObject **newvalues;
2385 newvalues = new_values(size);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002386 if (newvalues == NULL)
2387 return PyErr_NoMemory();
2388 split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
2389 if (split_copy == NULL) {
2390 free_values(newvalues);
2391 return NULL;
2392 }
2393 split_copy->ma_values = newvalues;
2394 split_copy->ma_keys = mp->ma_keys;
2395 split_copy->ma_used = mp->ma_used;
2396 DK_INCREF(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002397 for (i = 0, n = size; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002398 PyObject *value = mp->ma_values[i];
2399 Py_XINCREF(value);
2400 split_copy->ma_values[i] = value;
2401 }
Benjamin Peterson7ce67e42012-04-24 10:32:57 -04002402 if (_PyObject_GC_IS_TRACKED(mp))
2403 _PyObject_GC_TRACK(split_copy);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002404 return (PyObject *)split_copy;
2405 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 copy = PyDict_New();
2407 if (copy == NULL)
2408 return NULL;
2409 if (PyDict_Merge(copy, o, 1) == 0)
2410 return copy;
2411 Py_DECREF(copy);
2412 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002413}
2414
Martin v. Löwis18e16552006-02-15 17:27:45 +00002415Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00002416PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00002417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 if (mp == NULL || !PyDict_Check(mp)) {
2419 PyErr_BadInternalCall();
2420 return -1;
2421 }
2422 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00002423}
2424
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002425PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002426PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 if (mp == NULL || !PyDict_Check(mp)) {
2429 PyErr_BadInternalCall();
2430 return NULL;
2431 }
2432 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002433}
2434
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002435PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002436PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 if (mp == NULL || !PyDict_Check(mp)) {
2439 PyErr_BadInternalCall();
2440 return NULL;
2441 }
2442 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002443}
2444
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002445PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002446PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 if (mp == NULL || !PyDict_Check(mp)) {
2449 PyErr_BadInternalCall();
2450 return NULL;
2451 }
2452 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002453}
2454
Tim Peterse63415e2001-05-08 04:38:29 +00002455/* Return 1 if dicts equal, 0 if not, -1 if error.
2456 * Gets out as soon as any difference is detected.
2457 * Uses only Py_EQ comparison.
2458 */
2459static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002460dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00002461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 if (a->ma_used != b->ma_used)
2465 /* can't be equal if # of entries differ */
2466 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Victor Stinner742da042016-09-07 17:40:12 -07002468 for (i = 0; i < a->ma_keys->dk_nentries; i++) {
2469 PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002470 PyObject *aval;
2471 if (a->ma_values)
2472 aval = a->ma_values[i];
2473 else
2474 aval = ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 if (aval != NULL) {
2476 int cmp;
2477 PyObject *bval;
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002478 PyObject **vaddr;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002479 PyObject *key = ep->me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 /* temporarily bump aval's refcount to ensure it stays
2481 alive until we're done with it */
2482 Py_INCREF(aval);
2483 /* ditto for key */
2484 Py_INCREF(key);
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002485 /* reuse the known hash value */
Victor Stinner742da042016-09-07 17:40:12 -07002486 if ((b->ma_keys->dk_lookup)(b, key, ep->me_hash, &vaddr, NULL) < 0)
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002487 bval = NULL;
2488 else
2489 bval = *vaddr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 Py_DECREF(key);
2491 if (bval == NULL) {
2492 Py_DECREF(aval);
2493 if (PyErr_Occurred())
2494 return -1;
2495 return 0;
2496 }
2497 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
2498 Py_DECREF(aval);
2499 if (cmp <= 0) /* error or not equal */
2500 return cmp;
2501 }
2502 }
2503 return 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002504}
Tim Peterse63415e2001-05-08 04:38:29 +00002505
2506static PyObject *
2507dict_richcompare(PyObject *v, PyObject *w, int op)
2508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 int cmp;
2510 PyObject *res;
Tim Peterse63415e2001-05-08 04:38:29 +00002511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 if (!PyDict_Check(v) || !PyDict_Check(w)) {
2513 res = Py_NotImplemented;
2514 }
2515 else if (op == Py_EQ || op == Py_NE) {
2516 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
2517 if (cmp < 0)
2518 return NULL;
2519 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
2520 }
2521 else
2522 res = Py_NotImplemented;
2523 Py_INCREF(res);
2524 return res;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002525}
Tim Peterse63415e2001-05-08 04:38:29 +00002526
Larry Hastings61272b72014-01-07 12:41:53 -08002527/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002528
2529@coexist
2530dict.__contains__
2531
2532 key: object
2533 /
2534
Meador Ingee02de8c2014-01-14 16:48:31 -06002535True if D has a key k, else False.
Larry Hastings61272b72014-01-07 12:41:53 -08002536[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002537
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002538static PyObject *
Larry Hastingsc2047262014-01-25 20:43:29 -08002539dict___contains__(PyDictObject *self, PyObject *key)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002540/*[clinic end generated code: output=a3d03db709ed6e6b input=b852b2a19b51ab24]*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002541{
Larry Hastingsc2047262014-01-25 20:43:29 -08002542 register PyDictObject *mp = self;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002543 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002544 Py_ssize_t ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002545 PyObject **value_addr;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002548 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 hash = PyObject_Hash(key);
2550 if (hash == -1)
2551 return NULL;
2552 }
Victor Stinner742da042016-09-07 17:40:12 -07002553 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2554 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002556 if (ix == DKIX_EMPTY || *value_addr == NULL)
2557 Py_RETURN_FALSE;
2558 Py_RETURN_TRUE;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002559}
2560
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002561static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002562dict_get(PyDictObject *mp, PyObject *args)
Barry Warsawc38c5da1997-10-06 17:49:20 +00002563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 PyObject *key;
2565 PyObject *failobj = Py_None;
2566 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002567 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002568 Py_ssize_t ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002569 PyObject **value_addr;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
2572 return NULL;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002575 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 hash = PyObject_Hash(key);
2577 if (hash == -1)
2578 return NULL;
2579 }
Victor Stinner742da042016-09-07 17:40:12 -07002580 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2581 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002583 if (ix == DKIX_EMPTY || *value_addr == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 val = failobj;
Victor Stinner742da042016-09-07 17:40:12 -07002585 else
2586 val = *value_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 Py_INCREF(val);
2588 return val;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002589}
2590
Benjamin Peterson00e98862013-03-07 22:16:29 -05002591PyObject *
2592PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
Guido van Rossum164452c2000-08-08 16:12:54 +00002593{
Benjamin Peterson00e98862013-03-07 22:16:29 -05002594 PyDictObject *mp = (PyDictObject *)d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002596 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002597 Py_ssize_t hashpos, ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002598 PyDictKeyEntry *ep;
2599 PyObject **value_addr;
Guido van Rossum164452c2000-08-08 16:12:54 +00002600
Benjamin Peterson00e98862013-03-07 22:16:29 -05002601 if (!PyDict_Check(d)) {
2602 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 return NULL;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002604 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002606 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 hash = PyObject_Hash(key);
2608 if (hash == -1)
2609 return NULL;
2610 }
Victor Stinner742da042016-09-07 17:40:12 -07002611 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
2612 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002614 if (ix == DKIX_EMPTY || *value_addr == NULL) {
2615 val = defaultobj;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002616 if (mp->ma_keys->dk_usable <= 0) {
2617 /* Need to resize. */
2618 if (insertion_resize(mp) < 0)
2619 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002620 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002621 }
Victor Stinner742da042016-09-07 17:40:12 -07002622 ix = mp->ma_keys->dk_nentries;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002623 Py_INCREF(defaultobj);
Benjamin Petersonb1efa532013-03-04 09:47:50 -05002624 Py_INCREF(key);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002625 MAINTAIN_TRACKING(mp, key, defaultobj);
Victor Stinner742da042016-09-07 17:40:12 -07002626 dk_set_index(mp->ma_keys, hashpos, ix);
2627 ep = &DK_ENTRIES(mp->ma_keys)[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002628 ep->me_key = key;
2629 ep->me_hash = hash;
Victor Stinner742da042016-09-07 17:40:12 -07002630 if (mp->ma_values) {
2631 mp->ma_values[ix] = val;
2632 }
2633 else {
2634 ep->me_value = val;
2635 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002636 mp->ma_keys->dk_usable--;
Victor Stinner742da042016-09-07 17:40:12 -07002637 mp->ma_keys->dk_nentries++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002638 mp->ma_used++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 }
Victor Stinner742da042016-09-07 17:40:12 -07002640 else
2641 val = *value_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 return val;
Guido van Rossum164452c2000-08-08 16:12:54 +00002643}
2644
Benjamin Peterson00e98862013-03-07 22:16:29 -05002645static PyObject *
2646dict_setdefault(PyDictObject *mp, PyObject *args)
2647{
2648 PyObject *key, *val;
2649 PyObject *defaultobj = Py_None;
2650
2651 if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &defaultobj))
2652 return NULL;
2653
Benjamin Peterson55898502013-03-08 08:36:49 -05002654 val = PyDict_SetDefault((PyObject *)mp, key, defaultobj);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002655 Py_XINCREF(val);
2656 return val;
2657}
Guido van Rossum164452c2000-08-08 16:12:54 +00002658
2659static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002660dict_clear(PyDictObject *mp)
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 PyDict_Clear((PyObject *)mp);
2663 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002664}
2665
Guido van Rossumba6ab842000-12-12 22:02:18 +00002666static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002667dict_pop(PyDictObject *mp, PyObject *args)
Guido van Rossume027d982002-04-12 15:11:59 +00002668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 PyObject *key, *deflt = NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00002670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
2672 return NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06002673
2674 return _PyDict_Pop(mp, key, deflt);
Guido van Rossume027d982002-04-12 15:11:59 +00002675}
2676
2677static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002678dict_popitem(PyDictObject *mp)
Guido van Rossumba6ab842000-12-12 22:02:18 +00002679{
Victor Stinner742da042016-09-07 17:40:12 -07002680 Py_ssize_t i, j;
2681 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 PyObject *res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 /* Allocate the result tuple before checking the size. Believe it
2685 * or not, this allocation could trigger a garbage collection which
2686 * could empty the dict, so if we checked the size first and that
2687 * happened, the result would be an infinite loop (searching for an
2688 * entry that no longer exists). Note that the usual popitem()
2689 * idiom is "while d: k, v = d.popitem()". so needing to throw the
2690 * tuple away if the dict *is* empty isn't a significant
2691 * inefficiency -- possible, but unlikely in practice.
2692 */
2693 res = PyTuple_New(2);
2694 if (res == NULL)
2695 return NULL;
2696 if (mp->ma_used == 0) {
2697 Py_DECREF(res);
2698 PyErr_SetString(PyExc_KeyError,
2699 "popitem(): dictionary is empty");
2700 return NULL;
2701 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002702 /* Convert split table to combined table */
2703 if (mp->ma_keys->dk_lookup == lookdict_split) {
2704 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
2705 Py_DECREF(res);
2706 return NULL;
2707 }
2708 }
2709 ENSURE_ALLOWS_DELETIONS(mp);
Victor Stinner742da042016-09-07 17:40:12 -07002710
2711 /* Pop last item */
2712 ep0 = DK_ENTRIES(mp->ma_keys);
2713 i = mp->ma_keys->dk_nentries - 1;
2714 while (i >= 0 && ep0[i].me_value == NULL) {
2715 i--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 }
Victor Stinner742da042016-09-07 17:40:12 -07002717 assert(i >= 0);
2718
2719 ep = &ep0[i];
2720 j = lookdict_index(mp->ma_keys, ep->me_hash, i);
2721 assert(j >= 0);
2722 assert(dk_get_index(mp->ma_keys, j) == i);
2723 dk_set_index(mp->ma_keys, j, DKIX_DUMMY);
2724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 PyTuple_SET_ITEM(res, 0, ep->me_key);
2726 PyTuple_SET_ITEM(res, 1, ep->me_value);
Victor Stinner742da042016-09-07 17:40:12 -07002727 ep->me_key = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 ep->me_value = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002729 /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
2730 mp->ma_keys->dk_nentries = i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 mp->ma_used--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 return res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002733}
2734
Jeremy Hylton8caad492000-06-23 14:18:11 +00002735static int
2736dict_traverse(PyObject *op, visitproc visit, void *arg)
2737{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002738 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson55f44522016-09-05 12:12:59 -07002739 PyDictKeysObject *keys = mp->ma_keys;
Victor Stinner742da042016-09-07 17:40:12 -07002740 PyDictKeyEntry *entries = DK_ENTRIES(mp->ma_keys);
2741 Py_ssize_t i, n = keys->dk_nentries;
2742
Benjamin Peterson55f44522016-09-05 12:12:59 -07002743 if (keys->dk_lookup == lookdict) {
2744 for (i = 0; i < n; i++) {
2745 if (entries[i].me_value != NULL) {
2746 Py_VISIT(entries[i].me_value);
2747 Py_VISIT(entries[i].me_key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002748 }
2749 }
Victor Stinner742da042016-09-07 17:40:12 -07002750 }
2751 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002752 if (mp->ma_values != NULL) {
Benjamin Peterson55f44522016-09-05 12:12:59 -07002753 for (i = 0; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002754 Py_VISIT(mp->ma_values[i]);
2755 }
2756 }
2757 else {
Benjamin Peterson55f44522016-09-05 12:12:59 -07002758 for (i = 0; i < n; i++) {
2759 Py_VISIT(entries[i].me_value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002760 }
2761 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 }
2763 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002764}
2765
2766static int
2767dict_tp_clear(PyObject *op)
2768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 PyDict_Clear(op);
2770 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002771}
2772
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002773static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00002774
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002775Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06002776_PyDict_SizeOf(PyDictObject *mp)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002777{
Victor Stinner742da042016-09-07 17:40:12 -07002778 Py_ssize_t size, usable, res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002779
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002780 size = DK_SIZE(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002781 usable = USABLE_FRACTION(size);
2782
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002783 res = _PyObject_SIZE(Py_TYPE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002784 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07002785 res += usable * sizeof(PyObject*);
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002786 /* If the dictionary is split, the keys portion is accounted-for
2787 in the type object. */
2788 if (mp->ma_keys->dk_refcnt == 1)
Victor Stinner742da042016-09-07 17:40:12 -07002789 res += sizeof(PyDictKeysObject) - 8 + DK_IXSIZE(mp->ma_keys) * size +
2790 sizeof(PyDictKeyEntry) * usable;
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002791 return res;
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002792}
2793
2794Py_ssize_t
2795_PyDict_KeysSize(PyDictKeysObject *keys)
2796{
Victor Stinner742da042016-09-07 17:40:12 -07002797 return sizeof(PyDictKeysObject) - 8
2798 + DK_IXSIZE(keys) * DK_SIZE(keys)
2799 + USABLE_FRACTION(DK_SIZE(keys)) * sizeof(PyDictKeyEntry);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002800}
2801
doko@ubuntu.com17210f52016-01-14 14:04:59 +01002802static PyObject *
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002803dict_sizeof(PyDictObject *mp)
2804{
2805 return PyLong_FromSsize_t(_PyDict_SizeOf(mp));
2806}
2807
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002808PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
2809
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002810PyDoc_STRVAR(sizeof__doc__,
2811"D.__sizeof__() -> size of D in memory, in bytes");
2812
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002813PyDoc_STRVAR(get__doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00002814"D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002815
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002816PyDoc_STRVAR(setdefault_doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00002817"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 +00002818
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002819PyDoc_STRVAR(pop__doc__,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002820"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00002821If key is not found, d is returned if given, otherwise KeyError is raised");
Guido van Rossume027d982002-04-12 15:11:59 +00002822
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002823PyDoc_STRVAR(popitem__doc__,
Tim Petersf7f88b12000-12-13 23:18:45 +00002824"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000028252-tuple; but raise KeyError if D is empty.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002826
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002827PyDoc_STRVAR(update__doc__,
Brett Cannonf2754162013-05-11 14:46:48 -04002828"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n\
2829If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]\n\
2830If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n\
2831In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00002832
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002833PyDoc_STRVAR(clear__doc__,
2834"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002835
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002836PyDoc_STRVAR(copy__doc__,
2837"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00002838
Guido van Rossumb90c8482007-02-10 01:11:45 +00002839/* Forward */
2840static PyObject *dictkeys_new(PyObject *);
2841static PyObject *dictitems_new(PyObject *);
2842static PyObject *dictvalues_new(PyObject *);
2843
Guido van Rossum45c85d12007-07-27 16:31:40 +00002844PyDoc_STRVAR(keys__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 "D.keys() -> a set-like object providing a view on D's keys");
Guido van Rossum45c85d12007-07-27 16:31:40 +00002846PyDoc_STRVAR(items__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 "D.items() -> a set-like object providing a view on D's items");
Guido van Rossum45c85d12007-07-27 16:31:40 +00002848PyDoc_STRVAR(values__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 "D.values() -> an object providing a view on D's values");
Guido van Rossumb90c8482007-02-10 01:11:45 +00002850
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002851static PyMethodDef mapp_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -07002852 DICT___CONTAINS___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
2854 getitem__doc__},
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002855 {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 sizeof__doc__},
2857 {"get", (PyCFunction)dict_get, METH_VARARGS,
2858 get__doc__},
2859 {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS,
2860 setdefault_doc__},
2861 {"pop", (PyCFunction)dict_pop, METH_VARARGS,
2862 pop__doc__},
2863 {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
2864 popitem__doc__},
2865 {"keys", (PyCFunction)dictkeys_new, METH_NOARGS,
2866 keys__doc__},
2867 {"items", (PyCFunction)dictitems_new, METH_NOARGS,
2868 items__doc__},
2869 {"values", (PyCFunction)dictvalues_new, METH_NOARGS,
2870 values__doc__},
2871 {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
2872 update__doc__},
Larry Hastings5c661892014-01-24 06:17:25 -08002873 DICT_FROMKEYS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
2875 clear__doc__},
2876 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
2877 copy__doc__},
2878 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002879};
2880
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002881/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00002882int
2883PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002884{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002885 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002886 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002888 PyObject **value_addr;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002891 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 hash = PyObject_Hash(key);
2893 if (hash == -1)
2894 return -1;
2895 }
Victor Stinner742da042016-09-07 17:40:12 -07002896 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2897 if (ix == DKIX_ERROR)
2898 return -1;
2899 return (ix != DKIX_EMPTY && *value_addr != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002900}
2901
Thomas Wouterscf297e42007-02-23 15:07:44 +00002902/* Internal version of PyDict_Contains used when the hash value is already known */
2903int
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002904_PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00002905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002907 PyObject **value_addr;
Victor Stinner742da042016-09-07 17:40:12 -07002908 Py_ssize_t ix;
Thomas Wouterscf297e42007-02-23 15:07:44 +00002909
Victor Stinner742da042016-09-07 17:40:12 -07002910 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2911 if (ix == DKIX_ERROR)
2912 return -1;
2913 return (ix != DKIX_EMPTY && *value_addr != NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00002914}
2915
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002916/* Hack to implement "key in dict" */
2917static PySequenceMethods dict_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 0, /* sq_length */
2919 0, /* sq_concat */
2920 0, /* sq_repeat */
2921 0, /* sq_item */
2922 0, /* sq_slice */
2923 0, /* sq_ass_item */
2924 0, /* sq_ass_slice */
2925 PyDict_Contains, /* sq_contains */
2926 0, /* sq_inplace_concat */
2927 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002928};
2929
Guido van Rossum09e563a2001-05-01 12:10:21 +00002930static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002931dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 PyObject *self;
Victor Stinnera9f61a52013-07-16 22:17:26 +02002934 PyDictObject *d;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 assert(type != NULL && type->tp_alloc != NULL);
2937 self = type->tp_alloc(type, 0);
Victor Stinnera9f61a52013-07-16 22:17:26 +02002938 if (self == NULL)
2939 return NULL;
Victor Stinnera9f61a52013-07-16 22:17:26 +02002940 d = (PyDictObject *)self;
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02002941
Victor Stinnera9f61a52013-07-16 22:17:26 +02002942 /* The object has been implicitly tracked by tp_alloc */
2943 if (type == &PyDict_Type)
2944 _PyObject_GC_UNTRACK(d);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02002945
2946 d->ma_used = 0;
Victor Stinner742da042016-09-07 17:40:12 -07002947 d->ma_keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02002948 if (d->ma_keys == NULL) {
2949 Py_DECREF(self);
2950 return NULL;
2951 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 return self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002953}
2954
Tim Peters25786c02001-09-02 08:22:48 +00002955static int
2956dict_init(PyObject *self, PyObject *args, PyObject *kwds)
2957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00002959}
2960
Tim Peters6d6c1a32001-08-02 04:15:00 +00002961static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002962dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00002963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00002965}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002966
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002967PyDoc_STRVAR(dictionary_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00002968"dict() -> new empty dictionary\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00002969"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00002970" (key, value) pairs\n"
2971"dict(iterable) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00002972" d = {}\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00002973" for k, v in iterable:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00002974" d[k] = v\n"
2975"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
2976" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00002977
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002978PyTypeObject PyDict_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2980 "dict",
2981 sizeof(PyDictObject),
2982 0,
2983 (destructor)dict_dealloc, /* tp_dealloc */
2984 0, /* tp_print */
2985 0, /* tp_getattr */
2986 0, /* tp_setattr */
2987 0, /* tp_reserved */
2988 (reprfunc)dict_repr, /* tp_repr */
2989 0, /* tp_as_number */
2990 &dict_as_sequence, /* tp_as_sequence */
2991 &dict_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00002992 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 0, /* tp_call */
2994 0, /* tp_str */
2995 PyObject_GenericGetAttr, /* tp_getattro */
2996 0, /* tp_setattro */
2997 0, /* tp_as_buffer */
2998 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2999 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
3000 dictionary_doc, /* tp_doc */
3001 dict_traverse, /* tp_traverse */
3002 dict_tp_clear, /* tp_clear */
3003 dict_richcompare, /* tp_richcompare */
3004 0, /* tp_weaklistoffset */
3005 (getiterfunc)dict_iter, /* tp_iter */
3006 0, /* tp_iternext */
3007 mapp_methods, /* tp_methods */
3008 0, /* tp_members */
3009 0, /* tp_getset */
3010 0, /* tp_base */
3011 0, /* tp_dict */
3012 0, /* tp_descr_get */
3013 0, /* tp_descr_set */
3014 0, /* tp_dictoffset */
3015 dict_init, /* tp_init */
3016 PyType_GenericAlloc, /* tp_alloc */
3017 dict_new, /* tp_new */
3018 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003019};
3020
Victor Stinner3c1e4812012-03-26 22:10:51 +02003021PyObject *
3022_PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
3023{
3024 PyObject *kv;
3025 kv = _PyUnicode_FromId(key); /* borrowed */
Victor Stinner5b3b1002013-07-22 23:50:57 +02003026 if (kv == NULL) {
3027 PyErr_Clear();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003028 return NULL;
Victor Stinner5b3b1002013-07-22 23:50:57 +02003029 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003030 return PyDict_GetItem(dp, kv);
3031}
3032
Guido van Rossum3cca2451997-05-16 14:23:33 +00003033/* For backward compatibility with old dictionary interface */
3034
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003035PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003036PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 PyObject *kv, *rv;
3039 kv = PyUnicode_FromString(key);
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003040 if (kv == NULL) {
3041 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 return NULL;
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003043 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 rv = PyDict_GetItem(v, kv);
3045 Py_DECREF(kv);
3046 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003047}
3048
3049int
Victor Stinner3c1e4812012-03-26 22:10:51 +02003050_PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
3051{
3052 PyObject *kv;
3053 kv = _PyUnicode_FromId(key); /* borrowed */
3054 if (kv == NULL)
3055 return -1;
3056 return PyDict_SetItem(v, kv, item);
3057}
3058
3059int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003060PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 PyObject *kv;
3063 int err;
3064 kv = PyUnicode_FromString(key);
3065 if (kv == NULL)
3066 return -1;
3067 PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
3068 err = PyDict_SetItem(v, kv, item);
3069 Py_DECREF(kv);
3070 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003071}
3072
3073int
Victor Stinner5fd2e5a2013-11-06 18:58:22 +01003074_PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
3075{
3076 PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
3077 if (kv == NULL)
3078 return -1;
3079 return PyDict_DelItem(v, kv);
3080}
3081
3082int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003083PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 PyObject *kv;
3086 int err;
3087 kv = PyUnicode_FromString(key);
3088 if (kv == NULL)
3089 return -1;
3090 err = PyDict_DelItem(v, kv);
3091 Py_DECREF(kv);
3092 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003093}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003094
Raymond Hettinger019a1482004-03-18 02:41:19 +00003095/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003096
3097typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 PyObject_HEAD
3099 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
3100 Py_ssize_t di_used;
3101 Py_ssize_t di_pos;
3102 PyObject* di_result; /* reusable result tuple for iteritems */
3103 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003104} dictiterobject;
3105
3106static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003107dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 dictiterobject *di;
3110 di = PyObject_GC_New(dictiterobject, itertype);
3111 if (di == NULL)
3112 return NULL;
3113 Py_INCREF(dict);
3114 di->di_dict = dict;
3115 di->di_used = dict->ma_used;
3116 di->di_pos = 0;
3117 di->len = dict->ma_used;
3118 if (itertype == &PyDictIterItem_Type) {
3119 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
3120 if (di->di_result == NULL) {
3121 Py_DECREF(di);
3122 return NULL;
3123 }
3124 }
3125 else
3126 di->di_result = NULL;
3127 _PyObject_GC_TRACK(di);
3128 return (PyObject *)di;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003129}
3130
3131static void
3132dictiter_dealloc(dictiterobject *di)
3133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 Py_XDECREF(di->di_dict);
3135 Py_XDECREF(di->di_result);
3136 PyObject_GC_Del(di);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003137}
3138
3139static int
3140dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
3141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 Py_VISIT(di->di_dict);
3143 Py_VISIT(di->di_result);
3144 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003145}
3146
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003147static PyObject *
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003148dictiter_len(dictiterobject *di)
3149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 Py_ssize_t len = 0;
3151 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
3152 len = di->len;
3153 return PyLong_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003154}
3155
Guido van Rossumb90c8482007-02-10 01:11:45 +00003156PyDoc_STRVAR(length_hint_doc,
3157 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003158
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003159static PyObject *
3160dictiter_reduce(dictiterobject *di);
3161
3162PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3163
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003164static PyMethodDef dictiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS,
3166 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003167 {"__reduce__", (PyCFunction)dictiter_reduce, METH_NOARGS,
3168 reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003170};
3171
Raymond Hettinger019a1482004-03-18 02:41:19 +00003172static PyObject *dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00003173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 PyObject *key;
Victor Stinner742da042016-09-07 17:40:12 -07003175 Py_ssize_t i, n, offset;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003176 PyDictKeysObject *k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003178 PyObject **value_ptr;
Guido van Rossum213c7a62001-04-23 14:08:49 +00003179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 if (d == NULL)
3181 return NULL;
3182 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00003183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 if (di->di_used != d->ma_used) {
3185 PyErr_SetString(PyExc_RuntimeError,
3186 "dictionary changed size during iteration");
3187 di->di_used = -1; /* Make this state sticky */
3188 return NULL;
3189 }
Guido van Rossum2147df72002-07-16 20:30:22 +00003190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 i = di->di_pos;
3192 if (i < 0)
3193 goto fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003194 k = d->ma_keys;
3195 if (d->ma_values) {
3196 value_ptr = &d->ma_values[i];
3197 offset = sizeof(PyObject *);
3198 }
3199 else {
Victor Stinner742da042016-09-07 17:40:12 -07003200 value_ptr = &DK_ENTRIES(k)[i].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003201 offset = sizeof(PyDictKeyEntry);
3202 }
Victor Stinner742da042016-09-07 17:40:12 -07003203 n = k->dk_nentries - 1;
3204 while (i <= n && *value_ptr == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003205 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 i++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003207 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 di->di_pos = i+1;
Victor Stinner742da042016-09-07 17:40:12 -07003209 if (i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 goto fail;
3211 di->len--;
Victor Stinner742da042016-09-07 17:40:12 -07003212 key = DK_ENTRIES(k)[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 Py_INCREF(key);
3214 return key;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003215
3216fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003218 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003220}
3221
Raymond Hettinger019a1482004-03-18 02:41:19 +00003222PyTypeObject PyDictIterKey_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3224 "dict_keyiterator", /* tp_name */
3225 sizeof(dictiterobject), /* tp_basicsize */
3226 0, /* tp_itemsize */
3227 /* methods */
3228 (destructor)dictiter_dealloc, /* tp_dealloc */
3229 0, /* tp_print */
3230 0, /* tp_getattr */
3231 0, /* tp_setattr */
3232 0, /* tp_reserved */
3233 0, /* tp_repr */
3234 0, /* tp_as_number */
3235 0, /* tp_as_sequence */
3236 0, /* tp_as_mapping */
3237 0, /* tp_hash */
3238 0, /* tp_call */
3239 0, /* tp_str */
3240 PyObject_GenericGetAttr, /* tp_getattro */
3241 0, /* tp_setattro */
3242 0, /* tp_as_buffer */
3243 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3244 0, /* tp_doc */
3245 (traverseproc)dictiter_traverse, /* tp_traverse */
3246 0, /* tp_clear */
3247 0, /* tp_richcompare */
3248 0, /* tp_weaklistoffset */
3249 PyObject_SelfIter, /* tp_iter */
3250 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
3251 dictiter_methods, /* tp_methods */
3252 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003253};
3254
3255static PyObject *dictiter_iternextvalue(dictiterobject *di)
3256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -07003258 Py_ssize_t i, n, offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003260 PyObject **value_ptr;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 if (d == NULL)
3263 return NULL;
3264 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 if (di->di_used != d->ma_used) {
3267 PyErr_SetString(PyExc_RuntimeError,
3268 "dictionary changed size during iteration");
3269 di->di_used = -1; /* Make this state sticky */
3270 return NULL;
3271 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 i = di->di_pos;
Victor Stinner742da042016-09-07 17:40:12 -07003274 n = d->ma_keys->dk_nentries - 1;
3275 if (i < 0 || i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 goto fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003277 if (d->ma_values) {
3278 value_ptr = &d->ma_values[i];
3279 offset = sizeof(PyObject *);
3280 }
3281 else {
Victor Stinner742da042016-09-07 17:40:12 -07003282 value_ptr = &DK_ENTRIES(d->ma_keys)[i].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003283 offset = sizeof(PyDictKeyEntry);
3284 }
Victor Stinner742da042016-09-07 17:40:12 -07003285 while (i <= n && *value_ptr == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003286 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 i++;
Victor Stinner742da042016-09-07 17:40:12 -07003288 if (i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003289 goto fail;
3290 }
3291 di->di_pos = i+1;
3292 di->len--;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003293 value = *value_ptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 Py_INCREF(value);
3295 return value;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003296
3297fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003299 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003301}
3302
3303PyTypeObject PyDictIterValue_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3305 "dict_valueiterator", /* tp_name */
3306 sizeof(dictiterobject), /* tp_basicsize */
3307 0, /* tp_itemsize */
3308 /* methods */
3309 (destructor)dictiter_dealloc, /* tp_dealloc */
3310 0, /* tp_print */
3311 0, /* tp_getattr */
3312 0, /* tp_setattr */
3313 0, /* tp_reserved */
3314 0, /* tp_repr */
3315 0, /* tp_as_number */
3316 0, /* tp_as_sequence */
3317 0, /* tp_as_mapping */
3318 0, /* tp_hash */
3319 0, /* tp_call */
3320 0, /* tp_str */
3321 PyObject_GenericGetAttr, /* tp_getattro */
3322 0, /* tp_setattro */
3323 0, /* tp_as_buffer */
3324 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3325 0, /* tp_doc */
3326 (traverseproc)dictiter_traverse, /* tp_traverse */
3327 0, /* tp_clear */
3328 0, /* tp_richcompare */
3329 0, /* tp_weaklistoffset */
3330 PyObject_SelfIter, /* tp_iter */
3331 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
3332 dictiter_methods, /* tp_methods */
3333 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003334};
3335
3336static PyObject *dictiter_iternextitem(dictiterobject *di)
3337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 PyObject *key, *value, *result = di->di_result;
Victor Stinner742da042016-09-07 17:40:12 -07003339 Py_ssize_t i, n, offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003341 PyObject **value_ptr;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 if (d == NULL)
3344 return NULL;
3345 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 if (di->di_used != d->ma_used) {
3348 PyErr_SetString(PyExc_RuntimeError,
3349 "dictionary changed size during iteration");
3350 di->di_used = -1; /* Make this state sticky */
3351 return NULL;
3352 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 i = di->di_pos;
3355 if (i < 0)
3356 goto fail;
Victor Stinner742da042016-09-07 17:40:12 -07003357 n = d->ma_keys->dk_nentries - 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003358 if (d->ma_values) {
3359 value_ptr = &d->ma_values[i];
3360 offset = sizeof(PyObject *);
3361 }
3362 else {
Victor Stinner742da042016-09-07 17:40:12 -07003363 value_ptr = &DK_ENTRIES(d->ma_keys)[i].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003364 offset = sizeof(PyDictKeyEntry);
3365 }
Victor Stinner742da042016-09-07 17:40:12 -07003366 while (i <= n && *value_ptr == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003367 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 i++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003369 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 di->di_pos = i+1;
Victor Stinner742da042016-09-07 17:40:12 -07003371 if (i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 goto fail;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 if (result->ob_refcnt == 1) {
3375 Py_INCREF(result);
3376 Py_DECREF(PyTuple_GET_ITEM(result, 0));
3377 Py_DECREF(PyTuple_GET_ITEM(result, 1));
3378 } else {
3379 result = PyTuple_New(2);
3380 if (result == NULL)
3381 return NULL;
3382 }
3383 di->len--;
Victor Stinner742da042016-09-07 17:40:12 -07003384 key = DK_ENTRIES(d->ma_keys)[i].me_key;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003385 value = *value_ptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 Py_INCREF(key);
3387 Py_INCREF(value);
Eric Snow96c6af92015-05-29 22:21:39 -06003388 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3389 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003391
3392fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003394 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003396}
3397
3398PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3400 "dict_itemiterator", /* tp_name */
3401 sizeof(dictiterobject), /* tp_basicsize */
3402 0, /* tp_itemsize */
3403 /* methods */
3404 (destructor)dictiter_dealloc, /* tp_dealloc */
3405 0, /* tp_print */
3406 0, /* tp_getattr */
3407 0, /* tp_setattr */
3408 0, /* tp_reserved */
3409 0, /* tp_repr */
3410 0, /* tp_as_number */
3411 0, /* tp_as_sequence */
3412 0, /* tp_as_mapping */
3413 0, /* tp_hash */
3414 0, /* tp_call */
3415 0, /* tp_str */
3416 PyObject_GenericGetAttr, /* tp_getattro */
3417 0, /* tp_setattro */
3418 0, /* tp_as_buffer */
3419 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3420 0, /* tp_doc */
3421 (traverseproc)dictiter_traverse, /* tp_traverse */
3422 0, /* tp_clear */
3423 0, /* tp_richcompare */
3424 0, /* tp_weaklistoffset */
3425 PyObject_SelfIter, /* tp_iter */
3426 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
3427 dictiter_methods, /* tp_methods */
3428 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003429};
Guido van Rossumb90c8482007-02-10 01:11:45 +00003430
3431
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003432static PyObject *
3433dictiter_reduce(dictiterobject *di)
3434{
3435 PyObject *list;
3436 dictiterobject tmp;
3437
3438 list = PyList_New(0);
3439 if (!list)
3440 return NULL;
3441
3442 /* copy the itertor state */
3443 tmp = *di;
3444 Py_XINCREF(tmp.di_dict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003445
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003446 /* iterate the temporary into a list */
3447 for(;;) {
3448 PyObject *element = 0;
3449 if (Py_TYPE(di) == &PyDictIterItem_Type)
3450 element = dictiter_iternextitem(&tmp);
3451 else if (Py_TYPE(di) == &PyDictIterKey_Type)
3452 element = dictiter_iternextkey(&tmp);
3453 else if (Py_TYPE(di) == &PyDictIterValue_Type)
3454 element = dictiter_iternextvalue(&tmp);
3455 else
3456 assert(0);
3457 if (element) {
3458 if (PyList_Append(list, element)) {
3459 Py_DECREF(element);
3460 Py_DECREF(list);
3461 Py_XDECREF(tmp.di_dict);
3462 return NULL;
3463 }
3464 Py_DECREF(element);
3465 } else
3466 break;
3467 }
3468 Py_XDECREF(tmp.di_dict);
3469 /* check for error */
3470 if (tmp.di_dict != NULL) {
3471 /* we have an error */
3472 Py_DECREF(list);
3473 return NULL;
3474 }
Antoine Pitroua7013882012-04-05 00:04:20 +02003475 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003476}
3477
Guido van Rossum3ac67412007-02-10 18:55:06 +00003478/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003479/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00003480/***********************************************/
3481
Guido van Rossumb90c8482007-02-10 01:11:45 +00003482/* The instance lay-out is the same for all three; but the type differs. */
3483
Guido van Rossumb90c8482007-02-10 01:11:45 +00003484static void
Eric Snow96c6af92015-05-29 22:21:39 -06003485dictview_dealloc(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 Py_XDECREF(dv->dv_dict);
3488 PyObject_GC_Del(dv);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003489}
3490
3491static int
Eric Snow96c6af92015-05-29 22:21:39 -06003492dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 Py_VISIT(dv->dv_dict);
3495 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003496}
3497
Guido van Rossum83825ac2007-02-10 04:54:19 +00003498static Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003499dictview_len(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 Py_ssize_t len = 0;
3502 if (dv->dv_dict != NULL)
3503 len = dv->dv_dict->ma_used;
3504 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003505}
3506
Eric Snow96c6af92015-05-29 22:21:39 -06003507PyObject *
3508_PyDictView_New(PyObject *dict, PyTypeObject *type)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003509{
Eric Snow96c6af92015-05-29 22:21:39 -06003510 _PyDictViewObject *dv;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003511 if (dict == NULL) {
3512 PyErr_BadInternalCall();
3513 return NULL;
3514 }
3515 if (!PyDict_Check(dict)) {
3516 /* XXX Get rid of this restriction later */
3517 PyErr_Format(PyExc_TypeError,
3518 "%s() requires a dict argument, not '%s'",
3519 type->tp_name, dict->ob_type->tp_name);
3520 return NULL;
3521 }
Eric Snow96c6af92015-05-29 22:21:39 -06003522 dv = PyObject_GC_New(_PyDictViewObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 if (dv == NULL)
3524 return NULL;
3525 Py_INCREF(dict);
3526 dv->dv_dict = (PyDictObject *)dict;
3527 _PyObject_GC_TRACK(dv);
3528 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003529}
3530
Neal Norwitze36f2ba2007-02-26 23:12:28 +00003531/* TODO(guido): The views objects are not complete:
3532
3533 * support more set operations
3534 * support arbitrary mappings?
3535 - either these should be static or exported in dictobject.h
3536 - if public then they should probably be in builtins
3537*/
3538
Guido van Rossumaac530c2007-08-24 22:33:45 +00003539/* Return 1 if self is a subset of other, iterating over self;
3540 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00003541static int
3542all_contained_in(PyObject *self, PyObject *other)
3543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 PyObject *iter = PyObject_GetIter(self);
3545 int ok = 1;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 if (iter == NULL)
3548 return -1;
3549 for (;;) {
3550 PyObject *next = PyIter_Next(iter);
3551 if (next == NULL) {
3552 if (PyErr_Occurred())
3553 ok = -1;
3554 break;
3555 }
3556 ok = PySequence_Contains(other, next);
3557 Py_DECREF(next);
3558 if (ok <= 0)
3559 break;
3560 }
3561 Py_DECREF(iter);
3562 return ok;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003563}
3564
3565static PyObject *
3566dictview_richcompare(PyObject *self, PyObject *other, int op)
3567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 Py_ssize_t len_self, len_other;
3569 int ok;
3570 PyObject *result;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 assert(self != NULL);
3573 assert(PyDictViewSet_Check(self));
3574 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00003575
Brian Curtindfc80e32011-08-10 20:28:54 -05003576 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
3577 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 len_self = PyObject_Size(self);
3580 if (len_self < 0)
3581 return NULL;
3582 len_other = PyObject_Size(other);
3583 if (len_other < 0)
3584 return NULL;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 ok = 0;
3587 switch(op) {
Guido van Rossumaac530c2007-08-24 22:33:45 +00003588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003589 case Py_NE:
3590 case Py_EQ:
3591 if (len_self == len_other)
3592 ok = all_contained_in(self, other);
3593 if (op == Py_NE && ok >= 0)
3594 ok = !ok;
3595 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003597 case Py_LT:
3598 if (len_self < len_other)
3599 ok = all_contained_in(self, other);
3600 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 case Py_LE:
3603 if (len_self <= len_other)
3604 ok = all_contained_in(self, other);
3605 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 case Py_GT:
3608 if (len_self > len_other)
3609 ok = all_contained_in(other, self);
3610 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003612 case Py_GE:
3613 if (len_self >= len_other)
3614 ok = all_contained_in(other, self);
3615 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 }
3618 if (ok < 0)
3619 return NULL;
3620 result = ok ? Py_True : Py_False;
3621 Py_INCREF(result);
3622 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003623}
3624
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003625static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003626dictview_repr(_PyDictViewObject *dv)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 PyObject *seq;
3629 PyObject *result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 seq = PySequence_List((PyObject *)dv);
3632 if (seq == NULL)
3633 return NULL;
3634
3635 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
3636 Py_DECREF(seq);
3637 return result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003638}
3639
Guido van Rossum3ac67412007-02-10 18:55:06 +00003640/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003641
3642static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003643dictkeys_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 if (dv->dv_dict == NULL) {
3646 Py_RETURN_NONE;
3647 }
3648 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003649}
3650
3651static int
Eric Snow96c6af92015-05-29 22:21:39 -06003652dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00003653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 if (dv->dv_dict == NULL)
3655 return 0;
3656 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003657}
3658
Guido van Rossum83825ac2007-02-10 04:54:19 +00003659static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 (lenfunc)dictview_len, /* sq_length */
3661 0, /* sq_concat */
3662 0, /* sq_repeat */
3663 0, /* sq_item */
3664 0, /* sq_slice */
3665 0, /* sq_ass_item */
3666 0, /* sq_ass_slice */
3667 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003668};
3669
Guido van Rossum523259b2007-08-24 23:41:22 +00003670static PyObject*
3671dictviews_sub(PyObject* self, PyObject *other)
3672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 PyObject *result = PySet_New(self);
3674 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003675 _Py_IDENTIFIER(difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003677 if (result == NULL)
3678 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003679
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003680 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 if (tmp == NULL) {
3682 Py_DECREF(result);
3683 return NULL;
3684 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 Py_DECREF(tmp);
3687 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003688}
3689
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003690PyObject*
3691_PyDictView_Intersect(PyObject* self, PyObject *other)
Guido van Rossum523259b2007-08-24 23:41:22 +00003692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 PyObject *result = PySet_New(self);
3694 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003695 _Py_IDENTIFIER(intersection_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 if (result == NULL)
3698 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003699
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003700 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_intersection_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003701 if (tmp == NULL) {
3702 Py_DECREF(result);
3703 return NULL;
3704 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003706 Py_DECREF(tmp);
3707 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003708}
3709
3710static PyObject*
3711dictviews_or(PyObject* self, PyObject *other)
3712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003713 PyObject *result = PySet_New(self);
3714 PyObject *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02003715 _Py_IDENTIFIER(update);
Victor Stinnerd1a9cc22011-10-13 22:51:17 +02003716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003717 if (result == NULL)
3718 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003719
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003720 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003721 if (tmp == NULL) {
3722 Py_DECREF(result);
3723 return NULL;
3724 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003726 Py_DECREF(tmp);
3727 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003728}
3729
3730static PyObject*
3731dictviews_xor(PyObject* self, PyObject *other)
3732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003733 PyObject *result = PySet_New(self);
3734 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003735 _Py_IDENTIFIER(symmetric_difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003737 if (result == NULL)
3738 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003739
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003740 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_symmetric_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003741 if (tmp == NULL) {
3742 Py_DECREF(result);
3743 return NULL;
3744 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003746 Py_DECREF(tmp);
3747 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003748}
3749
3750static PyNumberMethods dictviews_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 0, /*nb_add*/
3752 (binaryfunc)dictviews_sub, /*nb_subtract*/
3753 0, /*nb_multiply*/
3754 0, /*nb_remainder*/
3755 0, /*nb_divmod*/
3756 0, /*nb_power*/
3757 0, /*nb_negative*/
3758 0, /*nb_positive*/
3759 0, /*nb_absolute*/
3760 0, /*nb_bool*/
3761 0, /*nb_invert*/
3762 0, /*nb_lshift*/
3763 0, /*nb_rshift*/
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003764 (binaryfunc)_PyDictView_Intersect, /*nb_and*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 (binaryfunc)dictviews_xor, /*nb_xor*/
3766 (binaryfunc)dictviews_or, /*nb_or*/
Guido van Rossum523259b2007-08-24 23:41:22 +00003767};
3768
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003769static PyObject*
3770dictviews_isdisjoint(PyObject *self, PyObject *other)
3771{
3772 PyObject *it;
3773 PyObject *item = NULL;
3774
3775 if (self == other) {
Eric Snow96c6af92015-05-29 22:21:39 -06003776 if (dictview_len((_PyDictViewObject *)self) == 0)
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003777 Py_RETURN_TRUE;
3778 else
3779 Py_RETURN_FALSE;
3780 }
3781
3782 /* Iterate over the shorter object (only if other is a set,
3783 * because PySequence_Contains may be expensive otherwise): */
3784 if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
Eric Snow96c6af92015-05-29 22:21:39 -06003785 Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003786 Py_ssize_t len_other = PyObject_Size(other);
3787 if (len_other == -1)
3788 return NULL;
3789
3790 if ((len_other > len_self)) {
3791 PyObject *tmp = other;
3792 other = self;
3793 self = tmp;
3794 }
3795 }
3796
3797 it = PyObject_GetIter(other);
3798 if (it == NULL)
3799 return NULL;
3800
3801 while ((item = PyIter_Next(it)) != NULL) {
3802 int contains = PySequence_Contains(self, item);
3803 Py_DECREF(item);
3804 if (contains == -1) {
3805 Py_DECREF(it);
3806 return NULL;
3807 }
3808
3809 if (contains) {
3810 Py_DECREF(it);
3811 Py_RETURN_FALSE;
3812 }
3813 }
3814 Py_DECREF(it);
3815 if (PyErr_Occurred())
3816 return NULL; /* PyIter_Next raised an exception. */
3817 Py_RETURN_TRUE;
3818}
3819
3820PyDoc_STRVAR(isdisjoint_doc,
3821"Return True if the view and the given iterable have a null intersection.");
3822
Guido van Rossumb90c8482007-02-10 01:11:45 +00003823static PyMethodDef dictkeys_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003824 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
3825 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00003827};
3828
3829PyTypeObject PyDictKeys_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003830 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3831 "dict_keys", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06003832 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 0, /* tp_itemsize */
3834 /* methods */
3835 (destructor)dictview_dealloc, /* tp_dealloc */
3836 0, /* tp_print */
3837 0, /* tp_getattr */
3838 0, /* tp_setattr */
3839 0, /* tp_reserved */
3840 (reprfunc)dictview_repr, /* tp_repr */
3841 &dictviews_as_number, /* tp_as_number */
3842 &dictkeys_as_sequence, /* tp_as_sequence */
3843 0, /* tp_as_mapping */
3844 0, /* tp_hash */
3845 0, /* tp_call */
3846 0, /* tp_str */
3847 PyObject_GenericGetAttr, /* tp_getattro */
3848 0, /* tp_setattro */
3849 0, /* tp_as_buffer */
3850 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3851 0, /* tp_doc */
3852 (traverseproc)dictview_traverse, /* tp_traverse */
3853 0, /* tp_clear */
3854 dictview_richcompare, /* tp_richcompare */
3855 0, /* tp_weaklistoffset */
3856 (getiterfunc)dictkeys_iter, /* tp_iter */
3857 0, /* tp_iternext */
3858 dictkeys_methods, /* tp_methods */
3859 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00003860};
3861
3862static PyObject *
3863dictkeys_new(PyObject *dict)
3864{
Eric Snow96c6af92015-05-29 22:21:39 -06003865 return _PyDictView_New(dict, &PyDictKeys_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003866}
3867
Guido van Rossum3ac67412007-02-10 18:55:06 +00003868/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003869
3870static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003871dictitems_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 if (dv->dv_dict == NULL) {
3874 Py_RETURN_NONE;
3875 }
3876 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003877}
3878
3879static int
Eric Snow96c6af92015-05-29 22:21:39 -06003880dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00003881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 PyObject *key, *value, *found;
3883 if (dv->dv_dict == NULL)
3884 return 0;
3885 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
3886 return 0;
3887 key = PyTuple_GET_ITEM(obj, 0);
3888 value = PyTuple_GET_ITEM(obj, 1);
3889 found = PyDict_GetItem((PyObject *)dv->dv_dict, key);
3890 if (found == NULL) {
3891 if (PyErr_Occurred())
3892 return -1;
3893 return 0;
3894 }
3895 return PyObject_RichCompareBool(value, found, Py_EQ);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003896}
3897
Guido van Rossum83825ac2007-02-10 04:54:19 +00003898static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 (lenfunc)dictview_len, /* sq_length */
3900 0, /* sq_concat */
3901 0, /* sq_repeat */
3902 0, /* sq_item */
3903 0, /* sq_slice */
3904 0, /* sq_ass_item */
3905 0, /* sq_ass_slice */
3906 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003907};
3908
Guido van Rossumb90c8482007-02-10 01:11:45 +00003909static PyMethodDef dictitems_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003910 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
3911 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00003913};
3914
3915PyTypeObject PyDictItems_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003916 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3917 "dict_items", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06003918 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919 0, /* tp_itemsize */
3920 /* methods */
3921 (destructor)dictview_dealloc, /* tp_dealloc */
3922 0, /* tp_print */
3923 0, /* tp_getattr */
3924 0, /* tp_setattr */
3925 0, /* tp_reserved */
3926 (reprfunc)dictview_repr, /* tp_repr */
3927 &dictviews_as_number, /* tp_as_number */
3928 &dictitems_as_sequence, /* tp_as_sequence */
3929 0, /* tp_as_mapping */
3930 0, /* tp_hash */
3931 0, /* tp_call */
3932 0, /* tp_str */
3933 PyObject_GenericGetAttr, /* tp_getattro */
3934 0, /* tp_setattro */
3935 0, /* tp_as_buffer */
3936 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3937 0, /* tp_doc */
3938 (traverseproc)dictview_traverse, /* tp_traverse */
3939 0, /* tp_clear */
3940 dictview_richcompare, /* tp_richcompare */
3941 0, /* tp_weaklistoffset */
3942 (getiterfunc)dictitems_iter, /* tp_iter */
3943 0, /* tp_iternext */
3944 dictitems_methods, /* tp_methods */
3945 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00003946};
3947
3948static PyObject *
3949dictitems_new(PyObject *dict)
3950{
Eric Snow96c6af92015-05-29 22:21:39 -06003951 return _PyDictView_New(dict, &PyDictItems_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003952}
3953
Guido van Rossum3ac67412007-02-10 18:55:06 +00003954/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003955
3956static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003957dictvalues_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003959 if (dv->dv_dict == NULL) {
3960 Py_RETURN_NONE;
3961 }
3962 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003963}
3964
Guido van Rossum83825ac2007-02-10 04:54:19 +00003965static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003966 (lenfunc)dictview_len, /* sq_length */
3967 0, /* sq_concat */
3968 0, /* sq_repeat */
3969 0, /* sq_item */
3970 0, /* sq_slice */
3971 0, /* sq_ass_item */
3972 0, /* sq_ass_slice */
3973 (objobjproc)0, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003974};
3975
Guido van Rossumb90c8482007-02-10 01:11:45 +00003976static PyMethodDef dictvalues_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003977 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00003978};
3979
3980PyTypeObject PyDictValues_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3982 "dict_values", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06003983 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003984 0, /* tp_itemsize */
3985 /* methods */
3986 (destructor)dictview_dealloc, /* tp_dealloc */
3987 0, /* tp_print */
3988 0, /* tp_getattr */
3989 0, /* tp_setattr */
3990 0, /* tp_reserved */
3991 (reprfunc)dictview_repr, /* tp_repr */
3992 0, /* tp_as_number */
3993 &dictvalues_as_sequence, /* tp_as_sequence */
3994 0, /* tp_as_mapping */
3995 0, /* tp_hash */
3996 0, /* tp_call */
3997 0, /* tp_str */
3998 PyObject_GenericGetAttr, /* tp_getattro */
3999 0, /* tp_setattro */
4000 0, /* tp_as_buffer */
4001 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4002 0, /* tp_doc */
4003 (traverseproc)dictview_traverse, /* tp_traverse */
4004 0, /* tp_clear */
4005 0, /* tp_richcompare */
4006 0, /* tp_weaklistoffset */
4007 (getiterfunc)dictvalues_iter, /* tp_iter */
4008 0, /* tp_iternext */
4009 dictvalues_methods, /* tp_methods */
4010 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004011};
4012
4013static PyObject *
4014dictvalues_new(PyObject *dict)
4015{
Eric Snow96c6af92015-05-29 22:21:39 -06004016 return _PyDictView_New(dict, &PyDictValues_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004017}
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004018
4019/* Returns NULL if cannot allocate a new PyDictKeysObject,
4020 but does not set an error */
4021PyDictKeysObject *
4022_PyDict_NewKeysForClass(void)
4023{
Victor Stinner742da042016-09-07 17:40:12 -07004024 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004025 if (keys == NULL)
4026 PyErr_Clear();
4027 else
4028 keys->dk_lookup = lookdict_split;
4029 return keys;
4030}
4031
4032#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
4033
4034PyObject *
4035PyObject_GenericGetDict(PyObject *obj, void *context)
4036{
4037 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
4038 if (dictptr == NULL) {
4039 PyErr_SetString(PyExc_AttributeError,
4040 "This object has no __dict__");
4041 return NULL;
4042 }
4043 dict = *dictptr;
4044 if (dict == NULL) {
4045 PyTypeObject *tp = Py_TYPE(obj);
4046 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
4047 DK_INCREF(CACHED_KEYS(tp));
4048 *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
4049 }
4050 else {
4051 *dictptr = dict = PyDict_New();
4052 }
4053 }
4054 Py_XINCREF(dict);
4055 return dict;
4056}
4057
4058int
4059_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
Victor Stinner742da042016-09-07 17:40:12 -07004060 PyObject *key, PyObject *value)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004061{
4062 PyObject *dict;
4063 int res;
4064 PyDictKeysObject *cached;
4065
4066 assert(dictptr != NULL);
4067 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
4068 assert(dictptr != NULL);
4069 dict = *dictptr;
4070 if (dict == NULL) {
4071 DK_INCREF(cached);
4072 dict = new_dict_with_shared_keys(cached);
4073 if (dict == NULL)
4074 return -1;
4075 *dictptr = dict;
4076 }
4077 if (value == NULL) {
4078 res = PyDict_DelItem(dict, key);
4079 if (cached != ((PyDictObject *)dict)->ma_keys) {
4080 CACHED_KEYS(tp) = NULL;
4081 DK_DECREF(cached);
4082 }
4083 } else {
4084 res = PyDict_SetItem(dict, key, value);
4085 if (cached != ((PyDictObject *)dict)->ma_keys) {
4086 /* Either update tp->ht_cached_keys or delete it */
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004087 if (cached->dk_refcnt == 1) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004088 CACHED_KEYS(tp) = make_keys_shared(dict);
Victor Stinner742da042016-09-07 17:40:12 -07004089 }
4090 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004091 CACHED_KEYS(tp) = NULL;
4092 }
4093 DK_DECREF(cached);
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004094 if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
4095 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004096 }
4097 }
4098 } else {
4099 dict = *dictptr;
4100 if (dict == NULL) {
4101 dict = PyDict_New();
4102 if (dict == NULL)
4103 return -1;
4104 *dictptr = dict;
4105 }
4106 if (value == NULL) {
4107 res = PyDict_DelItem(dict, key);
4108 } else {
4109 res = PyDict_SetItem(dict, key, value);
4110 }
4111 }
4112 return res;
4113}
4114
4115void
4116_PyDictKeys_DecRef(PyDictKeysObject *keys)
4117{
4118 DK_DECREF(keys);
4119}