blob: df5f29fdf56e5a21cb72ef97756bab5cc195a090 [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 {
Victor Stinner98ee9d52016-09-08 09:33:56 -0700434 dk = PyObject_MALLOC(sizeof(PyDictKeysObject)
435 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
436 + es * size
437 + sizeof(PyDictKeyEntry) * usable);
Victor Stinner742da042016-09-07 17:40:12 -0700438 if (dk == NULL) {
439 PyErr_NoMemory();
440 return NULL;
441 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400442 }
Antoine Pitrou2d169b22012-05-12 23:43:44 +0200443 DK_DEBUG_INCREF dk->dk_refcnt = 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400444 dk->dk_size = size;
Victor Stinner742da042016-09-07 17:40:12 -0700445 dk->dk_usable = usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400446 dk->dk_lookup = lookdict_unicode_nodummy;
Victor Stinner742da042016-09-07 17:40:12 -0700447 dk->dk_nentries = 0;
448 memset(&dk->dk_indices[0], 0xff, es * size);
449 memset(DK_ENTRIES(dk), 0, sizeof(PyDictKeyEntry) * usable);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400450 return dk;
451}
452
453static void
454free_keys_object(PyDictKeysObject *keys)
455{
Victor Stinner742da042016-09-07 17:40:12 -0700456 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400457 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -0700458 for (i = 0, n = keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400459 Py_XDECREF(entries[i].me_key);
460 Py_XDECREF(entries[i].me_value);
461 }
Victor Stinner742da042016-09-07 17:40:12 -0700462 if (keys->dk_size == PyDict_MINSIZE && numfreekeys < PyDict_MAXFREELIST) {
463 keys_free_list[numfreekeys++] = keys;
464 return;
465 }
Raymond Hettingerce5179f2016-01-31 08:56:21 -0800466 PyObject_FREE(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400467}
468
469#define new_values(size) PyMem_NEW(PyObject *, size)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400470#define free_values(values) PyMem_FREE(values)
471
472/* Consumes a reference to the keys object */
473static PyObject *
474new_dict(PyDictKeysObject *keys, PyObject **values)
475{
476 PyDictObject *mp;
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200477 assert(keys != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 if (numfree) {
479 mp = free_list[--numfree];
480 assert (mp != NULL);
481 assert (Py_TYPE(mp) == &PyDict_Type);
482 _Py_NewReference((PyObject *)mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400484 else {
485 mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
486 if (mp == NULL) {
487 DK_DECREF(keys);
488 free_values(values);
489 return NULL;
490 }
491 }
492 mp->ma_keys = keys;
493 mp->ma_values = values;
494 mp->ma_used = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000496}
497
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400498/* Consumes a reference to the keys object */
499static PyObject *
500new_dict_with_shared_keys(PyDictKeysObject *keys)
501{
502 PyObject **values;
503 Py_ssize_t i, size;
504
Victor Stinner742da042016-09-07 17:40:12 -0700505 size = USABLE_FRACTION(DK_SIZE(keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400506 values = new_values(size);
507 if (values == NULL) {
508 DK_DECREF(keys);
509 return PyErr_NoMemory();
510 }
511 for (i = 0; i < size; i++) {
512 values[i] = NULL;
513 }
514 return new_dict(keys, values);
515}
516
517PyObject *
518PyDict_New(void)
519{
Victor Stinner742da042016-09-07 17:40:12 -0700520 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200521 if (keys == NULL)
522 return NULL;
523 return new_dict(keys, NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400524}
525
Victor Stinner742da042016-09-07 17:40:12 -0700526/* Search index of hash table from offset of entry table */
527static Py_ssize_t
528lookdict_index(PyDictKeysObject *k, Py_hash_t hash, Py_ssize_t index)
529{
530 size_t i, perturb;
531 size_t mask = DK_MASK(k);
532 Py_ssize_t ix;
533
534 i = (size_t)hash & mask;
535 ix = dk_get_index(k, i);
536 if (ix == index) {
537 return i;
538 }
539 if (ix == DKIX_EMPTY) {
540 return DKIX_EMPTY;
541 }
542
543 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
544 i = mask & ((i << 2) + i + perturb + 1);
545 ix = dk_get_index(k, i);
546 if (ix == index) {
547 return i;
548 }
549 if (ix == DKIX_EMPTY) {
550 return DKIX_EMPTY;
551 }
552 }
553 assert(0); /* NOT REACHED */
554 return DKIX_ERROR;
555}
556
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000557/*
558The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000559This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000560Open addressing is preferred over chaining since the link overhead for
561chaining would be substantial (100% with typical malloc overhead).
562
Tim Peterseb28ef22001-06-02 05:27:19 +0000563The initial probe index is computed as hash mod the table size. Subsequent
564probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000565
566All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000567
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000568The details in this version are due to Tim Peters, building on many past
Tim Peterseb28ef22001-06-02 05:27:19 +0000569contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000570Christian Tismer.
Fred Drake1bff34a2000-08-31 19:31:38 +0000571
Victor Stinner742da042016-09-07 17:40:12 -0700572lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000573comparison raises an exception (this was new in Python 2.5).
Guido van Rossum89d8c602007-09-18 17:26:56 +0000574lookdict_unicode() below is specialized to string keys, comparison of which can
Victor Stinner742da042016-09-07 17:40:12 -0700575never raise an exception; that function can never return DKIX_ERROR.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400576lookdict_unicode_nodummy is further specialized for string keys that cannot be
577the <dummy> value.
Victor Stinner742da042016-09-07 17:40:12 -0700578For both, when the key isn't found a DKIX_EMPTY is returned. hashpos returns
579where the key index should be inserted.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000580*/
Victor Stinner742da042016-09-07 17:40:12 -0700581static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400582lookdict(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700583 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000584{
Victor Stinner742da042016-09-07 17:40:12 -0700585 size_t i, perturb, mask;
586 Py_ssize_t ix, freeslot;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200587 int cmp;
Victor Stinner742da042016-09-07 17:40:12 -0700588 PyDictKeysObject *dk;
589 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 PyObject *startkey;
Tim Peterseb28ef22001-06-02 05:27:19 +0000591
Antoine Pitrou9a234902012-05-13 20:48:01 +0200592top:
Victor Stinner742da042016-09-07 17:40:12 -0700593 dk = mp->ma_keys;
594 mask = DK_MASK(dk);
595 ep0 = DK_ENTRIES(dk);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700597
598 ix = dk_get_index(dk, i);
599 if (ix == DKIX_EMPTY) {
600 if (hashpos != NULL)
601 *hashpos = i;
602 *value_addr = NULL;
603 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400604 }
Victor Stinner742da042016-09-07 17:40:12 -0700605 if (ix == DKIX_DUMMY) {
606 freeslot = i;
607 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 else {
Victor Stinner742da042016-09-07 17:40:12 -0700609 ep = &ep0[ix];
610 if (ep->me_key == key) {
611 *value_addr = &ep->me_value;
612 if (hashpos != NULL)
613 *hashpos = i;
614 return ix;
615 }
616 if (ep->me_key != NULL && ep->me_hash == hash) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 startkey = ep->me_key;
618 Py_INCREF(startkey);
619 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
620 Py_DECREF(startkey);
621 if (cmp < 0)
Victor Stinner742da042016-09-07 17:40:12 -0700622 return DKIX_ERROR;
623 if (dk == mp->ma_keys && ep->me_key == startkey) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400624 if (cmp > 0) {
625 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700626 if (hashpos != NULL)
627 *hashpos = i;
628 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400629 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 }
631 else {
Antoine Pitrou9a234902012-05-13 20:48:01 +0200632 /* The dict was mutated, restart */
633 goto top;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 }
635 }
Victor Stinner742da042016-09-07 17:40:12 -0700636 freeslot = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 }
Tim Peters15d49292001-05-27 07:39:22 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700640 i = ((i << 2) + i + perturb + 1) & mask;
641 ix = dk_get_index(dk, i);
642 if (ix == DKIX_EMPTY) {
643 if (hashpos != NULL) {
644 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400645 }
Victor Stinner742da042016-09-07 17:40:12 -0700646 *value_addr = NULL;
647 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400648 }
Victor Stinner742da042016-09-07 17:40:12 -0700649 if (ix == DKIX_DUMMY) {
650 if (freeslot == -1)
651 freeslot = i;
652 continue;
653 }
654 ep = &ep0[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400655 if (ep->me_key == key) {
Victor Stinner742da042016-09-07 17:40:12 -0700656 if (hashpos != NULL) {
657 *hashpos = i;
658 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400659 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700660 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400661 }
Victor Stinner742da042016-09-07 17:40:12 -0700662 if (ep->me_hash == hash && ep->me_key != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 startkey = ep->me_key;
664 Py_INCREF(startkey);
665 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
666 Py_DECREF(startkey);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400667 if (cmp < 0) {
668 *value_addr = NULL;
Victor Stinner742da042016-09-07 17:40:12 -0700669 return DKIX_ERROR;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400670 }
Victor Stinner742da042016-09-07 17:40:12 -0700671 if (dk == mp->ma_keys && ep->me_key == startkey) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400672 if (cmp > 0) {
Victor Stinner742da042016-09-07 17:40:12 -0700673 if (hashpos != NULL) {
674 *hashpos = i;
675 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400676 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700677 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400678 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 }
680 else {
Antoine Pitrou9a234902012-05-13 20:48:01 +0200681 /* The dict was mutated, restart */
682 goto top;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 }
684 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 }
686 assert(0); /* NOT REACHED */
687 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000688}
689
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400690/* Specialized version for string-only keys */
Victor Stinner742da042016-09-07 17:40:12 -0700691static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400692lookdict_unicode(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700693 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Fred Drake1bff34a2000-08-31 19:31:38 +0000694{
Victor Stinner742da042016-09-07 17:40:12 -0700695 size_t i, perturb;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200696 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700697 Py_ssize_t ix, freeslot;
698 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Fred Drake1bff34a2000-08-31 19:31:38 +0000699
Victor Stinner742da042016-09-07 17:40:12 -0700700 assert(mp->ma_values == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 /* Make sure this function doesn't have to handle non-unicode keys,
702 including subclasses of str; e.g., one reason to subclass
703 unicodes is to override __eq__, and for speed we don't cater to
704 that here. */
705 if (!PyUnicode_CheckExact(key)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400706 mp->ma_keys->dk_lookup = lookdict;
Victor Stinner742da042016-09-07 17:40:12 -0700707 return lookdict(mp, key, hash, value_addr, hashpos);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 }
Mark Dickinson57e683e2011-09-24 18:18:40 +0100709 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700710 ix = dk_get_index(mp->ma_keys, i);
711 if (ix == DKIX_EMPTY) {
712 if (hashpos != NULL)
713 *hashpos = i;
714 *value_addr = NULL;
715 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400716 }
Victor Stinner742da042016-09-07 17:40:12 -0700717 if (ix == DKIX_DUMMY) {
718 freeslot = i;
719 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 else {
Victor Stinner742da042016-09-07 17:40:12 -0700721 ep = &ep0[ix];
722 /* only split table can be ix != DKIX_DUMMY && me_key == NULL */
723 assert(ep->me_key != NULL);
724 if (ep->me_key == key || (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
725 if (hashpos != NULL)
726 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400727 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700728 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400729 }
Victor Stinner742da042016-09-07 17:40:12 -0700730 freeslot = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 }
Tim Peters15d49292001-05-27 07:39:22 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700734 i = mask & ((i << 2) + i + perturb + 1);
735 ix = dk_get_index(mp->ma_keys, i);
736 if (ix == DKIX_EMPTY) {
737 if (hashpos != NULL) {
738 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400739 }
Victor Stinner742da042016-09-07 17:40:12 -0700740 *value_addr = NULL;
741 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400742 }
Victor Stinner742da042016-09-07 17:40:12 -0700743 if (ix == DKIX_DUMMY) {
744 if (freeslot == -1)
745 freeslot = i;
746 continue;
747 }
748 ep = &ep0[ix];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 if (ep->me_key == key
750 || (ep->me_hash == hash
Victor Stinner742da042016-09-07 17:40:12 -0700751 && ep->me_key != NULL
752 && unicode_eq(ep->me_key, key))) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400753 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700754 if (hashpos != NULL) {
755 *hashpos = i;
756 }
757 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400758 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 }
760 assert(0); /* NOT REACHED */
761 return 0;
Fred Drake1bff34a2000-08-31 19:31:38 +0000762}
763
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400764/* Faster version of lookdict_unicode when it is known that no <dummy> keys
765 * will be present. */
Victor Stinner742da042016-09-07 17:40:12 -0700766static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400767lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700768 Py_hash_t hash, PyObject ***value_addr,
769 Py_ssize_t *hashpos)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400770{
Victor Stinner742da042016-09-07 17:40:12 -0700771 size_t i, perturb;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200772 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700773 Py_ssize_t ix;
774 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400775
Victor Stinner742da042016-09-07 17:40:12 -0700776 assert(mp->ma_values == NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400777 /* Make sure this function doesn't have to handle non-unicode keys,
778 including subclasses of str; e.g., one reason to subclass
779 unicodes is to override __eq__, and for speed we don't cater to
780 that here. */
781 if (!PyUnicode_CheckExact(key)) {
782 mp->ma_keys->dk_lookup = lookdict;
Victor Stinner742da042016-09-07 17:40:12 -0700783 return lookdict(mp, key, hash, value_addr, hashpos);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400784 }
785 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700786 ix = dk_get_index(mp->ma_keys, i);
787 assert (ix != DKIX_DUMMY);
788 if (ix == DKIX_EMPTY) {
789 if (hashpos != NULL)
790 *hashpos = i;
791 *value_addr = NULL;
792 return DKIX_EMPTY;
793 }
794 ep = &ep0[ix];
795 assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
796 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400797 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700798 if (hashpos != NULL)
799 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400800 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700801 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400802 }
803 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700804 i = mask & ((i << 2) + i + perturb + 1);
805 ix = dk_get_index(mp->ma_keys, i);
806 assert (ix != DKIX_DUMMY);
807 if (ix == DKIX_EMPTY) {
808 if (hashpos != NULL)
809 *hashpos = i;
810 *value_addr = NULL;
811 return DKIX_EMPTY;
812 }
813 ep = &ep0[ix];
814 assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
815 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400816 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700817 if (hashpos != NULL)
818 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400819 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700820 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400821 }
822 }
823 assert(0); /* NOT REACHED */
824 return 0;
825}
826
827/* Version of lookdict for split tables.
828 * All split tables and only split tables use this lookup function.
829 * Split tables only contain unicode keys and no dummy keys,
830 * so algorithm is the same as lookdict_unicode_nodummy.
831 */
Victor Stinner742da042016-09-07 17:40:12 -0700832static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400833lookdict_split(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700834 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400835{
Victor Stinner742da042016-09-07 17:40:12 -0700836 size_t i, perturb;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200837 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700838 Py_ssize_t ix;
839 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400840
Victor Stinner742da042016-09-07 17:40:12 -0700841 /* mp must split table */
842 assert(mp->ma_values != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400843 if (!PyUnicode_CheckExact(key)) {
Victor Stinner742da042016-09-07 17:40:12 -0700844 ix = lookdict(mp, key, hash, value_addr, hashpos);
845 if (ix >= 0) {
846 *value_addr = &mp->ma_values[ix];
847 }
848 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400849 }
Victor Stinner742da042016-09-07 17:40:12 -0700850
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400851 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700852 ix = dk_get_index(mp->ma_keys, i);
853 if (ix == DKIX_EMPTY) {
854 if (hashpos != NULL)
855 *hashpos = i;
856 *value_addr = NULL;
857 return DKIX_EMPTY;
858 }
859 assert(ix >= 0);
860 ep = &ep0[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400861 assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700862 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400863 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700864 if (hashpos != NULL)
865 *hashpos = i;
866 *value_addr = &mp->ma_values[ix];
867 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400868 }
869 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700870 i = mask & ((i << 2) + i + perturb + 1);
871 ix = dk_get_index(mp->ma_keys, i);
872 if (ix == DKIX_EMPTY) {
873 if (hashpos != NULL)
874 *hashpos = i;
875 *value_addr = NULL;
876 return DKIX_EMPTY;
877 }
878 assert(ix >= 0);
879 ep = &ep0[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400880 assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700881 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400882 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700883 if (hashpos != NULL)
884 *hashpos = i;
885 *value_addr = &mp->ma_values[ix];
886 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400887 }
888 }
889 assert(0); /* NOT REACHED */
890 return 0;
891}
892
Benjamin Petersonfb886362010-04-24 18:21:17 +0000893int
894_PyDict_HasOnlyStringKeys(PyObject *dict)
895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 Py_ssize_t pos = 0;
897 PyObject *key, *value;
Benjamin Petersonf6096542010-11-17 22:33:12 +0000898 assert(PyDict_Check(dict));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 /* Shortcut */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400900 if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 return 1;
902 while (PyDict_Next(dict, &pos, &key, &value))
903 if (!PyUnicode_Check(key))
904 return 0;
905 return 1;
Benjamin Petersonfb886362010-04-24 18:21:17 +0000906}
907
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000908#define MAINTAIN_TRACKING(mp, key, value) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 do { \
910 if (!_PyObject_GC_IS_TRACKED(mp)) { \
911 if (_PyObject_GC_MAY_BE_TRACKED(key) || \
912 _PyObject_GC_MAY_BE_TRACKED(value)) { \
913 _PyObject_GC_TRACK(mp); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 } \
915 } \
916 } while(0)
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000917
918void
919_PyDict_MaybeUntrack(PyObject *op)
920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 PyDictObject *mp;
922 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -0700923 Py_ssize_t i, numentries;
924 PyDictKeyEntry *ep0;
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
927 return;
928
929 mp = (PyDictObject *) op;
Victor Stinner742da042016-09-07 17:40:12 -0700930 ep0 = DK_ENTRIES(mp->ma_keys);
931 numentries = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400932 if (_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -0700933 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400934 if ((value = mp->ma_values[i]) == NULL)
935 continue;
936 if (_PyObject_GC_MAY_BE_TRACKED(value)) {
Victor Stinner742da042016-09-07 17:40:12 -0700937 assert(!_PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400938 return;
939 }
940 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400942 else {
Victor Stinner742da042016-09-07 17:40:12 -0700943 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400944 if ((value = ep0[i].me_value) == NULL)
945 continue;
946 if (_PyObject_GC_MAY_BE_TRACKED(value) ||
947 _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
948 return;
949 }
950 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 _PyObject_GC_UNTRACK(op);
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000952}
953
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400954/* Internal function to find slot for an item from its hash
955 * when it is known that the key is not present in the dict.
956 */
Victor Stinner742da042016-09-07 17:40:12 -0700957static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400958find_empty_slot(PyDictObject *mp, PyObject *key, Py_hash_t hash,
Victor Stinner742da042016-09-07 17:40:12 -0700959 PyObject ***value_addr, Py_ssize_t *hashpos)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000960{
Victor Stinner742da042016-09-07 17:40:12 -0700961 size_t i, perturb;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400962 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700963 Py_ssize_t ix;
964 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000965
Victor Stinner742da042016-09-07 17:40:12 -0700966 assert(hashpos != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400967 assert(key != NULL);
968 if (!PyUnicode_CheckExact(key))
969 mp->ma_keys->dk_lookup = lookdict;
970 i = hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700971 ix = dk_get_index(mp->ma_keys, i);
972 for (perturb = hash; ix != DKIX_EMPTY; perturb >>= PERTURB_SHIFT) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400973 i = (i << 2) + i + perturb + 1;
Victor Stinner742da042016-09-07 17:40:12 -0700974 ix = dk_get_index(mp->ma_keys, i & mask);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 }
Victor Stinner742da042016-09-07 17:40:12 -0700976 ep = &ep0[mp->ma_keys->dk_nentries];
977 *hashpos = i & mask;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400978 assert(ep->me_value == NULL);
979 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -0700980 *value_addr = &mp->ma_values[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400981 else
982 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700983 return ix;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000984}
985
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400986static int
987insertion_resize(PyDictObject *mp)
988{
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700989 return dictresize(mp, GROWTH_RATE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400990}
Antoine Pitroue965d972012-02-27 00:45:12 +0100991
992/*
993Internal routine to insert a new item into the table.
994Used both by the internal resize routine and by the public insert routine.
Antoine Pitroue965d972012-02-27 00:45:12 +0100995Returns -1 if an error occurred, or 0 on success.
996*/
997static int
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400998insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +0100999{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001000 PyObject *old_value;
1001 PyObject **value_addr;
Victor Stinner742da042016-09-07 17:40:12 -07001002 PyDictKeyEntry *ep, *ep0;
1003 Py_ssize_t hashpos, ix;
Antoine Pitroue965d972012-02-27 00:45:12 +01001004
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001005 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
1006 if (insertion_resize(mp) < 0)
1007 return -1;
1008 }
1009
Victor Stinner742da042016-09-07 17:40:12 -07001010 ix = mp->ma_keys->dk_lookup(mp, key, hash, &value_addr, &hashpos);
1011 if (ix == DKIX_ERROR) {
Antoine Pitroue965d972012-02-27 00:45:12 +01001012 return -1;
1013 }
Victor Stinner742da042016-09-07 17:40:12 -07001014
Antoine Pitroud6967322014-10-18 00:35:00 +02001015 assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
Benjamin Petersona6f195e2012-04-30 10:23:40 -04001016 Py_INCREF(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001017 MAINTAIN_TRACKING(mp, key, value);
Victor Stinner742da042016-09-07 17:40:12 -07001018
1019 /* When insertion order is different from shared key, we can't share
1020 * the key anymore. Convert this instance to combine table.
1021 */
1022 if (_PyDict_HasSplitTable(mp) &&
1023 ((ix >= 0 && *value_addr == NULL && mp->ma_used != ix) ||
1024 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
1025 if (insertion_resize(mp) < 0) {
1026 Py_DECREF(value);
1027 return -1;
1028 }
1029 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
1030 ix = DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001031 }
Victor Stinner742da042016-09-07 17:40:12 -07001032
1033 if (ix == DKIX_EMPTY) {
1034 /* Insert into new slot. */
1035 if (mp->ma_keys->dk_usable <= 0) {
1036 /* Need to resize. */
1037 if (insertion_resize(mp) < 0) {
1038 Py_DECREF(value);
1039 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001040 }
Victor Stinner742da042016-09-07 17:40:12 -07001041 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
1042 }
1043 ep0 = DK_ENTRIES(mp->ma_keys);
1044 ep = &ep0[mp->ma_keys->dk_nentries];
1045 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
1046 Py_INCREF(key);
1047 ep->me_key = key;
1048 ep->me_hash = hash;
1049 if (mp->ma_values) {
1050 assert (mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
1051 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001052 }
1053 else {
Victor Stinner742da042016-09-07 17:40:12 -07001054 ep->me_value = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001055 }
1056 mp->ma_used++;
Victor Stinner742da042016-09-07 17:40:12 -07001057 mp->ma_keys->dk_usable--;
1058 mp->ma_keys->dk_nentries++;
1059 assert(mp->ma_keys->dk_usable >= 0);
1060 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001061 }
Victor Stinner742da042016-09-07 17:40:12 -07001062
1063 assert(value_addr != NULL);
1064
1065 old_value = *value_addr;
1066 if (old_value != NULL) {
1067 *value_addr = value;
1068 Py_DECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
1069 return 0;
1070 }
1071
1072 /* pending state */
1073 assert(_PyDict_HasSplitTable(mp));
1074 assert(ix == mp->ma_used);
1075 *value_addr = value;
1076 mp->ma_used++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001077 return 0;
Antoine Pitroue965d972012-02-27 00:45:12 +01001078}
1079
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001080/*
1081Internal routine used by dictresize() to insert an item which is
1082known to be absent from the dict. This routine also assumes that
1083the dict contains no deleted entries. Besides the performance benefit,
1084using insertdict() in dictresize() is dangerous (SF bug #1456209).
1085Note that no refcounts are changed by this routine; if needed, the caller
1086is responsible for incref'ing `key` and `value`.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001087Neither mp->ma_used nor k->dk_usable are modified by this routine; the caller
1088must set them correctly
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001089*/
1090static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001091insertdict_clean(PyDictObject *mp, PyObject *key, Py_hash_t hash,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 PyObject *value)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001093{
Victor Stinner742da042016-09-07 17:40:12 -07001094 size_t i, perturb;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001095 PyDictKeysObject *k = mp->ma_keys;
1096 size_t mask = (size_t)DK_SIZE(k)-1;
Victor Stinner742da042016-09-07 17:40:12 -07001097 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001098 PyDictKeyEntry *ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001099
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001100 assert(k->dk_lookup != NULL);
1101 assert(value != NULL);
1102 assert(key != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001103 assert(PyUnicode_CheckExact(key) || k->dk_lookup == lookdict);
1104 i = hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -07001105 for (perturb = hash; dk_get_index(k, i) != DKIX_EMPTY;
1106 perturb >>= PERTURB_SHIFT) {
1107 i = mask & ((i << 2) + i + perturb + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 }
Victor Stinner742da042016-09-07 17:40:12 -07001109 ep = &ep0[k->dk_nentries];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 assert(ep->me_value == NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001111 dk_set_index(k, i, k->dk_nentries);
1112 k->dk_nentries++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 ep->me_key = key;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001114 ep->me_hash = hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 ep->me_value = value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001116}
1117
1118/*
1119Restructure the table by allocating a new table and reinserting all
1120items again. When entries have been deleted, the new table may
1121actually be smaller than the old one.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001122If a table is split (its keys and hashes are shared, its values are not),
1123then the values are temporarily copied into the table, it is resized as
1124a combined table, then the me_value slots in the old table are NULLed out.
1125After resizing a table is always combined,
1126but can be resplit by make_keys_shared().
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001127*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001128static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001129dictresize(PyDictObject *mp, Py_ssize_t minused)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001130{
Victor Stinner742da042016-09-07 17:40:12 -07001131 Py_ssize_t i, newsize;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001132 PyDictKeysObject *oldkeys;
1133 PyObject **oldvalues;
Victor Stinner742da042016-09-07 17:40:12 -07001134 PyDictKeyEntry *ep0;
Tim Peters91a364d2001-05-19 07:04:38 +00001135
Victor Stinner742da042016-09-07 17:40:12 -07001136 /* Find the smallest table size > minused. */
1137 for (newsize = PyDict_MINSIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 newsize <= minused && newsize > 0;
1139 newsize <<= 1)
1140 ;
1141 if (newsize <= 0) {
1142 PyErr_NoMemory();
1143 return -1;
1144 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001145 oldkeys = mp->ma_keys;
1146 oldvalues = mp->ma_values;
1147 /* Allocate a new table. */
1148 mp->ma_keys = new_keys_object(newsize);
1149 if (mp->ma_keys == NULL) {
1150 mp->ma_keys = oldkeys;
1151 return -1;
1152 }
1153 if (oldkeys->dk_lookup == lookdict)
1154 mp->ma_keys->dk_lookup = lookdict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001155 mp->ma_values = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001156 ep0 = DK_ENTRIES(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001157 /* Main loop below assumes we can transfer refcount to new keys
1158 * and that value is stored in me_value.
1159 * Increment ref-counts and copy values here to compensate
1160 * This (resizing a split table) should be relatively rare */
1161 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001162 for (i = 0; i < oldkeys->dk_nentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001163 if (oldvalues[i] != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001164 Py_INCREF(ep0[i].me_key);
1165 ep0[i].me_value = oldvalues[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 }
1168 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001169 /* Main loop */
Victor Stinner742da042016-09-07 17:40:12 -07001170 for (i = 0; i < oldkeys->dk_nentries; i++) {
1171 PyDictKeyEntry *ep = &ep0[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001172 if (ep->me_value != NULL) {
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001173 insertdict_clean(mp, ep->me_key, ep->me_hash, ep->me_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001176 mp->ma_keys->dk_usable -= mp->ma_used;
1177 if (oldvalues != NULL) {
1178 /* NULL out me_value slot in oldkeys, in case it was shared */
Victor Stinner742da042016-09-07 17:40:12 -07001179 for (i = 0; i < oldkeys->dk_nentries; i++)
1180 ep0[i].me_value = NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001181 DK_DECREF(oldkeys);
Victor Stinner742da042016-09-07 17:40:12 -07001182 if (oldvalues != empty_values) {
1183 free_values(oldvalues);
1184 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001185 }
1186 else {
1187 assert(oldkeys->dk_lookup != lookdict_split);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001188 assert(oldkeys->dk_refcnt == 1);
Raymond Hettingerce5179f2016-01-31 08:56:21 -08001189 DK_DEBUG_DECREF PyObject_FREE(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001190 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001192}
1193
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001194/* Returns NULL if unable to split table.
1195 * A NULL return does not necessarily indicate an error */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001196static PyDictKeysObject *
1197make_keys_shared(PyObject *op)
1198{
1199 Py_ssize_t i;
1200 Py_ssize_t size;
1201 PyDictObject *mp = (PyDictObject *)op;
1202
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001203 if (!PyDict_CheckExact(op))
1204 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001205 if (!_PyDict_HasSplitTable(mp)) {
1206 PyDictKeyEntry *ep0;
1207 PyObject **values;
1208 assert(mp->ma_keys->dk_refcnt == 1);
1209 if (mp->ma_keys->dk_lookup == lookdict) {
1210 return NULL;
1211 }
1212 else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
1213 /* Remove dummy keys */
1214 if (dictresize(mp, DK_SIZE(mp->ma_keys)))
1215 return NULL;
1216 }
1217 assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
1218 /* Copy values into a new array */
Victor Stinner742da042016-09-07 17:40:12 -07001219 ep0 = DK_ENTRIES(mp->ma_keys);
1220 size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001221 values = new_values(size);
1222 if (values == NULL) {
1223 PyErr_SetString(PyExc_MemoryError,
1224 "Not enough memory to allocate new values array");
1225 return NULL;
1226 }
1227 for (i = 0; i < size; i++) {
1228 values[i] = ep0[i].me_value;
1229 ep0[i].me_value = NULL;
1230 }
1231 mp->ma_keys->dk_lookup = lookdict_split;
1232 mp->ma_values = values;
1233 }
1234 DK_INCREF(mp->ma_keys);
1235 return mp->ma_keys;
1236}
Christian Heimes99170a52007-12-19 02:07:34 +00001237
1238PyObject *
1239_PyDict_NewPresized(Py_ssize_t minused)
1240{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001241 Py_ssize_t newsize;
1242 PyDictKeysObject *new_keys;
Victor Stinner742da042016-09-07 17:40:12 -07001243 for (newsize = PyDict_MINSIZE;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001244 newsize <= minused && newsize > 0;
1245 newsize <<= 1)
1246 ;
1247 new_keys = new_keys_object(newsize);
1248 if (new_keys == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001250 return new_dict(new_keys, NULL);
Christian Heimes99170a52007-12-19 02:07:34 +00001251}
1252
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001253/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
1254 * that may occur (originally dicts supported only string keys, and exceptions
1255 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001256 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001257 * (suppressed) occurred while computing the key's hash, or that some error
1258 * (suppressed) occurred when comparing keys in the dict's internal probe
1259 * sequence. A nasty example of the latter is when a Python-coded comparison
1260 * function hits a stack-depth error, which can cause this to return NULL
1261 * even if the key is present.
1262 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001263PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001264PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001265{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001266 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001267 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 PyDictObject *mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 PyThreadState *tstate;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001270 PyObject **value_addr;
1271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 if (!PyDict_Check(op))
1273 return NULL;
1274 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001275 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 {
1277 hash = PyObject_Hash(key);
1278 if (hash == -1) {
1279 PyErr_Clear();
1280 return NULL;
1281 }
1282 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 /* We can arrive here with a NULL tstate during initialization: try
1285 running "python -Wi" for an example related to string interning.
1286 Let's just hope that no exception occurs then... This must be
1287 _PyThreadState_Current and not PyThreadState_GET() because in debug
1288 mode, the latter complains if tstate is NULL. */
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001289 tstate = _PyThreadState_UncheckedGet();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (tstate != NULL && tstate->curexc_type != NULL) {
1291 /* preserve the existing exception */
1292 PyObject *err_type, *err_value, *err_tb;
1293 PyErr_Fetch(&err_type, &err_value, &err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001294 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 /* ignore errors */
1296 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001297 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 return NULL;
1299 }
1300 else {
Victor Stinner742da042016-09-07 17:40:12 -07001301 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1302 if (ix < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 PyErr_Clear();
1304 return NULL;
1305 }
1306 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001307 return *value_addr;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001308}
1309
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001310PyObject *
1311_PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1312{
Victor Stinner742da042016-09-07 17:40:12 -07001313 Py_ssize_t ix;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001314 PyDictObject *mp = (PyDictObject *)op;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001315 PyThreadState *tstate;
1316 PyObject **value_addr;
1317
1318 if (!PyDict_Check(op))
1319 return NULL;
1320
1321 /* We can arrive here with a NULL tstate during initialization: try
1322 running "python -Wi" for an example related to string interning.
1323 Let's just hope that no exception occurs then... This must be
1324 _PyThreadState_Current and not PyThreadState_GET() because in debug
1325 mode, the latter complains if tstate is NULL. */
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001326 tstate = _PyThreadState_UncheckedGet();
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001327 if (tstate != NULL && tstate->curexc_type != NULL) {
1328 /* preserve the existing exception */
1329 PyObject *err_type, *err_value, *err_tb;
1330 PyErr_Fetch(&err_type, &err_value, &err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001331 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001332 /* ignore errors */
1333 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001334 if (ix == DKIX_EMPTY)
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001335 return NULL;
1336 }
1337 else {
Victor Stinner742da042016-09-07 17:40:12 -07001338 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1339 if (ix == DKIX_EMPTY) {
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001340 PyErr_Clear();
1341 return NULL;
1342 }
1343 }
1344 return *value_addr;
1345}
1346
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001347/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
1348 This returns NULL *with* an exception set if an exception occurred.
1349 It returns NULL *without* an exception set if the key wasn't present.
1350*/
1351PyObject *
1352PyDict_GetItemWithError(PyObject *op, PyObject *key)
1353{
Victor Stinner742da042016-09-07 17:40:12 -07001354 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001355 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 PyDictObject*mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001357 PyObject **value_addr;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 if (!PyDict_Check(op)) {
1360 PyErr_BadInternalCall();
1361 return NULL;
1362 }
1363 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001364 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 {
1366 hash = PyObject_Hash(key);
1367 if (hash == -1) {
1368 return NULL;
1369 }
1370 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001371
Victor Stinner742da042016-09-07 17:40:12 -07001372 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1373 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001375 return *value_addr;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001376}
1377
Brett Cannonfd074152012-04-14 14:10:13 -04001378PyObject *
1379_PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
1380{
1381 PyObject *kv;
1382 kv = _PyUnicode_FromId(key); /* borrowed */
1383 if (kv == NULL)
1384 return NULL;
1385 return PyDict_GetItemWithError(dp, kv);
1386}
1387
Victor Stinnerb4efc962015-11-20 09:24:02 +01001388/* Fast version of global value lookup (LOAD_GLOBAL).
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001389 * Lookup in globals, then builtins.
Victor Stinnerb4efc962015-11-20 09:24:02 +01001390 *
1391 * Raise an exception and return NULL if an error occurred (ex: computing the
1392 * key hash failed, key comparison failed, ...). Return NULL if the key doesn't
1393 * exist. Return the value if the key exists.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001394 */
1395PyObject *
1396_PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001397{
Victor Stinner742da042016-09-07 17:40:12 -07001398 Py_ssize_t ix;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001399 Py_hash_t hash;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001400 PyObject **value_addr;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001401
1402 if (!PyUnicode_CheckExact(key) ||
1403 (hash = ((PyASCIIObject *) key)->hash) == -1)
1404 {
1405 hash = PyObject_Hash(key);
1406 if (hash == -1)
1407 return NULL;
Antoine Pitroue965d972012-02-27 00:45:12 +01001408 }
Victor Stinnerb4efc962015-11-20 09:24:02 +01001409
1410 /* namespace 1: globals */
Victor Stinner742da042016-09-07 17:40:12 -07001411 ix = globals->ma_keys->dk_lookup(globals, key, hash, &value_addr, NULL);
1412 if (ix == DKIX_ERROR)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001413 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001414 if (ix != DKIX_EMPTY && *value_addr != NULL)
1415 return *value_addr;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001416
1417 /* namespace 2: builtins */
Victor Stinner742da042016-09-07 17:40:12 -07001418 ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value_addr, NULL);
1419 if (ix < 0)
Victor Stinnerb4efc962015-11-20 09:24:02 +01001420 return NULL;
1421 return *value_addr;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001422}
1423
Antoine Pitroue965d972012-02-27 00:45:12 +01001424/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
1425 * dictionary if it's merely replacing the value for an existing key.
1426 * This means that it's safe to loop over a dictionary with PyDict_Next()
1427 * and occasionally replace a value -- but you can't insert new keys or
1428 * remove them.
1429 */
1430int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001431PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001432{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001433 PyDictObject *mp;
1434 Py_hash_t hash;
Antoine Pitroue965d972012-02-27 00:45:12 +01001435 if (!PyDict_Check(op)) {
1436 PyErr_BadInternalCall();
1437 return -1;
1438 }
1439 assert(key);
1440 assert(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001441 mp = (PyDictObject *)op;
1442 if (!PyUnicode_CheckExact(key) ||
1443 (hash = ((PyASCIIObject *) key)->hash) == -1)
1444 {
Antoine Pitroue965d972012-02-27 00:45:12 +01001445 hash = PyObject_Hash(key);
1446 if (hash == -1)
1447 return -1;
1448 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001449
1450 /* insertdict() handles any resizing that might be necessary */
1451 return insertdict(mp, key, hash, value);
Antoine Pitroue965d972012-02-27 00:45:12 +01001452}
1453
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001454int
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001455_PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
1456 Py_hash_t hash)
1457{
1458 PyDictObject *mp;
1459
1460 if (!PyDict_Check(op)) {
1461 PyErr_BadInternalCall();
1462 return -1;
1463 }
1464 assert(key);
1465 assert(value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001466 assert(hash != -1);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001467 mp = (PyDictObject *)op;
1468
1469 /* insertdict() handles any resizing that might be necessary */
1470 return insertdict(mp, key, hash, value);
1471}
1472
1473int
Tim Peters1f5871e2000-07-04 17:44:48 +00001474PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001475{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001476 Py_hash_t hash;
Guido van Rossumd7047b31995-01-02 19:07:15 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 assert(key);
1479 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001480 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 hash = PyObject_Hash(key);
1482 if (hash == -1)
1483 return -1;
1484 }
Victor Stinner742da042016-09-07 17:40:12 -07001485
1486 return _PyDict_DelItem_KnownHash(op, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001487}
1488
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001489int
1490_PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1491{
Victor Stinner742da042016-09-07 17:40:12 -07001492 Py_ssize_t hashpos, ix;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001493 PyDictObject *mp;
1494 PyDictKeyEntry *ep;
1495 PyObject *old_key, *old_value;
1496 PyObject **value_addr;
1497
1498 if (!PyDict_Check(op)) {
1499 PyErr_BadInternalCall();
1500 return -1;
1501 }
1502 assert(key);
1503 assert(hash != -1);
1504 mp = (PyDictObject *)op;
Victor Stinner742da042016-09-07 17:40:12 -07001505 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1506 if (ix == DKIX_ERROR)
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001507 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07001508 if (ix == DKIX_EMPTY || *value_addr == NULL) {
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001509 _PyErr_SetKeyError(key);
1510 return -1;
1511 }
Victor Stinner742da042016-09-07 17:40:12 -07001512 assert(dk_get_index(mp->ma_keys, hashpos) == ix);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001513 old_value = *value_addr;
1514 *value_addr = NULL;
1515 mp->ma_used--;
Victor Stinner742da042016-09-07 17:40:12 -07001516 if (_PyDict_HasSplitTable(mp)) {
1517 mp->ma_keys->dk_usable = 0;
1518 }
1519 else {
1520 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1521 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001522 ENSURE_ALLOWS_DELETIONS(mp);
1523 old_key = ep->me_key;
Victor Stinner742da042016-09-07 17:40:12 -07001524 ep->me_key = NULL;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001525 Py_DECREF(old_key);
1526 }
1527 Py_DECREF(old_value);
1528 return 0;
1529}
1530
Guido van Rossum25831651993-05-19 14:50:45 +00001531void
Tim Peters1f5871e2000-07-04 17:44:48 +00001532PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 PyDictObject *mp;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001535 PyDictKeysObject *oldkeys;
1536 PyObject **oldvalues;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +00001538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 if (!PyDict_Check(op))
1540 return;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001541 mp = ((PyDictObject *)op);
1542 oldkeys = mp->ma_keys;
1543 oldvalues = mp->ma_values;
1544 if (oldvalues == empty_values)
1545 return;
1546 /* Empty the dict... */
1547 DK_INCREF(Py_EMPTY_KEYS);
1548 mp->ma_keys = Py_EMPTY_KEYS;
1549 mp->ma_values = empty_values;
1550 mp->ma_used = 0;
1551 /* ...then clear the keys and values */
1552 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001553 n = oldkeys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001554 for (i = 0; i < n; i++)
1555 Py_CLEAR(oldvalues[i]);
1556 free_values(oldvalues);
1557 DK_DECREF(oldkeys);
1558 }
1559 else {
1560 assert(oldkeys->dk_refcnt == 1);
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001561 DK_DECREF(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001562 }
1563}
1564
1565/* Returns -1 if no more items (or op is not a dict),
1566 * index of item otherwise. Stores value in pvalue
1567 */
1568Py_LOCAL_INLINE(Py_ssize_t)
1569dict_next(PyObject *op, Py_ssize_t i, PyObject **pvalue)
1570{
Victor Stinner742da042016-09-07 17:40:12 -07001571 Py_ssize_t n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001572 PyDictObject *mp;
Victor Stinner742da042016-09-07 17:40:12 -07001573 PyObject **value_ptr = NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001574
1575 if (!PyDict_Check(op))
1576 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001578 if (i < 0)
1579 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07001580
1581 n = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001582 if (mp->ma_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001583 for (; i < n; i++) {
1584 value_ptr = &mp->ma_values[i];
1585 if (*value_ptr != NULL)
1586 break;
1587 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001589 else {
Victor Stinner742da042016-09-07 17:40:12 -07001590 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
1591 for (; i < n; i++) {
1592 value_ptr = &ep0[i].me_value;
1593 if (*value_ptr != NULL)
1594 break;
1595 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 }
Victor Stinner742da042016-09-07 17:40:12 -07001597 if (i >= n)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001598 return -1;
1599 if (pvalue)
1600 *pvalue = *value_ptr;
1601 return i;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001602}
1603
Tim Peters080c88b2003-02-15 03:01:11 +00001604/*
1605 * Iterate over a dict. Use like so:
1606 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001607 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +00001608 * PyObject *key, *value;
1609 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +00001610 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Tim Peters080c88b2003-02-15 03:01:11 +00001611 * Refer to borrowed references in key and value.
1612 * }
1613 *
1614 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +00001615 * mutates the dict. One exception: it is safe if the loop merely changes
1616 * the values associated with the keys (but doesn't insert new keys or
1617 * delete keys), via PyDict_SetItem().
1618 */
Guido van Rossum25831651993-05-19 14:50:45 +00001619int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001620PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001621{
Victor Stinner742da042016-09-07 17:40:12 -07001622 PyDictObject *mp = (PyDictObject*)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001623 Py_ssize_t i = dict_next(op, *ppos, pvalue);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 if (i < 0)
1625 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001626 mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 *ppos = i+1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 if (pkey)
Victor Stinner742da042016-09-07 17:40:12 -07001629 *pkey = DK_ENTRIES(mp->ma_keys)[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001631}
1632
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001633/* Internal version of PyDict_Next that returns a hash value in addition
1634 * to the key and value.
1635 */
Thomas Wouterscf297e42007-02-23 15:07:44 +00001636int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001637_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
1638 PyObject **pvalue, Py_hash_t *phash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001639{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001640 PyDictObject *mp;
Victor Stinner742da042016-09-07 17:40:12 -07001641 PyDictKeyEntry *ep0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001642 Py_ssize_t i = dict_next(op, *ppos, pvalue);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 if (i < 0)
1644 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001645 mp = (PyDictObject *)op;
Victor Stinner742da042016-09-07 17:40:12 -07001646 ep0 = DK_ENTRIES(mp->ma_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 *ppos = i+1;
Victor Stinner742da042016-09-07 17:40:12 -07001648 *phash = ep0[i].me_hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 if (pkey)
Victor Stinner742da042016-09-07 17:40:12 -07001650 *pkey = ep0[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 return 1;
Thomas Wouterscf297e42007-02-23 15:07:44 +00001652}
1653
Eric Snow96c6af92015-05-29 22:21:39 -06001654/* Internal version of dict.pop(). */
1655PyObject *
1656_PyDict_Pop(PyDictObject *mp, PyObject *key, PyObject *deflt)
1657{
1658 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001659 Py_ssize_t ix, hashpos;
Eric Snow96c6af92015-05-29 22:21:39 -06001660 PyObject *old_value, *old_key;
1661 PyDictKeyEntry *ep;
1662 PyObject **value_addr;
1663
1664 if (mp->ma_used == 0) {
1665 if (deflt) {
1666 Py_INCREF(deflt);
1667 return deflt;
1668 }
1669 _PyErr_SetKeyError(key);
1670 return NULL;
1671 }
1672 if (!PyUnicode_CheckExact(key) ||
1673 (hash = ((PyASCIIObject *) key)->hash) == -1) {
1674 hash = PyObject_Hash(key);
1675 if (hash == -1)
1676 return NULL;
1677 }
Victor Stinner742da042016-09-07 17:40:12 -07001678 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1679 if (ix == DKIX_ERROR)
Eric Snow96c6af92015-05-29 22:21:39 -06001680 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001681 if (ix == DKIX_EMPTY) {
Eric Snow96c6af92015-05-29 22:21:39 -06001682 if (deflt) {
1683 Py_INCREF(deflt);
1684 return deflt;
1685 }
1686 _PyErr_SetKeyError(key);
1687 return NULL;
1688 }
Victor Stinner742da042016-09-07 17:40:12 -07001689 old_value = *value_addr;
Eric Snow96c6af92015-05-29 22:21:39 -06001690 *value_addr = NULL;
1691 mp->ma_used--;
1692 if (!_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -07001693 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1694 ep = &DK_ENTRIES(mp->ma_keys)[ix];
Eric Snow96c6af92015-05-29 22:21:39 -06001695 ENSURE_ALLOWS_DELETIONS(mp);
1696 old_key = ep->me_key;
Victor Stinner742da042016-09-07 17:40:12 -07001697 ep->me_key = NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06001698 Py_DECREF(old_key);
1699 }
1700 return old_value;
1701}
1702
1703/* Internal version of dict.from_keys(). It is subclass-friendly. */
1704PyObject *
1705_PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
1706{
1707 PyObject *it; /* iter(iterable) */
1708 PyObject *key;
1709 PyObject *d;
1710 int status;
1711
1712 d = PyObject_CallObject(cls, NULL);
1713 if (d == NULL)
1714 return NULL;
1715
1716 if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
1717 if (PyDict_CheckExact(iterable)) {
1718 PyDictObject *mp = (PyDictObject *)d;
1719 PyObject *oldvalue;
1720 Py_ssize_t pos = 0;
1721 PyObject *key;
1722 Py_hash_t hash;
1723
Victor Stinner742da042016-09-07 17:40:12 -07001724 if (dictresize(mp, ESTIMATE_SIZE(Py_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001725 Py_DECREF(d);
1726 return NULL;
1727 }
1728
1729 while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
1730 if (insertdict(mp, key, hash, value)) {
1731 Py_DECREF(d);
1732 return NULL;
1733 }
1734 }
1735 return d;
1736 }
1737 if (PyAnySet_CheckExact(iterable)) {
1738 PyDictObject *mp = (PyDictObject *)d;
1739 Py_ssize_t pos = 0;
1740 PyObject *key;
1741 Py_hash_t hash;
1742
Victor Stinner742da042016-09-07 17:40:12 -07001743 if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001744 Py_DECREF(d);
1745 return NULL;
1746 }
1747
1748 while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
1749 if (insertdict(mp, key, hash, value)) {
1750 Py_DECREF(d);
1751 return NULL;
1752 }
1753 }
1754 return d;
1755 }
1756 }
1757
1758 it = PyObject_GetIter(iterable);
1759 if (it == NULL){
1760 Py_DECREF(d);
1761 return NULL;
1762 }
1763
1764 if (PyDict_CheckExact(d)) {
1765 while ((key = PyIter_Next(it)) != NULL) {
1766 status = PyDict_SetItem(d, key, value);
1767 Py_DECREF(key);
1768 if (status < 0)
1769 goto Fail;
1770 }
1771 } else {
1772 while ((key = PyIter_Next(it)) != NULL) {
1773 status = PyObject_SetItem(d, key, value);
1774 Py_DECREF(key);
1775 if (status < 0)
1776 goto Fail;
1777 }
1778 }
1779
1780 if (PyErr_Occurred())
1781 goto Fail;
1782 Py_DECREF(it);
1783 return d;
1784
1785Fail:
1786 Py_DECREF(it);
1787 Py_DECREF(d);
1788 return NULL;
1789}
1790
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001791/* Methods */
1792
1793static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001794dict_dealloc(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001795{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001796 PyObject **values = mp->ma_values;
1797 PyDictKeysObject *keys = mp->ma_keys;
1798 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 PyObject_GC_UnTrack(mp);
1800 Py_TRASHCAN_SAFE_BEGIN(mp)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001801 if (values != NULL) {
1802 if (values != empty_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001803 for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001804 Py_XDECREF(values[i]);
1805 }
1806 free_values(values);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001808 DK_DECREF(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 }
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02001810 else if (keys != NULL) {
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001811 assert(keys->dk_refcnt == 1);
1812 DK_DECREF(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001813 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
1815 free_list[numfree++] = mp;
1816 else
1817 Py_TYPE(mp)->tp_free((PyObject *)mp);
1818 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001819}
1820
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001821
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001822static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001823dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 Py_ssize_t i;
Victor Stinnerf91929b2013-11-19 13:07:38 +01001826 PyObject *key = NULL, *value = NULL;
1827 _PyUnicodeWriter writer;
1828 int first;
Guido van Rossum255443b1998-04-10 22:47:14 +00001829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 i = Py_ReprEnter((PyObject *)mp);
1831 if (i != 0) {
1832 return i > 0 ? PyUnicode_FromString("{...}") : NULL;
1833 }
Guido van Rossum255443b1998-04-10 22:47:14 +00001834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 if (mp->ma_used == 0) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01001836 Py_ReprLeave((PyObject *)mp);
1837 return PyUnicode_FromString("{}");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 }
Tim Petersa7259592001-06-16 05:11:17 +00001839
Victor Stinnerf91929b2013-11-19 13:07:38 +01001840 _PyUnicodeWriter_Init(&writer);
1841 writer.overallocate = 1;
1842 /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
1843 writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +00001844
Victor Stinnerf91929b2013-11-19 13:07:38 +01001845 if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
1846 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00001847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 /* Do repr() on each key+value pair, and insert ": " between them.
1849 Note that repr may mutate the dict. */
1850 i = 0;
Victor Stinnerf91929b2013-11-19 13:07:38 +01001851 first = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01001853 PyObject *s;
1854 int res;
1855
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001856 /* Prevent repr from deleting key or value during key format. */
1857 Py_INCREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 Py_INCREF(value);
Victor Stinnerf97dfd72013-07-18 01:00:45 +02001859
Victor Stinnerf91929b2013-11-19 13:07:38 +01001860 if (!first) {
1861 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
1862 goto error;
1863 }
1864 first = 0;
1865
1866 s = PyObject_Repr(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 if (s == NULL)
Victor Stinnerf91929b2013-11-19 13:07:38 +01001868 goto error;
1869 res = _PyUnicodeWriter_WriteStr(&writer, s);
1870 Py_DECREF(s);
1871 if (res < 0)
1872 goto error;
1873
1874 if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
1875 goto error;
1876
1877 s = PyObject_Repr(value);
1878 if (s == NULL)
1879 goto error;
1880 res = _PyUnicodeWriter_WriteStr(&writer, s);
1881 Py_DECREF(s);
1882 if (res < 0)
1883 goto error;
1884
1885 Py_CLEAR(key);
1886 Py_CLEAR(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 }
Tim Petersa7259592001-06-16 05:11:17 +00001888
Victor Stinnerf91929b2013-11-19 13:07:38 +01001889 writer.overallocate = 0;
1890 if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
1891 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 Py_ReprLeave((PyObject *)mp);
Victor Stinnerf91929b2013-11-19 13:07:38 +01001894
1895 return _PyUnicodeWriter_Finish(&writer);
1896
1897error:
1898 Py_ReprLeave((PyObject *)mp);
1899 _PyUnicodeWriter_Dealloc(&writer);
1900 Py_XDECREF(key);
1901 Py_XDECREF(value);
1902 return NULL;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001903}
1904
Martin v. Löwis18e16552006-02-15 17:27:45 +00001905static Py_ssize_t
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001906dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 return mp->ma_used;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001909}
1910
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001911static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001912dict_subscript(PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 PyObject *v;
Victor Stinner742da042016-09-07 17:40:12 -07001915 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001916 Py_hash_t hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001917 PyObject **value_addr;
1918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001920 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 hash = PyObject_Hash(key);
1922 if (hash == -1)
1923 return NULL;
1924 }
Victor Stinner742da042016-09-07 17:40:12 -07001925 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1926 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001928 if (ix == DKIX_EMPTY || *value_addr == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 if (!PyDict_CheckExact(mp)) {
1930 /* Look up __missing__ method if we're a subclass. */
1931 PyObject *missing, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05001932 _Py_IDENTIFIER(__missing__);
1933 missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 if (missing != NULL) {
1935 res = PyObject_CallFunctionObjArgs(missing,
1936 key, NULL);
1937 Py_DECREF(missing);
1938 return res;
1939 }
1940 else if (PyErr_Occurred())
1941 return NULL;
1942 }
Raymond Hettinger69492da2013-09-02 15:59:26 -07001943 _PyErr_SetKeyError(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 return NULL;
1945 }
Victor Stinner742da042016-09-07 17:40:12 -07001946 v = *value_addr;
1947 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001949}
1950
1951static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001952dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 if (w == NULL)
1955 return PyDict_DelItem((PyObject *)mp, v);
1956 else
1957 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001958}
1959
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001960static PyMappingMethods dict_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 (lenfunc)dict_length, /*mp_length*/
1962 (binaryfunc)dict_subscript, /*mp_subscript*/
1963 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001964};
1965
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001966static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001967dict_keys(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001968{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001969 PyObject *v;
1970 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001971 PyDictKeyEntry *ep;
1972 Py_ssize_t size, n, offset;
1973 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001974
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001975 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 n = mp->ma_used;
1977 v = PyList_New(n);
1978 if (v == NULL)
1979 return NULL;
1980 if (n != mp->ma_used) {
1981 /* Durnit. The allocations caused the dict to resize.
1982 * Just start over, this shouldn't normally happen.
1983 */
1984 Py_DECREF(v);
1985 goto again;
1986 }
Victor Stinner742da042016-09-07 17:40:12 -07001987 ep = DK_ENTRIES(mp->ma_keys);
1988 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001989 if (mp->ma_values) {
1990 value_ptr = mp->ma_values;
1991 offset = sizeof(PyObject *);
1992 }
1993 else {
1994 value_ptr = &ep[0].me_value;
1995 offset = sizeof(PyDictKeyEntry);
1996 }
1997 for (i = 0, j = 0; i < size; i++) {
1998 if (*value_ptr != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 PyObject *key = ep[i].me_key;
2000 Py_INCREF(key);
2001 PyList_SET_ITEM(v, j, key);
2002 j++;
2003 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002004 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 }
2006 assert(j == n);
2007 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002008}
2009
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002010static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002011dict_values(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002012{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002013 PyObject *v;
2014 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002015 Py_ssize_t size, n, offset;
2016 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002017
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002018 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 n = mp->ma_used;
2020 v = PyList_New(n);
2021 if (v == NULL)
2022 return NULL;
2023 if (n != mp->ma_used) {
2024 /* Durnit. The allocations caused the dict to resize.
2025 * Just start over, this shouldn't normally happen.
2026 */
2027 Py_DECREF(v);
2028 goto again;
2029 }
Victor Stinner742da042016-09-07 17:40:12 -07002030 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002031 if (mp->ma_values) {
2032 value_ptr = mp->ma_values;
2033 offset = sizeof(PyObject *);
2034 }
2035 else {
Victor Stinner742da042016-09-07 17:40:12 -07002036 value_ptr = &(DK_ENTRIES(mp->ma_keys)[0].me_value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002037 offset = sizeof(PyDictKeyEntry);
2038 }
2039 for (i = 0, j = 0; i < size; i++) {
2040 PyObject *value = *value_ptr;
2041 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2042 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 Py_INCREF(value);
2044 PyList_SET_ITEM(v, j, value);
2045 j++;
2046 }
2047 }
2048 assert(j == n);
2049 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002050}
2051
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002052static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002053dict_items(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002054{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002055 PyObject *v;
2056 Py_ssize_t i, j, n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002057 Py_ssize_t size, offset;
2058 PyObject *item, *key;
2059 PyDictKeyEntry *ep;
2060 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 /* Preallocate the list of tuples, to avoid allocations during
2063 * the loop over the items, which could trigger GC, which
2064 * could resize the dict. :-(
2065 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002066 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 n = mp->ma_used;
2068 v = PyList_New(n);
2069 if (v == NULL)
2070 return NULL;
2071 for (i = 0; i < n; i++) {
2072 item = PyTuple_New(2);
2073 if (item == NULL) {
2074 Py_DECREF(v);
2075 return NULL;
2076 }
2077 PyList_SET_ITEM(v, i, item);
2078 }
2079 if (n != mp->ma_used) {
2080 /* Durnit. The allocations caused the dict to resize.
2081 * Just start over, this shouldn't normally happen.
2082 */
2083 Py_DECREF(v);
2084 goto again;
2085 }
2086 /* Nothing we do below makes any function calls. */
Victor Stinner742da042016-09-07 17:40:12 -07002087 ep = DK_ENTRIES(mp->ma_keys);
2088 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002089 if (mp->ma_values) {
2090 value_ptr = mp->ma_values;
2091 offset = sizeof(PyObject *);
2092 }
2093 else {
2094 value_ptr = &ep[0].me_value;
2095 offset = sizeof(PyDictKeyEntry);
2096 }
2097 for (i = 0, j = 0; i < size; i++) {
2098 PyObject *value = *value_ptr;
2099 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2100 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 key = ep[i].me_key;
2102 item = PyList_GET_ITEM(v, j);
2103 Py_INCREF(key);
2104 PyTuple_SET_ITEM(item, 0, key);
2105 Py_INCREF(value);
2106 PyTuple_SET_ITEM(item, 1, value);
2107 j++;
2108 }
2109 }
2110 assert(j == n);
2111 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002112}
2113
Larry Hastings5c661892014-01-24 06:17:25 -08002114/*[clinic input]
2115@classmethod
2116dict.fromkeys
Larry Hastings5c661892014-01-24 06:17:25 -08002117 iterable: object
2118 value: object=None
2119 /
2120
2121Returns a new dict with keys from iterable and values equal to value.
2122[clinic start generated code]*/
2123
Larry Hastings5c661892014-01-24 06:17:25 -08002124static PyObject *
2125dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002126/*[clinic end generated code: output=8fb98e4b10384999 input=b85a667f9bf4669d]*/
Larry Hastings5c661892014-01-24 06:17:25 -08002127{
Eric Snow96c6af92015-05-29 22:21:39 -06002128 return _PyDict_FromKeys((PyObject *)type, iterable, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002129}
2130
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002131static int
Victor Stinner742da042016-09-07 17:40:12 -07002132dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
2133 const char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 PyObject *arg = NULL;
2136 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
2139 result = -1;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 else if (arg != NULL) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02002142 _Py_IDENTIFIER(keys);
2143 if (_PyObject_HasAttrId(arg, &PyId_keys))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 result = PyDict_Merge(self, arg, 1);
2145 else
2146 result = PyDict_MergeFromSeq2(self, arg, 1);
2147 }
2148 if (result == 0 && kwds != NULL) {
2149 if (PyArg_ValidateKeywordArguments(kwds))
2150 result = PyDict_Merge(self, kwds, 1);
2151 else
2152 result = -1;
2153 }
2154 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002155}
2156
2157static PyObject *
2158dict_update(PyObject *self, PyObject *args, PyObject *kwds)
2159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 if (dict_update_common(self, args, kwds, "update") != -1)
2161 Py_RETURN_NONE;
2162 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002163}
2164
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002165/* Update unconditionally replaces existing items.
2166 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00002167 otherwise it leaves existing items unchanged.
2168
2169 PyDict_{Update,Merge} update/merge from a mapping object.
2170
Tim Petersf582b822001-12-11 18:51:08 +00002171 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00002172 producing iterable objects of length 2.
2173*/
2174
Tim Petersf582b822001-12-11 18:51:08 +00002175int
Tim Peters1fc240e2001-10-26 05:06:50 +00002176PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
2177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 PyObject *it; /* iter(seq2) */
2179 Py_ssize_t i; /* index into seq2 of current element */
2180 PyObject *item; /* seq2[i] */
2181 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00002182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 assert(d != NULL);
2184 assert(PyDict_Check(d));
2185 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 it = PyObject_GetIter(seq2);
2188 if (it == NULL)
2189 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 for (i = 0; ; ++i) {
2192 PyObject *key, *value;
2193 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00002194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 fast = NULL;
2196 item = PyIter_Next(it);
2197 if (item == NULL) {
2198 if (PyErr_Occurred())
2199 goto Fail;
2200 break;
2201 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 /* Convert item to sequence, and verify length 2. */
2204 fast = PySequence_Fast(item, "");
2205 if (fast == NULL) {
2206 if (PyErr_ExceptionMatches(PyExc_TypeError))
2207 PyErr_Format(PyExc_TypeError,
2208 "cannot convert dictionary update "
2209 "sequence element #%zd to a sequence",
2210 i);
2211 goto Fail;
2212 }
2213 n = PySequence_Fast_GET_SIZE(fast);
2214 if (n != 2) {
2215 PyErr_Format(PyExc_ValueError,
2216 "dictionary update sequence element #%zd "
2217 "has length %zd; 2 is required",
2218 i, n);
2219 goto Fail;
2220 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 /* Update/merge with this (key, value) pair. */
2223 key = PySequence_Fast_GET_ITEM(fast, 0);
2224 value = PySequence_Fast_GET_ITEM(fast, 1);
2225 if (override || PyDict_GetItem(d, key) == NULL) {
2226 int status = PyDict_SetItem(d, key, value);
2227 if (status < 0)
2228 goto Fail;
2229 }
2230 Py_DECREF(fast);
2231 Py_DECREF(item);
2232 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 i = 0;
2235 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00002236Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 Py_XDECREF(item);
2238 Py_XDECREF(fast);
2239 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002240Return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 Py_DECREF(it);
2242 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00002243}
2244
Tim Peters6d6c1a32001-08-02 04:15:00 +00002245int
2246PyDict_Update(PyObject *a, PyObject *b)
2247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 return PyDict_Merge(a, b, 1);
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002249}
2250
2251int
2252PyDict_Merge(PyObject *a, PyObject *b, int override)
2253{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002254 PyDictObject *mp, *other;
2255 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -07002256 PyDictKeyEntry *entry, *ep0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 /* We accept for the argument either a concrete dictionary object,
2259 * or an abstract "mapping" object. For the former, we can do
2260 * things quite efficiently. For the latter, we only require that
2261 * PyMapping_Keys() and PyObject_GetItem() be supported.
2262 */
2263 if (a == NULL || !PyDict_Check(a) || b == NULL) {
2264 PyErr_BadInternalCall();
2265 return -1;
2266 }
2267 mp = (PyDictObject*)a;
2268 if (PyDict_Check(b)) {
2269 other = (PyDictObject*)b;
2270 if (other == mp || other->ma_used == 0)
2271 /* a.update(a) or a.update({}); nothing to do */
2272 return 0;
2273 if (mp->ma_used == 0)
2274 /* Since the target dict is empty, PyDict_GetItem()
2275 * always returns NULL. Setting override to 1
2276 * skips the unnecessary test.
2277 */
2278 override = 1;
2279 /* Do one big resize at the start, rather than
2280 * incrementally resizing as we insert new items. Expect
2281 * that there will be no (or few) overlapping keys.
2282 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002283 if (mp->ma_keys->dk_usable * 3 < other->ma_used * 2)
2284 if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07002286 ep0 = DK_ENTRIES(other->ma_keys);
2287 for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002288 PyObject *key, *value;
2289 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002290 entry = &ep0[i];
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002291 key = entry->me_key;
2292 hash = entry->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002293 if (other->ma_values)
2294 value = other->ma_values[i];
2295 else
2296 value = entry->me_value;
2297
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002298 if (value != NULL) {
2299 int err = 0;
2300 Py_INCREF(key);
2301 Py_INCREF(value);
2302 if (override || PyDict_GetItem(a, key) == NULL)
2303 err = insertdict(mp, key, hash, value);
2304 Py_DECREF(value);
2305 Py_DECREF(key);
2306 if (err != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 return -1;
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002308
Victor Stinner742da042016-09-07 17:40:12 -07002309 if (n != other->ma_keys->dk_nentries) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002310 PyErr_SetString(PyExc_RuntimeError,
2311 "dict mutated during update");
2312 return -1;
2313 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 }
2315 }
2316 }
2317 else {
2318 /* Do it the generic, slower way */
2319 PyObject *keys = PyMapping_Keys(b);
2320 PyObject *iter;
2321 PyObject *key, *value;
2322 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 if (keys == NULL)
2325 /* Docstring says this is equivalent to E.keys() so
2326 * if E doesn't have a .keys() method we want
2327 * AttributeError to percolate up. Might as well
2328 * do the same for any other error.
2329 */
2330 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 iter = PyObject_GetIter(keys);
2333 Py_DECREF(keys);
2334 if (iter == NULL)
2335 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
2338 if (!override && PyDict_GetItem(a, key) != NULL) {
2339 Py_DECREF(key);
2340 continue;
2341 }
2342 value = PyObject_GetItem(b, key);
2343 if (value == NULL) {
2344 Py_DECREF(iter);
2345 Py_DECREF(key);
2346 return -1;
2347 }
2348 status = PyDict_SetItem(a, key, value);
2349 Py_DECREF(key);
2350 Py_DECREF(value);
2351 if (status < 0) {
2352 Py_DECREF(iter);
2353 return -1;
2354 }
2355 }
2356 Py_DECREF(iter);
2357 if (PyErr_Occurred())
2358 /* Iterator completed, via error */
2359 return -1;
2360 }
2361 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002362}
2363
2364static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002365dict_copy(PyDictObject *mp)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002368}
2369
2370PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002371PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 PyObject *copy;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002374 PyDictObject *mp;
2375 Py_ssize_t i, n;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 if (o == NULL || !PyDict_Check(o)) {
2378 PyErr_BadInternalCall();
2379 return NULL;
2380 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002381 mp = (PyDictObject *)o;
2382 if (_PyDict_HasSplitTable(mp)) {
2383 PyDictObject *split_copy;
Victor Stinner742da042016-09-07 17:40:12 -07002384 Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
2385 PyObject **newvalues;
2386 newvalues = new_values(size);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002387 if (newvalues == NULL)
2388 return PyErr_NoMemory();
2389 split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
2390 if (split_copy == NULL) {
2391 free_values(newvalues);
2392 return NULL;
2393 }
2394 split_copy->ma_values = newvalues;
2395 split_copy->ma_keys = mp->ma_keys;
2396 split_copy->ma_used = mp->ma_used;
2397 DK_INCREF(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002398 for (i = 0, n = size; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002399 PyObject *value = mp->ma_values[i];
2400 Py_XINCREF(value);
2401 split_copy->ma_values[i] = value;
2402 }
Benjamin Peterson7ce67e42012-04-24 10:32:57 -04002403 if (_PyObject_GC_IS_TRACKED(mp))
2404 _PyObject_GC_TRACK(split_copy);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002405 return (PyObject *)split_copy;
2406 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 copy = PyDict_New();
2408 if (copy == NULL)
2409 return NULL;
2410 if (PyDict_Merge(copy, o, 1) == 0)
2411 return copy;
2412 Py_DECREF(copy);
2413 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002414}
2415
Martin v. Löwis18e16552006-02-15 17:27:45 +00002416Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00002417PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00002418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 if (mp == NULL || !PyDict_Check(mp)) {
2420 PyErr_BadInternalCall();
2421 return -1;
2422 }
2423 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00002424}
2425
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002426PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002427PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 if (mp == NULL || !PyDict_Check(mp)) {
2430 PyErr_BadInternalCall();
2431 return NULL;
2432 }
2433 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002434}
2435
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002436PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002437PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 if (mp == NULL || !PyDict_Check(mp)) {
2440 PyErr_BadInternalCall();
2441 return NULL;
2442 }
2443 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002444}
2445
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002446PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002447PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 if (mp == NULL || !PyDict_Check(mp)) {
2450 PyErr_BadInternalCall();
2451 return NULL;
2452 }
2453 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002454}
2455
Tim Peterse63415e2001-05-08 04:38:29 +00002456/* Return 1 if dicts equal, 0 if not, -1 if error.
2457 * Gets out as soon as any difference is detected.
2458 * Uses only Py_EQ comparison.
2459 */
2460static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002461dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00002462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00002464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 if (a->ma_used != b->ma_used)
2466 /* can't be equal if # of entries differ */
2467 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Victor Stinner742da042016-09-07 17:40:12 -07002469 for (i = 0; i < a->ma_keys->dk_nentries; i++) {
2470 PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002471 PyObject *aval;
2472 if (a->ma_values)
2473 aval = a->ma_values[i];
2474 else
2475 aval = ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 if (aval != NULL) {
2477 int cmp;
2478 PyObject *bval;
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002479 PyObject **vaddr;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002480 PyObject *key = ep->me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 /* temporarily bump aval's refcount to ensure it stays
2482 alive until we're done with it */
2483 Py_INCREF(aval);
2484 /* ditto for key */
2485 Py_INCREF(key);
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002486 /* reuse the known hash value */
Victor Stinner742da042016-09-07 17:40:12 -07002487 if ((b->ma_keys->dk_lookup)(b, key, ep->me_hash, &vaddr, NULL) < 0)
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002488 bval = NULL;
2489 else
2490 bval = *vaddr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 Py_DECREF(key);
2492 if (bval == NULL) {
2493 Py_DECREF(aval);
2494 if (PyErr_Occurred())
2495 return -1;
2496 return 0;
2497 }
2498 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
2499 Py_DECREF(aval);
2500 if (cmp <= 0) /* error or not equal */
2501 return cmp;
2502 }
2503 }
2504 return 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002505}
Tim Peterse63415e2001-05-08 04:38:29 +00002506
2507static PyObject *
2508dict_richcompare(PyObject *v, PyObject *w, int op)
2509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 int cmp;
2511 PyObject *res;
Tim Peterse63415e2001-05-08 04:38:29 +00002512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 if (!PyDict_Check(v) || !PyDict_Check(w)) {
2514 res = Py_NotImplemented;
2515 }
2516 else if (op == Py_EQ || op == Py_NE) {
2517 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
2518 if (cmp < 0)
2519 return NULL;
2520 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
2521 }
2522 else
2523 res = Py_NotImplemented;
2524 Py_INCREF(res);
2525 return res;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002526}
Tim Peterse63415e2001-05-08 04:38:29 +00002527
Larry Hastings61272b72014-01-07 12:41:53 -08002528/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002529
2530@coexist
2531dict.__contains__
2532
2533 key: object
2534 /
2535
Meador Ingee02de8c2014-01-14 16:48:31 -06002536True if D has a key k, else False.
Larry Hastings61272b72014-01-07 12:41:53 -08002537[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002538
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002539static PyObject *
Larry Hastingsc2047262014-01-25 20:43:29 -08002540dict___contains__(PyDictObject *self, PyObject *key)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002541/*[clinic end generated code: output=a3d03db709ed6e6b input=b852b2a19b51ab24]*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002542{
Larry Hastingsc2047262014-01-25 20:43:29 -08002543 register PyDictObject *mp = self;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002544 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002545 Py_ssize_t ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002546 PyObject **value_addr;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002549 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 hash = PyObject_Hash(key);
2551 if (hash == -1)
2552 return NULL;
2553 }
Victor Stinner742da042016-09-07 17:40:12 -07002554 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2555 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002557 if (ix == DKIX_EMPTY || *value_addr == NULL)
2558 Py_RETURN_FALSE;
2559 Py_RETURN_TRUE;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002560}
2561
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002562static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002563dict_get(PyDictObject *mp, PyObject *args)
Barry Warsawc38c5da1997-10-06 17:49:20 +00002564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 PyObject *key;
2566 PyObject *failobj = Py_None;
2567 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002568 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002569 Py_ssize_t ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002570 PyObject **value_addr;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
2573 return NULL;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002576 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 hash = PyObject_Hash(key);
2578 if (hash == -1)
2579 return NULL;
2580 }
Victor Stinner742da042016-09-07 17:40:12 -07002581 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2582 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002584 if (ix == DKIX_EMPTY || *value_addr == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 val = failobj;
Victor Stinner742da042016-09-07 17:40:12 -07002586 else
2587 val = *value_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 Py_INCREF(val);
2589 return val;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002590}
2591
Benjamin Peterson00e98862013-03-07 22:16:29 -05002592PyObject *
2593PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
Guido van Rossum164452c2000-08-08 16:12:54 +00002594{
Benjamin Peterson00e98862013-03-07 22:16:29 -05002595 PyDictObject *mp = (PyDictObject *)d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002597 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002598 Py_ssize_t hashpos, ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002599 PyDictKeyEntry *ep;
2600 PyObject **value_addr;
Guido van Rossum164452c2000-08-08 16:12:54 +00002601
Benjamin Peterson00e98862013-03-07 22:16:29 -05002602 if (!PyDict_Check(d)) {
2603 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 return NULL;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002605 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002607 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 hash = PyObject_Hash(key);
2609 if (hash == -1)
2610 return NULL;
2611 }
Victor Stinner742da042016-09-07 17:40:12 -07002612 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
2613 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002615 if (ix == DKIX_EMPTY || *value_addr == NULL) {
2616 val = defaultobj;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002617 if (mp->ma_keys->dk_usable <= 0) {
2618 /* Need to resize. */
2619 if (insertion_resize(mp) < 0)
2620 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002621 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002622 }
Victor Stinner742da042016-09-07 17:40:12 -07002623 ix = mp->ma_keys->dk_nentries;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002624 Py_INCREF(defaultobj);
Benjamin Petersonb1efa532013-03-04 09:47:50 -05002625 Py_INCREF(key);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002626 MAINTAIN_TRACKING(mp, key, defaultobj);
Victor Stinner742da042016-09-07 17:40:12 -07002627 dk_set_index(mp->ma_keys, hashpos, ix);
2628 ep = &DK_ENTRIES(mp->ma_keys)[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002629 ep->me_key = key;
2630 ep->me_hash = hash;
Victor Stinner742da042016-09-07 17:40:12 -07002631 if (mp->ma_values) {
2632 mp->ma_values[ix] = val;
2633 }
2634 else {
2635 ep->me_value = val;
2636 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002637 mp->ma_keys->dk_usable--;
Victor Stinner742da042016-09-07 17:40:12 -07002638 mp->ma_keys->dk_nentries++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002639 mp->ma_used++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 }
Victor Stinner742da042016-09-07 17:40:12 -07002641 else
2642 val = *value_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 return val;
Guido van Rossum164452c2000-08-08 16:12:54 +00002644}
2645
Benjamin Peterson00e98862013-03-07 22:16:29 -05002646static PyObject *
2647dict_setdefault(PyDictObject *mp, PyObject *args)
2648{
2649 PyObject *key, *val;
2650 PyObject *defaultobj = Py_None;
2651
2652 if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &defaultobj))
2653 return NULL;
2654
Benjamin Peterson55898502013-03-08 08:36:49 -05002655 val = PyDict_SetDefault((PyObject *)mp, key, defaultobj);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002656 Py_XINCREF(val);
2657 return val;
2658}
Guido van Rossum164452c2000-08-08 16:12:54 +00002659
2660static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002661dict_clear(PyDictObject *mp)
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 PyDict_Clear((PyObject *)mp);
2664 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002665}
2666
Guido van Rossumba6ab842000-12-12 22:02:18 +00002667static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002668dict_pop(PyDictObject *mp, PyObject *args)
Guido van Rossume027d982002-04-12 15:11:59 +00002669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 PyObject *key, *deflt = NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00002671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
2673 return NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06002674
2675 return _PyDict_Pop(mp, key, deflt);
Guido van Rossume027d982002-04-12 15:11:59 +00002676}
2677
2678static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002679dict_popitem(PyDictObject *mp)
Guido van Rossumba6ab842000-12-12 22:02:18 +00002680{
Victor Stinner742da042016-09-07 17:40:12 -07002681 Py_ssize_t i, j;
2682 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 PyObject *res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 /* Allocate the result tuple before checking the size. Believe it
2686 * or not, this allocation could trigger a garbage collection which
2687 * could empty the dict, so if we checked the size first and that
2688 * happened, the result would be an infinite loop (searching for an
2689 * entry that no longer exists). Note that the usual popitem()
2690 * idiom is "while d: k, v = d.popitem()". so needing to throw the
2691 * tuple away if the dict *is* empty isn't a significant
2692 * inefficiency -- possible, but unlikely in practice.
2693 */
2694 res = PyTuple_New(2);
2695 if (res == NULL)
2696 return NULL;
2697 if (mp->ma_used == 0) {
2698 Py_DECREF(res);
2699 PyErr_SetString(PyExc_KeyError,
2700 "popitem(): dictionary is empty");
2701 return NULL;
2702 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002703 /* Convert split table to combined table */
2704 if (mp->ma_keys->dk_lookup == lookdict_split) {
2705 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
2706 Py_DECREF(res);
2707 return NULL;
2708 }
2709 }
2710 ENSURE_ALLOWS_DELETIONS(mp);
Victor Stinner742da042016-09-07 17:40:12 -07002711
2712 /* Pop last item */
2713 ep0 = DK_ENTRIES(mp->ma_keys);
2714 i = mp->ma_keys->dk_nentries - 1;
2715 while (i >= 0 && ep0[i].me_value == NULL) {
2716 i--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 }
Victor Stinner742da042016-09-07 17:40:12 -07002718 assert(i >= 0);
2719
2720 ep = &ep0[i];
2721 j = lookdict_index(mp->ma_keys, ep->me_hash, i);
2722 assert(j >= 0);
2723 assert(dk_get_index(mp->ma_keys, j) == i);
2724 dk_set_index(mp->ma_keys, j, DKIX_DUMMY);
2725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 PyTuple_SET_ITEM(res, 0, ep->me_key);
2727 PyTuple_SET_ITEM(res, 1, ep->me_value);
Victor Stinner742da042016-09-07 17:40:12 -07002728 ep->me_key = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 ep->me_value = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002730 /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
2731 mp->ma_keys->dk_nentries = i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 mp->ma_used--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 return res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002734}
2735
Jeremy Hylton8caad492000-06-23 14:18:11 +00002736static int
2737dict_traverse(PyObject *op, visitproc visit, void *arg)
2738{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002739 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson55f44522016-09-05 12:12:59 -07002740 PyDictKeysObject *keys = mp->ma_keys;
Victor Stinner742da042016-09-07 17:40:12 -07002741 PyDictKeyEntry *entries = DK_ENTRIES(mp->ma_keys);
2742 Py_ssize_t i, n = keys->dk_nentries;
2743
Benjamin Peterson55f44522016-09-05 12:12:59 -07002744 if (keys->dk_lookup == lookdict) {
2745 for (i = 0; i < n; i++) {
2746 if (entries[i].me_value != NULL) {
2747 Py_VISIT(entries[i].me_value);
2748 Py_VISIT(entries[i].me_key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002749 }
2750 }
Victor Stinner742da042016-09-07 17:40:12 -07002751 }
2752 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002753 if (mp->ma_values != NULL) {
Benjamin Peterson55f44522016-09-05 12:12:59 -07002754 for (i = 0; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002755 Py_VISIT(mp->ma_values[i]);
2756 }
2757 }
2758 else {
Benjamin Peterson55f44522016-09-05 12:12:59 -07002759 for (i = 0; i < n; i++) {
2760 Py_VISIT(entries[i].me_value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002761 }
2762 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 }
2764 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002765}
2766
2767static int
2768dict_tp_clear(PyObject *op)
2769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 PyDict_Clear(op);
2771 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002772}
2773
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002774static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00002775
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002776Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06002777_PyDict_SizeOf(PyDictObject *mp)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002778{
Victor Stinner742da042016-09-07 17:40:12 -07002779 Py_ssize_t size, usable, res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002780
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002781 size = DK_SIZE(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002782 usable = USABLE_FRACTION(size);
2783
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002784 res = _PyObject_SIZE(Py_TYPE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002785 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07002786 res += usable * sizeof(PyObject*);
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002787 /* If the dictionary is split, the keys portion is accounted-for
2788 in the type object. */
2789 if (mp->ma_keys->dk_refcnt == 1)
Victor Stinner98ee9d52016-09-08 09:33:56 -07002790 res += (sizeof(PyDictKeysObject)
2791 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
2792 + DK_IXSIZE(mp->ma_keys) * size
2793 + sizeof(PyDictKeyEntry) * usable);
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002794 return res;
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002795}
2796
2797Py_ssize_t
2798_PyDict_KeysSize(PyDictKeysObject *keys)
2799{
Victor Stinner98ee9d52016-09-08 09:33:56 -07002800 return (sizeof(PyDictKeysObject)
2801 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
2802 + DK_IXSIZE(keys) * DK_SIZE(keys)
2803 + USABLE_FRACTION(DK_SIZE(keys)) * sizeof(PyDictKeyEntry));
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002804}
2805
doko@ubuntu.com17210f52016-01-14 14:04:59 +01002806static PyObject *
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002807dict_sizeof(PyDictObject *mp)
2808{
2809 return PyLong_FromSsize_t(_PyDict_SizeOf(mp));
2810}
2811
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002812PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
2813
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002814PyDoc_STRVAR(sizeof__doc__,
2815"D.__sizeof__() -> size of D in memory, in bytes");
2816
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002817PyDoc_STRVAR(get__doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00002818"D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002819
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002820PyDoc_STRVAR(setdefault_doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00002821"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 +00002822
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002823PyDoc_STRVAR(pop__doc__,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002824"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00002825If key is not found, d is returned if given, otherwise KeyError is raised");
Guido van Rossume027d982002-04-12 15:11:59 +00002826
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002827PyDoc_STRVAR(popitem__doc__,
Tim Petersf7f88b12000-12-13 23:18:45 +00002828"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000028292-tuple; but raise KeyError if D is empty.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002830
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002831PyDoc_STRVAR(update__doc__,
Brett Cannonf2754162013-05-11 14:46:48 -04002832"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n\
2833If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]\n\
2834If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n\
2835In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00002836
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002837PyDoc_STRVAR(clear__doc__,
2838"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002839
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002840PyDoc_STRVAR(copy__doc__,
2841"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00002842
Guido van Rossumb90c8482007-02-10 01:11:45 +00002843/* Forward */
2844static PyObject *dictkeys_new(PyObject *);
2845static PyObject *dictitems_new(PyObject *);
2846static PyObject *dictvalues_new(PyObject *);
2847
Guido van Rossum45c85d12007-07-27 16:31:40 +00002848PyDoc_STRVAR(keys__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 "D.keys() -> a set-like object providing a view on D's keys");
Guido van Rossum45c85d12007-07-27 16:31:40 +00002850PyDoc_STRVAR(items__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 "D.items() -> a set-like object providing a view on D's items");
Guido van Rossum45c85d12007-07-27 16:31:40 +00002852PyDoc_STRVAR(values__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 "D.values() -> an object providing a view on D's values");
Guido van Rossumb90c8482007-02-10 01:11:45 +00002854
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002855static PyMethodDef mapp_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -07002856 DICT___CONTAINS___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
2858 getitem__doc__},
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002859 {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 sizeof__doc__},
2861 {"get", (PyCFunction)dict_get, METH_VARARGS,
2862 get__doc__},
2863 {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS,
2864 setdefault_doc__},
2865 {"pop", (PyCFunction)dict_pop, METH_VARARGS,
2866 pop__doc__},
2867 {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
2868 popitem__doc__},
2869 {"keys", (PyCFunction)dictkeys_new, METH_NOARGS,
2870 keys__doc__},
2871 {"items", (PyCFunction)dictitems_new, METH_NOARGS,
2872 items__doc__},
2873 {"values", (PyCFunction)dictvalues_new, METH_NOARGS,
2874 values__doc__},
2875 {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
2876 update__doc__},
Larry Hastings5c661892014-01-24 06:17:25 -08002877 DICT_FROMKEYS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
2879 clear__doc__},
2880 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
2881 copy__doc__},
2882 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002883};
2884
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002885/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00002886int
2887PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002888{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002889 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002890 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002892 PyObject **value_addr;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002895 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 hash = PyObject_Hash(key);
2897 if (hash == -1)
2898 return -1;
2899 }
Victor Stinner742da042016-09-07 17:40:12 -07002900 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2901 if (ix == DKIX_ERROR)
2902 return -1;
2903 return (ix != DKIX_EMPTY && *value_addr != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002904}
2905
Thomas Wouterscf297e42007-02-23 15:07:44 +00002906/* Internal version of PyDict_Contains used when the hash value is already known */
2907int
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002908_PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00002909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002911 PyObject **value_addr;
Victor Stinner742da042016-09-07 17:40:12 -07002912 Py_ssize_t ix;
Thomas Wouterscf297e42007-02-23 15:07:44 +00002913
Victor Stinner742da042016-09-07 17:40:12 -07002914 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2915 if (ix == DKIX_ERROR)
2916 return -1;
2917 return (ix != DKIX_EMPTY && *value_addr != NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00002918}
2919
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002920/* Hack to implement "key in dict" */
2921static PySequenceMethods dict_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 0, /* sq_length */
2923 0, /* sq_concat */
2924 0, /* sq_repeat */
2925 0, /* sq_item */
2926 0, /* sq_slice */
2927 0, /* sq_ass_item */
2928 0, /* sq_ass_slice */
2929 PyDict_Contains, /* sq_contains */
2930 0, /* sq_inplace_concat */
2931 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002932};
2933
Guido van Rossum09e563a2001-05-01 12:10:21 +00002934static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002935dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 PyObject *self;
Victor Stinnera9f61a52013-07-16 22:17:26 +02002938 PyDictObject *d;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 assert(type != NULL && type->tp_alloc != NULL);
2941 self = type->tp_alloc(type, 0);
Victor Stinnera9f61a52013-07-16 22:17:26 +02002942 if (self == NULL)
2943 return NULL;
Victor Stinnera9f61a52013-07-16 22:17:26 +02002944 d = (PyDictObject *)self;
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02002945
Victor Stinnera9f61a52013-07-16 22:17:26 +02002946 /* The object has been implicitly tracked by tp_alloc */
2947 if (type == &PyDict_Type)
2948 _PyObject_GC_UNTRACK(d);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02002949
2950 d->ma_used = 0;
Victor Stinner742da042016-09-07 17:40:12 -07002951 d->ma_keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02002952 if (d->ma_keys == NULL) {
2953 Py_DECREF(self);
2954 return NULL;
2955 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 return self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002957}
2958
Tim Peters25786c02001-09-02 08:22:48 +00002959static int
2960dict_init(PyObject *self, PyObject *args, PyObject *kwds)
2961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00002963}
2964
Tim Peters6d6c1a32001-08-02 04:15:00 +00002965static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002966dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00002967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00002969}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002970
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002971PyDoc_STRVAR(dictionary_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00002972"dict() -> new empty dictionary\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00002973"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00002974" (key, value) pairs\n"
2975"dict(iterable) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00002976" d = {}\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00002977" for k, v in iterable:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00002978" d[k] = v\n"
2979"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
2980" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00002981
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002982PyTypeObject PyDict_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2984 "dict",
2985 sizeof(PyDictObject),
2986 0,
2987 (destructor)dict_dealloc, /* tp_dealloc */
2988 0, /* tp_print */
2989 0, /* tp_getattr */
2990 0, /* tp_setattr */
2991 0, /* tp_reserved */
2992 (reprfunc)dict_repr, /* tp_repr */
2993 0, /* tp_as_number */
2994 &dict_as_sequence, /* tp_as_sequence */
2995 &dict_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00002996 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 0, /* tp_call */
2998 0, /* tp_str */
2999 PyObject_GenericGetAttr, /* tp_getattro */
3000 0, /* tp_setattro */
3001 0, /* tp_as_buffer */
3002 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3003 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
3004 dictionary_doc, /* tp_doc */
3005 dict_traverse, /* tp_traverse */
3006 dict_tp_clear, /* tp_clear */
3007 dict_richcompare, /* tp_richcompare */
3008 0, /* tp_weaklistoffset */
3009 (getiterfunc)dict_iter, /* tp_iter */
3010 0, /* tp_iternext */
3011 mapp_methods, /* tp_methods */
3012 0, /* tp_members */
3013 0, /* tp_getset */
3014 0, /* tp_base */
3015 0, /* tp_dict */
3016 0, /* tp_descr_get */
3017 0, /* tp_descr_set */
3018 0, /* tp_dictoffset */
3019 dict_init, /* tp_init */
3020 PyType_GenericAlloc, /* tp_alloc */
3021 dict_new, /* tp_new */
3022 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003023};
3024
Victor Stinner3c1e4812012-03-26 22:10:51 +02003025PyObject *
3026_PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
3027{
3028 PyObject *kv;
3029 kv = _PyUnicode_FromId(key); /* borrowed */
Victor Stinner5b3b1002013-07-22 23:50:57 +02003030 if (kv == NULL) {
3031 PyErr_Clear();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003032 return NULL;
Victor Stinner5b3b1002013-07-22 23:50:57 +02003033 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003034 return PyDict_GetItem(dp, kv);
3035}
3036
Guido van Rossum3cca2451997-05-16 14:23:33 +00003037/* For backward compatibility with old dictionary interface */
3038
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003039PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003040PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 PyObject *kv, *rv;
3043 kv = PyUnicode_FromString(key);
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003044 if (kv == NULL) {
3045 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 return NULL;
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003047 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 rv = PyDict_GetItem(v, kv);
3049 Py_DECREF(kv);
3050 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003051}
3052
3053int
Victor Stinner3c1e4812012-03-26 22:10:51 +02003054_PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
3055{
3056 PyObject *kv;
3057 kv = _PyUnicode_FromId(key); /* borrowed */
3058 if (kv == NULL)
3059 return -1;
3060 return PyDict_SetItem(v, kv, item);
3061}
3062
3063int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003064PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 PyObject *kv;
3067 int err;
3068 kv = PyUnicode_FromString(key);
3069 if (kv == NULL)
3070 return -1;
3071 PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
3072 err = PyDict_SetItem(v, kv, item);
3073 Py_DECREF(kv);
3074 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003075}
3076
3077int
Victor Stinner5fd2e5a2013-11-06 18:58:22 +01003078_PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
3079{
3080 PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
3081 if (kv == NULL)
3082 return -1;
3083 return PyDict_DelItem(v, kv);
3084}
3085
3086int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003087PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 PyObject *kv;
3090 int err;
3091 kv = PyUnicode_FromString(key);
3092 if (kv == NULL)
3093 return -1;
3094 err = PyDict_DelItem(v, kv);
3095 Py_DECREF(kv);
3096 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003097}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003098
Raymond Hettinger019a1482004-03-18 02:41:19 +00003099/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003100
3101typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 PyObject_HEAD
3103 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
3104 Py_ssize_t di_used;
3105 Py_ssize_t di_pos;
3106 PyObject* di_result; /* reusable result tuple for iteritems */
3107 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003108} dictiterobject;
3109
3110static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003111dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 dictiterobject *di;
3114 di = PyObject_GC_New(dictiterobject, itertype);
3115 if (di == NULL)
3116 return NULL;
3117 Py_INCREF(dict);
3118 di->di_dict = dict;
3119 di->di_used = dict->ma_used;
3120 di->di_pos = 0;
3121 di->len = dict->ma_used;
3122 if (itertype == &PyDictIterItem_Type) {
3123 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
3124 if (di->di_result == NULL) {
3125 Py_DECREF(di);
3126 return NULL;
3127 }
3128 }
3129 else
3130 di->di_result = NULL;
3131 _PyObject_GC_TRACK(di);
3132 return (PyObject *)di;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003133}
3134
3135static void
3136dictiter_dealloc(dictiterobject *di)
3137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 Py_XDECREF(di->di_dict);
3139 Py_XDECREF(di->di_result);
3140 PyObject_GC_Del(di);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003141}
3142
3143static int
3144dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
3145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 Py_VISIT(di->di_dict);
3147 Py_VISIT(di->di_result);
3148 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003149}
3150
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003151static PyObject *
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003152dictiter_len(dictiterobject *di)
3153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 Py_ssize_t len = 0;
3155 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
3156 len = di->len;
3157 return PyLong_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003158}
3159
Guido van Rossumb90c8482007-02-10 01:11:45 +00003160PyDoc_STRVAR(length_hint_doc,
3161 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003162
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003163static PyObject *
3164dictiter_reduce(dictiterobject *di);
3165
3166PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3167
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003168static PyMethodDef dictiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS,
3170 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003171 {"__reduce__", (PyCFunction)dictiter_reduce, METH_NOARGS,
3172 reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003174};
3175
Raymond Hettinger019a1482004-03-18 02:41:19 +00003176static PyObject *dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00003177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 PyObject *key;
Victor Stinner742da042016-09-07 17:40:12 -07003179 Py_ssize_t i, n, offset;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003180 PyDictKeysObject *k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003182 PyObject **value_ptr;
Guido van Rossum213c7a62001-04-23 14:08:49 +00003183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 if (d == NULL)
3185 return NULL;
3186 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00003187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 if (di->di_used != d->ma_used) {
3189 PyErr_SetString(PyExc_RuntimeError,
3190 "dictionary changed size during iteration");
3191 di->di_used = -1; /* Make this state sticky */
3192 return NULL;
3193 }
Guido van Rossum2147df72002-07-16 20:30:22 +00003194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 i = di->di_pos;
3196 if (i < 0)
3197 goto fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003198 k = d->ma_keys;
3199 if (d->ma_values) {
3200 value_ptr = &d->ma_values[i];
3201 offset = sizeof(PyObject *);
3202 }
3203 else {
Victor Stinner742da042016-09-07 17:40:12 -07003204 value_ptr = &DK_ENTRIES(k)[i].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003205 offset = sizeof(PyDictKeyEntry);
3206 }
Victor Stinner742da042016-09-07 17:40:12 -07003207 n = k->dk_nentries - 1;
3208 while (i <= n && *value_ptr == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003209 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 i++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003211 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 di->di_pos = i+1;
Victor Stinner742da042016-09-07 17:40:12 -07003213 if (i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 goto fail;
3215 di->len--;
Victor Stinner742da042016-09-07 17:40:12 -07003216 key = DK_ENTRIES(k)[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 Py_INCREF(key);
3218 return key;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003219
3220fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003222 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003224}
3225
Raymond Hettinger019a1482004-03-18 02:41:19 +00003226PyTypeObject PyDictIterKey_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3228 "dict_keyiterator", /* tp_name */
3229 sizeof(dictiterobject), /* tp_basicsize */
3230 0, /* tp_itemsize */
3231 /* methods */
3232 (destructor)dictiter_dealloc, /* tp_dealloc */
3233 0, /* tp_print */
3234 0, /* tp_getattr */
3235 0, /* tp_setattr */
3236 0, /* tp_reserved */
3237 0, /* tp_repr */
3238 0, /* tp_as_number */
3239 0, /* tp_as_sequence */
3240 0, /* tp_as_mapping */
3241 0, /* tp_hash */
3242 0, /* tp_call */
3243 0, /* tp_str */
3244 PyObject_GenericGetAttr, /* tp_getattro */
3245 0, /* tp_setattro */
3246 0, /* tp_as_buffer */
3247 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3248 0, /* tp_doc */
3249 (traverseproc)dictiter_traverse, /* tp_traverse */
3250 0, /* tp_clear */
3251 0, /* tp_richcompare */
3252 0, /* tp_weaklistoffset */
3253 PyObject_SelfIter, /* tp_iter */
3254 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
3255 dictiter_methods, /* tp_methods */
3256 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003257};
3258
3259static PyObject *dictiter_iternextvalue(dictiterobject *di)
3260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -07003262 Py_ssize_t i, n, offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003264 PyObject **value_ptr;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 if (d == NULL)
3267 return NULL;
3268 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 if (di->di_used != d->ma_used) {
3271 PyErr_SetString(PyExc_RuntimeError,
3272 "dictionary changed size during iteration");
3273 di->di_used = -1; /* Make this state sticky */
3274 return NULL;
3275 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 i = di->di_pos;
Victor Stinner742da042016-09-07 17:40:12 -07003278 n = d->ma_keys->dk_nentries - 1;
3279 if (i < 0 || i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 goto fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003281 if (d->ma_values) {
3282 value_ptr = &d->ma_values[i];
3283 offset = sizeof(PyObject *);
3284 }
3285 else {
Victor Stinner742da042016-09-07 17:40:12 -07003286 value_ptr = &DK_ENTRIES(d->ma_keys)[i].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003287 offset = sizeof(PyDictKeyEntry);
3288 }
Victor Stinner742da042016-09-07 17:40:12 -07003289 while (i <= n && *value_ptr == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003290 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 i++;
Victor Stinner742da042016-09-07 17:40:12 -07003292 if (i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003293 goto fail;
3294 }
3295 di->di_pos = i+1;
3296 di->len--;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003297 value = *value_ptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 Py_INCREF(value);
3299 return value;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003300
3301fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003303 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003305}
3306
3307PyTypeObject PyDictIterValue_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3309 "dict_valueiterator", /* tp_name */
3310 sizeof(dictiterobject), /* tp_basicsize */
3311 0, /* tp_itemsize */
3312 /* methods */
3313 (destructor)dictiter_dealloc, /* tp_dealloc */
3314 0, /* tp_print */
3315 0, /* tp_getattr */
3316 0, /* tp_setattr */
3317 0, /* tp_reserved */
3318 0, /* tp_repr */
3319 0, /* tp_as_number */
3320 0, /* tp_as_sequence */
3321 0, /* tp_as_mapping */
3322 0, /* tp_hash */
3323 0, /* tp_call */
3324 0, /* tp_str */
3325 PyObject_GenericGetAttr, /* tp_getattro */
3326 0, /* tp_setattro */
3327 0, /* tp_as_buffer */
3328 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3329 0, /* tp_doc */
3330 (traverseproc)dictiter_traverse, /* tp_traverse */
3331 0, /* tp_clear */
3332 0, /* tp_richcompare */
3333 0, /* tp_weaklistoffset */
3334 PyObject_SelfIter, /* tp_iter */
3335 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
3336 dictiter_methods, /* tp_methods */
3337 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003338};
3339
3340static PyObject *dictiter_iternextitem(dictiterobject *di)
3341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 PyObject *key, *value, *result = di->di_result;
Victor Stinner742da042016-09-07 17:40:12 -07003343 Py_ssize_t i, n, offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003345 PyObject **value_ptr;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 if (d == NULL)
3348 return NULL;
3349 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 if (di->di_used != d->ma_used) {
3352 PyErr_SetString(PyExc_RuntimeError,
3353 "dictionary changed size during iteration");
3354 di->di_used = -1; /* Make this state sticky */
3355 return NULL;
3356 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 i = di->di_pos;
3359 if (i < 0)
3360 goto fail;
Victor Stinner742da042016-09-07 17:40:12 -07003361 n = d->ma_keys->dk_nentries - 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003362 if (d->ma_values) {
3363 value_ptr = &d->ma_values[i];
3364 offset = sizeof(PyObject *);
3365 }
3366 else {
Victor Stinner742da042016-09-07 17:40:12 -07003367 value_ptr = &DK_ENTRIES(d->ma_keys)[i].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003368 offset = sizeof(PyDictKeyEntry);
3369 }
Victor Stinner742da042016-09-07 17:40:12 -07003370 while (i <= n && *value_ptr == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003371 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 i++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003373 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 di->di_pos = i+1;
Victor Stinner742da042016-09-07 17:40:12 -07003375 if (i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 goto fail;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 if (result->ob_refcnt == 1) {
3379 Py_INCREF(result);
3380 Py_DECREF(PyTuple_GET_ITEM(result, 0));
3381 Py_DECREF(PyTuple_GET_ITEM(result, 1));
3382 } else {
3383 result = PyTuple_New(2);
3384 if (result == NULL)
3385 return NULL;
3386 }
3387 di->len--;
Victor Stinner742da042016-09-07 17:40:12 -07003388 key = DK_ENTRIES(d->ma_keys)[i].me_key;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003389 value = *value_ptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 Py_INCREF(key);
3391 Py_INCREF(value);
Eric Snow96c6af92015-05-29 22:21:39 -06003392 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3393 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003395
3396fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003398 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003400}
3401
3402PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3404 "dict_itemiterator", /* tp_name */
3405 sizeof(dictiterobject), /* tp_basicsize */
3406 0, /* tp_itemsize */
3407 /* methods */
3408 (destructor)dictiter_dealloc, /* tp_dealloc */
3409 0, /* tp_print */
3410 0, /* tp_getattr */
3411 0, /* tp_setattr */
3412 0, /* tp_reserved */
3413 0, /* tp_repr */
3414 0, /* tp_as_number */
3415 0, /* tp_as_sequence */
3416 0, /* tp_as_mapping */
3417 0, /* tp_hash */
3418 0, /* tp_call */
3419 0, /* tp_str */
3420 PyObject_GenericGetAttr, /* tp_getattro */
3421 0, /* tp_setattro */
3422 0, /* tp_as_buffer */
3423 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3424 0, /* tp_doc */
3425 (traverseproc)dictiter_traverse, /* tp_traverse */
3426 0, /* tp_clear */
3427 0, /* tp_richcompare */
3428 0, /* tp_weaklistoffset */
3429 PyObject_SelfIter, /* tp_iter */
3430 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
3431 dictiter_methods, /* tp_methods */
3432 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003433};
Guido van Rossumb90c8482007-02-10 01:11:45 +00003434
3435
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003436static PyObject *
3437dictiter_reduce(dictiterobject *di)
3438{
3439 PyObject *list;
3440 dictiterobject tmp;
3441
3442 list = PyList_New(0);
3443 if (!list)
3444 return NULL;
3445
3446 /* copy the itertor state */
3447 tmp = *di;
3448 Py_XINCREF(tmp.di_dict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003449
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003450 /* iterate the temporary into a list */
3451 for(;;) {
3452 PyObject *element = 0;
3453 if (Py_TYPE(di) == &PyDictIterItem_Type)
3454 element = dictiter_iternextitem(&tmp);
3455 else if (Py_TYPE(di) == &PyDictIterKey_Type)
3456 element = dictiter_iternextkey(&tmp);
3457 else if (Py_TYPE(di) == &PyDictIterValue_Type)
3458 element = dictiter_iternextvalue(&tmp);
3459 else
3460 assert(0);
3461 if (element) {
3462 if (PyList_Append(list, element)) {
3463 Py_DECREF(element);
3464 Py_DECREF(list);
3465 Py_XDECREF(tmp.di_dict);
3466 return NULL;
3467 }
3468 Py_DECREF(element);
3469 } else
3470 break;
3471 }
3472 Py_XDECREF(tmp.di_dict);
3473 /* check for error */
3474 if (tmp.di_dict != NULL) {
3475 /* we have an error */
3476 Py_DECREF(list);
3477 return NULL;
3478 }
Antoine Pitroua7013882012-04-05 00:04:20 +02003479 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003480}
3481
Guido van Rossum3ac67412007-02-10 18:55:06 +00003482/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003483/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00003484/***********************************************/
3485
Guido van Rossumb90c8482007-02-10 01:11:45 +00003486/* The instance lay-out is the same for all three; but the type differs. */
3487
Guido van Rossumb90c8482007-02-10 01:11:45 +00003488static void
Eric Snow96c6af92015-05-29 22:21:39 -06003489dictview_dealloc(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 Py_XDECREF(dv->dv_dict);
3492 PyObject_GC_Del(dv);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003493}
3494
3495static int
Eric Snow96c6af92015-05-29 22:21:39 -06003496dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 Py_VISIT(dv->dv_dict);
3499 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003500}
3501
Guido van Rossum83825ac2007-02-10 04:54:19 +00003502static Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003503dictview_len(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 Py_ssize_t len = 0;
3506 if (dv->dv_dict != NULL)
3507 len = dv->dv_dict->ma_used;
3508 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003509}
3510
Eric Snow96c6af92015-05-29 22:21:39 -06003511PyObject *
3512_PyDictView_New(PyObject *dict, PyTypeObject *type)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003513{
Eric Snow96c6af92015-05-29 22:21:39 -06003514 _PyDictViewObject *dv;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 if (dict == NULL) {
3516 PyErr_BadInternalCall();
3517 return NULL;
3518 }
3519 if (!PyDict_Check(dict)) {
3520 /* XXX Get rid of this restriction later */
3521 PyErr_Format(PyExc_TypeError,
3522 "%s() requires a dict argument, not '%s'",
3523 type->tp_name, dict->ob_type->tp_name);
3524 return NULL;
3525 }
Eric Snow96c6af92015-05-29 22:21:39 -06003526 dv = PyObject_GC_New(_PyDictViewObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 if (dv == NULL)
3528 return NULL;
3529 Py_INCREF(dict);
3530 dv->dv_dict = (PyDictObject *)dict;
3531 _PyObject_GC_TRACK(dv);
3532 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003533}
3534
Neal Norwitze36f2ba2007-02-26 23:12:28 +00003535/* TODO(guido): The views objects are not complete:
3536
3537 * support more set operations
3538 * support arbitrary mappings?
3539 - either these should be static or exported in dictobject.h
3540 - if public then they should probably be in builtins
3541*/
3542
Guido van Rossumaac530c2007-08-24 22:33:45 +00003543/* Return 1 if self is a subset of other, iterating over self;
3544 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00003545static int
3546all_contained_in(PyObject *self, PyObject *other)
3547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 PyObject *iter = PyObject_GetIter(self);
3549 int ok = 1;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 if (iter == NULL)
3552 return -1;
3553 for (;;) {
3554 PyObject *next = PyIter_Next(iter);
3555 if (next == NULL) {
3556 if (PyErr_Occurred())
3557 ok = -1;
3558 break;
3559 }
3560 ok = PySequence_Contains(other, next);
3561 Py_DECREF(next);
3562 if (ok <= 0)
3563 break;
3564 }
3565 Py_DECREF(iter);
3566 return ok;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003567}
3568
3569static PyObject *
3570dictview_richcompare(PyObject *self, PyObject *other, int op)
3571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 Py_ssize_t len_self, len_other;
3573 int ok;
3574 PyObject *result;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 assert(self != NULL);
3577 assert(PyDictViewSet_Check(self));
3578 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00003579
Brian Curtindfc80e32011-08-10 20:28:54 -05003580 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
3581 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 len_self = PyObject_Size(self);
3584 if (len_self < 0)
3585 return NULL;
3586 len_other = PyObject_Size(other);
3587 if (len_other < 0)
3588 return NULL;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003590 ok = 0;
3591 switch(op) {
Guido van Rossumaac530c2007-08-24 22:33:45 +00003592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 case Py_NE:
3594 case Py_EQ:
3595 if (len_self == len_other)
3596 ok = all_contained_in(self, other);
3597 if (op == Py_NE && ok >= 0)
3598 ok = !ok;
3599 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 case Py_LT:
3602 if (len_self < len_other)
3603 ok = all_contained_in(self, other);
3604 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 case Py_LE:
3607 if (len_self <= len_other)
3608 ok = all_contained_in(self, other);
3609 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 case Py_GT:
3612 if (len_self > len_other)
3613 ok = all_contained_in(other, self);
3614 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 case Py_GE:
3617 if (len_self >= len_other)
3618 ok = all_contained_in(other, self);
3619 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 }
3622 if (ok < 0)
3623 return NULL;
3624 result = ok ? Py_True : Py_False;
3625 Py_INCREF(result);
3626 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003627}
3628
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003629static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003630dictview_repr(_PyDictViewObject *dv)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 PyObject *seq;
3633 PyObject *result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 seq = PySequence_List((PyObject *)dv);
3636 if (seq == NULL)
3637 return NULL;
3638
3639 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
3640 Py_DECREF(seq);
3641 return result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003642}
3643
Guido van Rossum3ac67412007-02-10 18:55:06 +00003644/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003645
3646static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003647dictkeys_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 if (dv->dv_dict == NULL) {
3650 Py_RETURN_NONE;
3651 }
3652 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003653}
3654
3655static int
Eric Snow96c6af92015-05-29 22:21:39 -06003656dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00003657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 if (dv->dv_dict == NULL)
3659 return 0;
3660 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003661}
3662
Guido van Rossum83825ac2007-02-10 04:54:19 +00003663static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 (lenfunc)dictview_len, /* sq_length */
3665 0, /* sq_concat */
3666 0, /* sq_repeat */
3667 0, /* sq_item */
3668 0, /* sq_slice */
3669 0, /* sq_ass_item */
3670 0, /* sq_ass_slice */
3671 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003672};
3673
Guido van Rossum523259b2007-08-24 23:41:22 +00003674static PyObject*
3675dictviews_sub(PyObject* self, PyObject *other)
3676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003677 PyObject *result = PySet_New(self);
3678 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003679 _Py_IDENTIFIER(difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 if (result == NULL)
3682 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003683
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003684 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685 if (tmp == NULL) {
3686 Py_DECREF(result);
3687 return NULL;
3688 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 Py_DECREF(tmp);
3691 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003692}
3693
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003694PyObject*
3695_PyDictView_Intersect(PyObject* self, PyObject *other)
Guido van Rossum523259b2007-08-24 23:41:22 +00003696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 PyObject *result = PySet_New(self);
3698 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003699 _Py_IDENTIFIER(intersection_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003701 if (result == NULL)
3702 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003703
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003704 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_intersection_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 if (tmp == NULL) {
3706 Py_DECREF(result);
3707 return NULL;
3708 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003710 Py_DECREF(tmp);
3711 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003712}
3713
3714static PyObject*
3715dictviews_or(PyObject* self, PyObject *other)
3716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003717 PyObject *result = PySet_New(self);
3718 PyObject *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02003719 _Py_IDENTIFIER(update);
Victor Stinnerd1a9cc22011-10-13 22:51:17 +02003720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003721 if (result == NULL)
3722 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003723
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003724 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 if (tmp == NULL) {
3726 Py_DECREF(result);
3727 return NULL;
3728 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 Py_DECREF(tmp);
3731 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003732}
3733
3734static PyObject*
3735dictviews_xor(PyObject* self, PyObject *other)
3736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003737 PyObject *result = PySet_New(self);
3738 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003739 _Py_IDENTIFIER(symmetric_difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003741 if (result == NULL)
3742 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003743
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003744 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_symmetric_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 if (tmp == NULL) {
3746 Py_DECREF(result);
3747 return NULL;
3748 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 Py_DECREF(tmp);
3751 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003752}
3753
3754static PyNumberMethods dictviews_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 0, /*nb_add*/
3756 (binaryfunc)dictviews_sub, /*nb_subtract*/
3757 0, /*nb_multiply*/
3758 0, /*nb_remainder*/
3759 0, /*nb_divmod*/
3760 0, /*nb_power*/
3761 0, /*nb_negative*/
3762 0, /*nb_positive*/
3763 0, /*nb_absolute*/
3764 0, /*nb_bool*/
3765 0, /*nb_invert*/
3766 0, /*nb_lshift*/
3767 0, /*nb_rshift*/
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003768 (binaryfunc)_PyDictView_Intersect, /*nb_and*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 (binaryfunc)dictviews_xor, /*nb_xor*/
3770 (binaryfunc)dictviews_or, /*nb_or*/
Guido van Rossum523259b2007-08-24 23:41:22 +00003771};
3772
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003773static PyObject*
3774dictviews_isdisjoint(PyObject *self, PyObject *other)
3775{
3776 PyObject *it;
3777 PyObject *item = NULL;
3778
3779 if (self == other) {
Eric Snow96c6af92015-05-29 22:21:39 -06003780 if (dictview_len((_PyDictViewObject *)self) == 0)
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003781 Py_RETURN_TRUE;
3782 else
3783 Py_RETURN_FALSE;
3784 }
3785
3786 /* Iterate over the shorter object (only if other is a set,
3787 * because PySequence_Contains may be expensive otherwise): */
3788 if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
Eric Snow96c6af92015-05-29 22:21:39 -06003789 Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003790 Py_ssize_t len_other = PyObject_Size(other);
3791 if (len_other == -1)
3792 return NULL;
3793
3794 if ((len_other > len_self)) {
3795 PyObject *tmp = other;
3796 other = self;
3797 self = tmp;
3798 }
3799 }
3800
3801 it = PyObject_GetIter(other);
3802 if (it == NULL)
3803 return NULL;
3804
3805 while ((item = PyIter_Next(it)) != NULL) {
3806 int contains = PySequence_Contains(self, item);
3807 Py_DECREF(item);
3808 if (contains == -1) {
3809 Py_DECREF(it);
3810 return NULL;
3811 }
3812
3813 if (contains) {
3814 Py_DECREF(it);
3815 Py_RETURN_FALSE;
3816 }
3817 }
3818 Py_DECREF(it);
3819 if (PyErr_Occurred())
3820 return NULL; /* PyIter_Next raised an exception. */
3821 Py_RETURN_TRUE;
3822}
3823
3824PyDoc_STRVAR(isdisjoint_doc,
3825"Return True if the view and the given iterable have a null intersection.");
3826
Guido van Rossumb90c8482007-02-10 01:11:45 +00003827static PyMethodDef dictkeys_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003828 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
3829 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003830 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00003831};
3832
3833PyTypeObject PyDictKeys_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003834 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3835 "dict_keys", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06003836 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003837 0, /* tp_itemsize */
3838 /* methods */
3839 (destructor)dictview_dealloc, /* tp_dealloc */
3840 0, /* tp_print */
3841 0, /* tp_getattr */
3842 0, /* tp_setattr */
3843 0, /* tp_reserved */
3844 (reprfunc)dictview_repr, /* tp_repr */
3845 &dictviews_as_number, /* tp_as_number */
3846 &dictkeys_as_sequence, /* tp_as_sequence */
3847 0, /* tp_as_mapping */
3848 0, /* tp_hash */
3849 0, /* tp_call */
3850 0, /* tp_str */
3851 PyObject_GenericGetAttr, /* tp_getattro */
3852 0, /* tp_setattro */
3853 0, /* tp_as_buffer */
3854 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3855 0, /* tp_doc */
3856 (traverseproc)dictview_traverse, /* tp_traverse */
3857 0, /* tp_clear */
3858 dictview_richcompare, /* tp_richcompare */
3859 0, /* tp_weaklistoffset */
3860 (getiterfunc)dictkeys_iter, /* tp_iter */
3861 0, /* tp_iternext */
3862 dictkeys_methods, /* tp_methods */
3863 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00003864};
3865
3866static PyObject *
3867dictkeys_new(PyObject *dict)
3868{
Eric Snow96c6af92015-05-29 22:21:39 -06003869 return _PyDictView_New(dict, &PyDictKeys_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003870}
3871
Guido van Rossum3ac67412007-02-10 18:55:06 +00003872/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003873
3874static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003875dictitems_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 if (dv->dv_dict == NULL) {
3878 Py_RETURN_NONE;
3879 }
3880 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003881}
3882
3883static int
Eric Snow96c6af92015-05-29 22:21:39 -06003884dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00003885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 PyObject *key, *value, *found;
3887 if (dv->dv_dict == NULL)
3888 return 0;
3889 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
3890 return 0;
3891 key = PyTuple_GET_ITEM(obj, 0);
3892 value = PyTuple_GET_ITEM(obj, 1);
3893 found = PyDict_GetItem((PyObject *)dv->dv_dict, key);
3894 if (found == NULL) {
3895 if (PyErr_Occurred())
3896 return -1;
3897 return 0;
3898 }
3899 return PyObject_RichCompareBool(value, found, Py_EQ);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003900}
3901
Guido van Rossum83825ac2007-02-10 04:54:19 +00003902static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 (lenfunc)dictview_len, /* sq_length */
3904 0, /* sq_concat */
3905 0, /* sq_repeat */
3906 0, /* sq_item */
3907 0, /* sq_slice */
3908 0, /* sq_ass_item */
3909 0, /* sq_ass_slice */
3910 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003911};
3912
Guido van Rossumb90c8482007-02-10 01:11:45 +00003913static PyMethodDef dictitems_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003914 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
3915 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003916 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00003917};
3918
3919PyTypeObject PyDictItems_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3921 "dict_items", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06003922 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 0, /* tp_itemsize */
3924 /* methods */
3925 (destructor)dictview_dealloc, /* tp_dealloc */
3926 0, /* tp_print */
3927 0, /* tp_getattr */
3928 0, /* tp_setattr */
3929 0, /* tp_reserved */
3930 (reprfunc)dictview_repr, /* tp_repr */
3931 &dictviews_as_number, /* tp_as_number */
3932 &dictitems_as_sequence, /* tp_as_sequence */
3933 0, /* tp_as_mapping */
3934 0, /* tp_hash */
3935 0, /* tp_call */
3936 0, /* tp_str */
3937 PyObject_GenericGetAttr, /* tp_getattro */
3938 0, /* tp_setattro */
3939 0, /* tp_as_buffer */
3940 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3941 0, /* tp_doc */
3942 (traverseproc)dictview_traverse, /* tp_traverse */
3943 0, /* tp_clear */
3944 dictview_richcompare, /* tp_richcompare */
3945 0, /* tp_weaklistoffset */
3946 (getiterfunc)dictitems_iter, /* tp_iter */
3947 0, /* tp_iternext */
3948 dictitems_methods, /* tp_methods */
3949 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00003950};
3951
3952static PyObject *
3953dictitems_new(PyObject *dict)
3954{
Eric Snow96c6af92015-05-29 22:21:39 -06003955 return _PyDictView_New(dict, &PyDictItems_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003956}
3957
Guido van Rossum3ac67412007-02-10 18:55:06 +00003958/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003959
3960static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003961dictvalues_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 if (dv->dv_dict == NULL) {
3964 Py_RETURN_NONE;
3965 }
3966 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003967}
3968
Guido van Rossum83825ac2007-02-10 04:54:19 +00003969static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 (lenfunc)dictview_len, /* sq_length */
3971 0, /* sq_concat */
3972 0, /* sq_repeat */
3973 0, /* sq_item */
3974 0, /* sq_slice */
3975 0, /* sq_ass_item */
3976 0, /* sq_ass_slice */
3977 (objobjproc)0, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003978};
3979
Guido van Rossumb90c8482007-02-10 01:11:45 +00003980static PyMethodDef dictvalues_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00003982};
3983
3984PyTypeObject PyDictValues_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003985 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3986 "dict_values", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06003987 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003988 0, /* tp_itemsize */
3989 /* methods */
3990 (destructor)dictview_dealloc, /* tp_dealloc */
3991 0, /* tp_print */
3992 0, /* tp_getattr */
3993 0, /* tp_setattr */
3994 0, /* tp_reserved */
3995 (reprfunc)dictview_repr, /* tp_repr */
3996 0, /* tp_as_number */
3997 &dictvalues_as_sequence, /* tp_as_sequence */
3998 0, /* tp_as_mapping */
3999 0, /* tp_hash */
4000 0, /* tp_call */
4001 0, /* tp_str */
4002 PyObject_GenericGetAttr, /* tp_getattro */
4003 0, /* tp_setattro */
4004 0, /* tp_as_buffer */
4005 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4006 0, /* tp_doc */
4007 (traverseproc)dictview_traverse, /* tp_traverse */
4008 0, /* tp_clear */
4009 0, /* tp_richcompare */
4010 0, /* tp_weaklistoffset */
4011 (getiterfunc)dictvalues_iter, /* tp_iter */
4012 0, /* tp_iternext */
4013 dictvalues_methods, /* tp_methods */
4014 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004015};
4016
4017static PyObject *
4018dictvalues_new(PyObject *dict)
4019{
Eric Snow96c6af92015-05-29 22:21:39 -06004020 return _PyDictView_New(dict, &PyDictValues_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004021}
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004022
4023/* Returns NULL if cannot allocate a new PyDictKeysObject,
4024 but does not set an error */
4025PyDictKeysObject *
4026_PyDict_NewKeysForClass(void)
4027{
Victor Stinner742da042016-09-07 17:40:12 -07004028 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004029 if (keys == NULL)
4030 PyErr_Clear();
4031 else
4032 keys->dk_lookup = lookdict_split;
4033 return keys;
4034}
4035
4036#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
4037
4038PyObject *
4039PyObject_GenericGetDict(PyObject *obj, void *context)
4040{
4041 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
4042 if (dictptr == NULL) {
4043 PyErr_SetString(PyExc_AttributeError,
4044 "This object has no __dict__");
4045 return NULL;
4046 }
4047 dict = *dictptr;
4048 if (dict == NULL) {
4049 PyTypeObject *tp = Py_TYPE(obj);
4050 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
4051 DK_INCREF(CACHED_KEYS(tp));
4052 *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
4053 }
4054 else {
4055 *dictptr = dict = PyDict_New();
4056 }
4057 }
4058 Py_XINCREF(dict);
4059 return dict;
4060}
4061
4062int
4063_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
Victor Stinner742da042016-09-07 17:40:12 -07004064 PyObject *key, PyObject *value)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004065{
4066 PyObject *dict;
4067 int res;
4068 PyDictKeysObject *cached;
4069
4070 assert(dictptr != NULL);
4071 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
4072 assert(dictptr != NULL);
4073 dict = *dictptr;
4074 if (dict == NULL) {
4075 DK_INCREF(cached);
4076 dict = new_dict_with_shared_keys(cached);
4077 if (dict == NULL)
4078 return -1;
4079 *dictptr = dict;
4080 }
4081 if (value == NULL) {
4082 res = PyDict_DelItem(dict, key);
4083 if (cached != ((PyDictObject *)dict)->ma_keys) {
4084 CACHED_KEYS(tp) = NULL;
4085 DK_DECREF(cached);
4086 }
4087 } else {
4088 res = PyDict_SetItem(dict, key, value);
4089 if (cached != ((PyDictObject *)dict)->ma_keys) {
4090 /* Either update tp->ht_cached_keys or delete it */
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004091 if (cached->dk_refcnt == 1) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004092 CACHED_KEYS(tp) = make_keys_shared(dict);
Victor Stinner742da042016-09-07 17:40:12 -07004093 }
4094 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004095 CACHED_KEYS(tp) = NULL;
4096 }
4097 DK_DECREF(cached);
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004098 if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
4099 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004100 }
4101 }
4102 } else {
4103 dict = *dictptr;
4104 if (dict == NULL) {
4105 dict = PyDict_New();
4106 if (dict == NULL)
4107 return -1;
4108 *dictptr = dict;
4109 }
4110 if (value == NULL) {
4111 res = PyDict_DelItem(dict, key);
4112 } else {
4113 res = PyDict_SetItem(dict, key, value);
4114 }
4115 }
4116 return res;
4117}
4118
4119void
4120_PyDictKeys_DecRef(PyDictKeysObject *keys)
4121{
4122 DK_DECREF(keys);
4123}