blob: 3d5d4bd2a723eb4ec08c8d4d695f79c15a8f836a [file] [log] [blame]
Guido van Rossum2bc13791999-03-24 19:06:42 +00001/* Dictionary object implementation using a hash table */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002
Raymond Hettinger930427b2003-05-03 06:51:59 +00003/* The distribution includes a separate file, Objects/dictnotes.txt,
Tim Peters60b29962006-01-01 01:19:23 +00004 describing explorations into dictionary design and optimization.
Raymond Hettinger930427b2003-05-03 06:51:59 +00005 It covers typical dictionary use patterns, the parameters for
6 tuning dictionaries, and several ideas for possible optimizations.
7*/
8
Victor Stinner742da042016-09-07 17:40:12 -07009/* PyDictKeysObject
10
11This implements the dictionary's hashtable.
12
13As of Python 3.6, this is compact and orderd. Basic idea is described here.
Benjamin Peterson003f0592016-09-08 10:14:31 -070014https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html
Victor Stinner742da042016-09-07 17:40:12 -070015
16layout:
17
18+---------------+
19| dk_refcnt |
20| dk_size |
21| dk_lookup |
22| dk_usable |
23| dk_nentries |
24+---------------+
25| dk_indices |
26| |
27+---------------+
28| dk_entries |
29| |
30+---------------+
31
32dk_indices is actual hashtable. It holds index in entries, or DKIX_EMPTY(-1)
33or DKIX_DUMMY(-2).
34Size of indices is dk_size. Type of each index in indices is vary on dk_size:
35
36* int8 for dk_size <= 128
37* int16 for 256 <= dk_size <= 2**15
38* int32 for 2**16 <= dk_size <= 2**31
39* int64 for 2**32 <= dk_size
40
41dk_entries is array of PyDictKeyEntry. It's size is USABLE_FRACTION(dk_size).
42DK_ENTRIES(dk) can be used to get pointer to entries.
43
44NOTE: Since negative value is used for DKIX_EMPTY and DKIX_DUMMY, type of
45dk_indices entry is signed integer and int16 is used for table which
46dk_size == 256.
47*/
48
Benjamin Peterson7d95e402012-04-23 11:24:50 -040049
50/*
Benjamin Peterson7d95e402012-04-23 11:24:50 -040051The DictObject can be in one of two forms.
Victor Stinner742da042016-09-07 17:40:12 -070052
Benjamin Peterson7d95e402012-04-23 11:24:50 -040053Either:
54 A combined table:
55 ma_values == NULL, dk_refcnt == 1.
56 Values are stored in the me_value field of the PyDictKeysObject.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040057Or:
58 A split table:
59 ma_values != NULL, dk_refcnt >= 1
60 Values are stored in the ma_values array.
Victor Stinner742da042016-09-07 17:40:12 -070061 Only string (unicode) keys are allowed.
62 All dicts sharing same key must have same insertion order.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040063
Victor Stinner742da042016-09-07 17:40:12 -070064There are four kinds of slots in the table (slot is index, and
65DK_ENTRIES(keys)[index] if index >= 0):
66
671. Unused. index == DKIX_EMPTY
68 Does not hold an active (key, value) pair now and never did. Unused can
69 transition to Active upon key insertion. This is each slot's initial state.
70
712. Active. index >= 0, me_key != NULL and me_value != NULL
72 Holds an active (key, value) pair. Active can transition to Dummy or
73 Pending upon key deletion (for combined and split tables respectively).
74 This is the only case in which me_value != NULL.
75
763. Dummy. index == DKIX_DUMMY (combined only)
77 Previously held an active (key, value) pair, but that was deleted and an
78 active pair has not yet overwritten the slot. Dummy can transition to
79 Active upon key insertion. Dummy slots cannot be made Unused again
80 else the probe sequence in case of collision would have no way to know
81 they were once active.
82
834. Pending. index >= 0, key != NULL, and value == NULL (split only)
84 Not yet inserted in split-table.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040085*/
86
Victor Stinner742da042016-09-07 17:40:12 -070087/*
88Preserving insertion order
Benjamin Peterson7d95e402012-04-23 11:24:50 -040089
Victor Stinner742da042016-09-07 17:40:12 -070090It's simple for combined table. Since dk_entries is mostly append only, we can
91get insertion order by just iterating dk_entries.
92
93One exception is .popitem(). It removes last item in dk_entries and decrement
94dk_nentries to achieve amortized O(1). Since there are DKIX_DUMMY remains in
95dk_indices, we can't increment dk_usable even though dk_nentries is
96decremented.
97
98In split table, inserting into pending entry is allowed only for dk_entries[ix]
99where ix == mp->ma_used. Inserting into other index and deleting item cause
100converting the dict to the combined table.
101*/
102
103/* PyDict_MINSIZE is the starting size for any new dict.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400104 * 8 allows dicts with no more than 5 active entries; experiments suggested
105 * this suffices for the majority of dicts (consisting mostly of usually-small
106 * dicts created to pass keyword arguments).
107 * Making this 8, rather than 4 reduces the number of resizes for most
108 * dictionaries, without any significant extra memory use.
109 */
Victor Stinner742da042016-09-07 17:40:12 -0700110#define PyDict_MINSIZE 8
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400111
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112#include "Python.h"
Eric Snow96c6af92015-05-29 22:21:39 -0600113#include "dict-common.h"
Christian Heimes0ded5b52007-12-10 15:50:56 +0000114#include "stringlib/eq.h"
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000115
Larry Hastings61272b72014-01-07 12:41:53 -0800116/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -0800117class dict "PyDictObject *" "&PyDict_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800118[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -0800119/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f157a5a0ce9589d6]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800120
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400121
122/*
123To ensure the lookup algorithm terminates, there must be at least one Unused
124slot (NULL key) in the table.
125To avoid slowing down lookups on a near-full table, we resize the table when
126it's USABLE_FRACTION (currently two-thirds) full.
127*/
Guido van Rossum16e93a81997-01-28 00:00:11 +0000128
Tim Peterseb28ef22001-06-02 05:27:19 +0000129#define PERTURB_SHIFT 5
130
Guido van Rossum16e93a81997-01-28 00:00:11 +0000131/*
Tim Peterseb28ef22001-06-02 05:27:19 +0000132Major subtleties ahead: Most hash schemes depend on having a "good" hash
133function, in the sense of simulating randomness. Python doesn't: its most
R David Murray537ad7a2016-07-10 12:33:18 -0400134important hash functions (for ints) are very regular in common
Tim Peterseb28ef22001-06-02 05:27:19 +0000135cases:
Tim Peters15d49292001-05-27 07:39:22 +0000136
R David Murray537ad7a2016-07-10 12:33:18 -0400137 >>>[hash(i) for i in range(4)]
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000138 [0, 1, 2, 3]
Tim Peters15d49292001-05-27 07:39:22 +0000139
Tim Peterseb28ef22001-06-02 05:27:19 +0000140This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
141the low-order i bits as the initial table index is extremely fast, and there
R David Murray537ad7a2016-07-10 12:33:18 -0400142are no collisions at all for dicts indexed by a contiguous range of ints. So
143this gives better-than-random behavior in common cases, and that's very
144desirable.
Tim Peters15d49292001-05-27 07:39:22 +0000145
Tim Peterseb28ef22001-06-02 05:27:19 +0000146OTOH, when collisions occur, the tendency to fill contiguous slices of the
147hash table makes a good collision resolution strategy crucial. Taking only
148the last i bits of the hash code is also vulnerable: for example, consider
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149the list [i << 16 for i in range(20000)] as a set of keys. Since ints are
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000150their own hash codes, and this fits in a dict of size 2**15, the last 15 bits
151 of every hash code are all 0: they *all* map to the same table index.
Tim Peters15d49292001-05-27 07:39:22 +0000152
Tim Peterseb28ef22001-06-02 05:27:19 +0000153But catering to unusual cases should not slow the usual ones, so we just take
154the last i bits anyway. It's up to collision resolution to do the rest. If
155we *usually* find the key we're looking for on the first try (and, it turns
156out, we usually do -- the table load factor is kept under 2/3, so the odds
157are solidly in our favor), then it makes best sense to keep the initial index
158computation dirt cheap.
Tim Peters15d49292001-05-27 07:39:22 +0000159
Tim Peterseb28ef22001-06-02 05:27:19 +0000160The first half of collision resolution is to visit table indices via this
161recurrence:
Tim Peters15d49292001-05-27 07:39:22 +0000162
Tim Peterseb28ef22001-06-02 05:27:19 +0000163 j = ((5*j) + 1) mod 2**i
Tim Peters15d49292001-05-27 07:39:22 +0000164
Tim Peterseb28ef22001-06-02 05:27:19 +0000165For any initial j in range(2**i), repeating that 2**i times generates each
166int in range(2**i) exactly once (see any text on random-number generation for
167proof). By itself, this doesn't help much: like linear probing (setting
168j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
169order. This would be bad, except that's not the only thing we do, and it's
170actually *good* in the common cases where hash keys are consecutive. In an
171example that's really too small to make this entirely clear, for a table of
172size 2**3 the order of indices is:
Tim Peters15d49292001-05-27 07:39:22 +0000173
Tim Peterseb28ef22001-06-02 05:27:19 +0000174 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
175
176If two things come in at index 5, the first place we look after is index 2,
177not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
178Linear probing is deadly in this case because there the fixed probe order
179is the *same* as the order consecutive keys are likely to arrive. But it's
180extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
181and certain that consecutive hash codes do not.
182
183The other half of the strategy is to get the other bits of the hash code
184into play. This is done by initializing a (unsigned) vrbl "perturb" to the
185full hash code, and changing the recurrence to:
186
187 j = (5*j) + 1 + perturb;
188 perturb >>= PERTURB_SHIFT;
189 use j % 2**i as the next table index;
190
191Now the probe sequence depends (eventually) on every bit in the hash code,
192and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
193because it quickly magnifies small differences in the bits that didn't affect
194the initial index. Note that because perturb is unsigned, if the recurrence
195is executed often enough perturb eventually becomes and remains 0. At that
196point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
197that's certain to find an empty slot eventually (since it generates every int
198in range(2**i), and we make sure there's always at least one empty slot).
199
200Selecting a good value for PERTURB_SHIFT is a balancing act. You want it
201small so that the high bits of the hash code continue to affect the probe
202sequence across iterations; but you want it large so that in really bad cases
203the high-order hash bits have an effect on early iterations. 5 was "the
204best" in minimizing total collisions across experiments Tim Peters ran (on
205both normal and pathological cases), but 4 and 6 weren't significantly worse.
206
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000207Historical: Reimer Behrends contributed the idea of using a polynomial-based
Tim Peterseb28ef22001-06-02 05:27:19 +0000208approach, using repeated multiplication by x in GF(2**n) where an irreducible
209polynomial for each table size was chosen such that x was a primitive root.
210Christian Tismer later extended that to use division by x instead, as an
211efficient way to get the high bits of the hash code into play. This scheme
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000212also gave excellent collision statistics, but was more expensive: two
213if-tests were required inside the loop; computing "the next" index took about
214the same number of operations but without as much potential parallelism
215(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
216above, and then shifting perturb can be done while the table index is being
217masked); and the PyDictObject struct required a member to hold the table's
218polynomial. In Tim's experiments the current scheme ran faster, produced
219equally good collision statistics, needed less code & used less memory.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000220
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000221*/
Tim Petersdea48ec2001-05-22 20:40:22 +0000222
Fred Drake1bff34a2000-08-31 19:31:38 +0000223/* forward declarations */
Victor Stinner742da042016-09-07 17:40:12 -0700224static Py_ssize_t lookdict(PyDictObject *mp, PyObject *key,
225 Py_hash_t hash, PyObject ***value_addr,
226 Py_ssize_t *hashpos);
227static Py_ssize_t lookdict_unicode(PyDictObject *mp, PyObject *key,
228 Py_hash_t hash, PyObject ***value_addr,
229 Py_ssize_t *hashpos);
230static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400231lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700232 Py_hash_t hash, PyObject ***value_addr,
233 Py_ssize_t *hashpos);
234static Py_ssize_t lookdict_split(PyDictObject *mp, PyObject *key,
235 Py_hash_t hash, PyObject ***value_addr,
236 Py_ssize_t *hashpos);
Fred Drake1bff34a2000-08-31 19:31:38 +0000237
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400238static int dictresize(PyDictObject *mp, Py_ssize_t minused);
Tim Petersdea48ec2001-05-22 20:40:22 +0000239
Victor Stinner742da042016-09-07 17:40:12 -0700240/* Dictionary reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +0000241#ifndef PyDict_MAXFREELIST
242#define PyDict_MAXFREELIST 80
243#endif
244static PyDictObject *free_list[PyDict_MAXFREELIST];
245static int numfree = 0;
Victor Stinner742da042016-09-07 17:40:12 -0700246static PyDictKeysObject *keys_free_list[PyDict_MAXFREELIST];
247static int numfreekeys = 0;
Raymond Hettinger43442782004-03-17 21:55:03 +0000248
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300249#include "clinic/dictobject.c.h"
250
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100251int
252PyDict_ClearFreeList(void)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 PyDictObject *op;
Victor Stinner742da042016-09-07 17:40:12 -0700255 int ret = numfree + numfreekeys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 while (numfree) {
257 op = free_list[--numfree];
258 assert(PyDict_CheckExact(op));
259 PyObject_GC_Del(op);
260 }
Victor Stinner742da042016-09-07 17:40:12 -0700261 while (numfreekeys) {
262 PyObject_FREE(keys_free_list[--numfreekeys]);
263 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100264 return ret;
265}
266
David Malcolm49526f42012-06-22 14:55:41 -0400267/* Print summary info about the state of the optimized allocator */
268void
269_PyDict_DebugMallocStats(FILE *out)
270{
271 _PyDebugAllocatorStats(out,
272 "free PyDictObject", numfree, sizeof(PyDictObject));
273}
274
275
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100276void
277PyDict_Fini(void)
278{
279 PyDict_ClearFreeList();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000280}
281
Victor Stinner742da042016-09-07 17:40:12 -0700282#define DK_SIZE(dk) ((dk)->dk_size)
283#if SIZEOF_VOID_P > 4
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700284#define DK_IXSIZE(dk) \
285 (DK_SIZE(dk) <= 0xff ? \
286 1 : DK_SIZE(dk) <= 0xffff ? \
287 2 : DK_SIZE(dk) <= 0xffffffff ? \
288 4 : sizeof(Py_ssize_t))
Victor Stinner742da042016-09-07 17:40:12 -0700289#else
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700290#define DK_IXSIZE(dk) \
291 (DK_SIZE(dk) <= 0xff ? \
292 1 : DK_SIZE(dk) <= 0xffff ? \
293 2 : sizeof(Py_ssize_t))
Victor Stinner742da042016-09-07 17:40:12 -0700294#endif
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700295#define DK_ENTRIES(dk) \
Benjamin Peterson186122e2016-09-08 12:20:12 -0700296 ((PyDictKeyEntry*)(&(dk)->dk_indices.as_1[DK_SIZE(dk) * DK_IXSIZE(dk)]))
Victor Stinner742da042016-09-07 17:40:12 -0700297
Antoine Pitrou2d169b22012-05-12 23:43:44 +0200298#define DK_DEBUG_INCREF _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA
299#define DK_DEBUG_DECREF _Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA
300
301#define DK_INCREF(dk) (DK_DEBUG_INCREF ++(dk)->dk_refcnt)
302#define DK_DECREF(dk) if (DK_DEBUG_DECREF (--(dk)->dk_refcnt) == 0) free_keys_object(dk)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400303#define DK_MASK(dk) (((dk)->dk_size)-1)
304#define IS_POWER_OF_2(x) (((x) & (x-1)) == 0)
305
Victor Stinner742da042016-09-07 17:40:12 -0700306
307/* lookup indices. returns DKIX_EMPTY, DKIX_DUMMY, or ix >=0 */
Benjamin Peterson73222252016-09-08 09:58:47 -0700308static inline Py_ssize_t
Victor Stinner742da042016-09-07 17:40:12 -0700309dk_get_index(PyDictKeysObject *keys, Py_ssize_t i)
310{
311 Py_ssize_t s = DK_SIZE(keys);
Victor Stinner71211e32016-09-08 10:52:46 -0700312 Py_ssize_t ix;
313
Victor Stinner742da042016-09-07 17:40:12 -0700314 if (s <= 0xff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700315 int8_t *indices = keys->dk_indices.as_1;
Victor Stinner208857e2016-09-08 11:35:46 -0700316 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700317 }
318 else if (s <= 0xffff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700319 int16_t *indices = keys->dk_indices.as_2;
Victor Stinner208857e2016-09-08 11:35:46 -0700320 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700321 }
Victor Stinner742da042016-09-07 17:40:12 -0700322 else if (s <= 0xffffffff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700323 int32_t *indices = keys->dk_indices.as_4;
Victor Stinner208857e2016-09-08 11:35:46 -0700324 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700325 }
Victor Stinner742da042016-09-07 17:40:12 -0700326 else {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700327 int64_t *indices = keys->dk_indices.as_8;
Victor Stinner208857e2016-09-08 11:35:46 -0700328 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700329 }
Victor Stinner71211e32016-09-08 10:52:46 -0700330 assert(ix >= DKIX_DUMMY);
331 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700332}
333
334/* write to indices. */
Benjamin Peterson73222252016-09-08 09:58:47 -0700335static inline void
Victor Stinner742da042016-09-07 17:40:12 -0700336dk_set_index(PyDictKeysObject *keys, Py_ssize_t i, Py_ssize_t ix)
337{
338 Py_ssize_t s = DK_SIZE(keys);
Victor Stinner71211e32016-09-08 10:52:46 -0700339
340 assert(ix >= DKIX_DUMMY);
341
Victor Stinner742da042016-09-07 17:40:12 -0700342 if (s <= 0xff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700343 int8_t *indices = keys->dk_indices.as_1;
Victor Stinner71211e32016-09-08 10:52:46 -0700344 assert(ix <= 0x7f);
Victor Stinner208857e2016-09-08 11:35:46 -0700345 indices[i] = (char)ix;
Victor Stinner742da042016-09-07 17:40:12 -0700346 }
347 else if (s <= 0xffff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700348 int16_t *indices = keys->dk_indices.as_2;
Victor Stinner71211e32016-09-08 10:52:46 -0700349 assert(ix <= 0x7fff);
Victor Stinner208857e2016-09-08 11:35:46 -0700350 indices[i] = (int16_t)ix;
Victor Stinner742da042016-09-07 17:40:12 -0700351 }
Victor Stinner742da042016-09-07 17:40:12 -0700352 else if (s <= 0xffffffff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700353 int32_t *indices = keys->dk_indices.as_4;
Victor Stinner71211e32016-09-08 10:52:46 -0700354 assert(ix <= 0x7fffffff);
Victor Stinner208857e2016-09-08 11:35:46 -0700355 indices[i] = (int32_t)ix;
Victor Stinner742da042016-09-07 17:40:12 -0700356 }
Victor Stinner742da042016-09-07 17:40:12 -0700357 else {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700358 int64_t *indices = keys->dk_indices.as_8;
Victor Stinner208857e2016-09-08 11:35:46 -0700359 indices[i] = ix;
Victor Stinner742da042016-09-07 17:40:12 -0700360 }
361}
362
363
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200364/* USABLE_FRACTION is the maximum dictionary load.
Victor Stinner742da042016-09-07 17:40:12 -0700365 * Increasing this ratio makes dictionaries more dense resulting in more
366 * collisions. Decreasing it improves sparseness at the expense of spreading
367 * indices over more cache lines and at the cost of total memory consumed.
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200368 *
369 * USABLE_FRACTION must obey the following:
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400370 * (0 < USABLE_FRACTION(n) < n) for all n >= 2
371 *
Victor Stinner742da042016-09-07 17:40:12 -0700372 * USABLE_FRACTION should be quick to calculate.
373 * Fractions around 1/2 to 2/3 seem to work well in practice.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400374 */
Victor Stinner742da042016-09-07 17:40:12 -0700375#define USABLE_FRACTION(n) (((n) << 1)/3)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400376
Victor Stinner742da042016-09-07 17:40:12 -0700377/* ESTIMATE_SIZE is reverse function of USABLE_FRACTION.
378 * This can be used to reserve enough size to insert n entries without
379 * resizing.
380 */
381#define ESTIMATE_SIZE(n) (((n)*3) >> 1)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400382
Victor Stinner742da042016-09-07 17:40:12 -0700383/* Alternative fraction that is otherwise close enough to 2n/3 to make
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400384 * little difference. 8 * 2/3 == 8 * 5/8 == 5. 16 * 2/3 == 16 * 5/8 == 10.
385 * 32 * 2/3 = 21, 32 * 5/8 = 20.
386 * Its advantage is that it is faster to compute on machines with slow division.
387 * #define USABLE_FRACTION(n) (((n) >> 1) + ((n) >> 2) - ((n) >> 3))
Victor Stinner742da042016-09-07 17:40:12 -0700388 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400389
Victor Stinnera9f61a52013-07-16 22:17:26 +0200390/* GROWTH_RATE. Growth rate upon hitting maximum load.
391 * Currently set to used*2 + capacity/2.
392 * This means that dicts double in size when growing without deletions,
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700393 * but have more head room when the number of deletions is on a par with the
394 * number of insertions.
395 * Raising this to used*4 doubles memory consumption depending on the size of
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200396 * the dictionary, but results in half the number of resizes, less effort to
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700397 * resize.
398 * GROWTH_RATE was set to used*4 up to version 3.2.
399 * GROWTH_RATE was set to used*2 in version 3.3.0
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200400 */
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700401#define GROWTH_RATE(d) (((d)->ma_used*2)+((d)->ma_keys->dk_size>>1))
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400402
403#define ENSURE_ALLOWS_DELETIONS(d) \
404 if ((d)->ma_keys->dk_lookup == lookdict_unicode_nodummy) { \
405 (d)->ma_keys->dk_lookup = lookdict_unicode; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400407
408/* This immutable, empty PyDictKeysObject is used for PyDict_Clear()
409 * (which cannot fail and thus can do no allocation).
410 */
411static PyDictKeysObject empty_keys_struct = {
412 2, /* dk_refcnt 1 for this struct, 1 for dummy_struct */
413 1, /* dk_size */
414 lookdict_split, /* dk_lookup */
415 0, /* dk_usable (immutable) */
Victor Stinner742da042016-09-07 17:40:12 -0700416 0, /* dk_nentries */
Benjamin Peterson186122e2016-09-08 12:20:12 -0700417 .dk_indices = { .as_1 = {DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY,
418 DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY}},
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400419};
420
421static PyObject *empty_values[1] = { NULL };
422
423#define Py_EMPTY_KEYS &empty_keys_struct
424
425static PyDictKeysObject *new_keys_object(Py_ssize_t size)
426{
427 PyDictKeysObject *dk;
Victor Stinner742da042016-09-07 17:40:12 -0700428 Py_ssize_t es, usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400429
Victor Stinner742da042016-09-07 17:40:12 -0700430 assert(size >= PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400431 assert(IS_POWER_OF_2(size));
Victor Stinner742da042016-09-07 17:40:12 -0700432
433 usable = USABLE_FRACTION(size);
434 if (size <= 0xff) {
435 es = 1;
436 }
437 else if (size <= 0xffff) {
438 es = 2;
439 }
440#if SIZEOF_VOID_P > 4
441 else if (size <= 0xffffffff) {
442 es = 4;
443 }
444#endif
445 else {
446 es = sizeof(Py_ssize_t);
447 }
448
449 if (size == PyDict_MINSIZE && numfreekeys > 0) {
450 dk = keys_free_list[--numfreekeys];
451 }
452 else {
Victor Stinner98ee9d52016-09-08 09:33:56 -0700453 dk = PyObject_MALLOC(sizeof(PyDictKeysObject)
454 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
455 + es * size
456 + sizeof(PyDictKeyEntry) * usable);
Victor Stinner742da042016-09-07 17:40:12 -0700457 if (dk == NULL) {
458 PyErr_NoMemory();
459 return NULL;
460 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400461 }
Antoine Pitrou2d169b22012-05-12 23:43:44 +0200462 DK_DEBUG_INCREF dk->dk_refcnt = 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400463 dk->dk_size = size;
Victor Stinner742da042016-09-07 17:40:12 -0700464 dk->dk_usable = usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400465 dk->dk_lookup = lookdict_unicode_nodummy;
Victor Stinner742da042016-09-07 17:40:12 -0700466 dk->dk_nentries = 0;
Benjamin Peterson186122e2016-09-08 12:20:12 -0700467 memset(&dk->dk_indices.as_1[0], 0xff, es * size);
Victor Stinner742da042016-09-07 17:40:12 -0700468 memset(DK_ENTRIES(dk), 0, sizeof(PyDictKeyEntry) * usable);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400469 return dk;
470}
471
472static void
473free_keys_object(PyDictKeysObject *keys)
474{
Victor Stinner742da042016-09-07 17:40:12 -0700475 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400476 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -0700477 for (i = 0, n = keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400478 Py_XDECREF(entries[i].me_key);
479 Py_XDECREF(entries[i].me_value);
480 }
Victor Stinner742da042016-09-07 17:40:12 -0700481 if (keys->dk_size == PyDict_MINSIZE && numfreekeys < PyDict_MAXFREELIST) {
482 keys_free_list[numfreekeys++] = keys;
483 return;
484 }
Raymond Hettingerce5179f2016-01-31 08:56:21 -0800485 PyObject_FREE(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400486}
487
488#define new_values(size) PyMem_NEW(PyObject *, size)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400489#define free_values(values) PyMem_FREE(values)
490
491/* Consumes a reference to the keys object */
492static PyObject *
493new_dict(PyDictKeysObject *keys, PyObject **values)
494{
495 PyDictObject *mp;
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200496 assert(keys != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (numfree) {
498 mp = free_list[--numfree];
499 assert (mp != NULL);
500 assert (Py_TYPE(mp) == &PyDict_Type);
501 _Py_NewReference((PyObject *)mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400503 else {
504 mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
505 if (mp == NULL) {
506 DK_DECREF(keys);
507 free_values(values);
508 return NULL;
509 }
510 }
511 mp->ma_keys = keys;
512 mp->ma_values = values;
513 mp->ma_used = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000515}
516
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400517/* Consumes a reference to the keys object */
518static PyObject *
519new_dict_with_shared_keys(PyDictKeysObject *keys)
520{
521 PyObject **values;
522 Py_ssize_t i, size;
523
Victor Stinner742da042016-09-07 17:40:12 -0700524 size = USABLE_FRACTION(DK_SIZE(keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400525 values = new_values(size);
526 if (values == NULL) {
527 DK_DECREF(keys);
528 return PyErr_NoMemory();
529 }
530 for (i = 0; i < size; i++) {
531 values[i] = NULL;
532 }
533 return new_dict(keys, values);
534}
535
536PyObject *
537PyDict_New(void)
538{
Victor Stinner742da042016-09-07 17:40:12 -0700539 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200540 if (keys == NULL)
541 return NULL;
542 return new_dict(keys, NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400543}
544
Victor Stinner742da042016-09-07 17:40:12 -0700545/* Search index of hash table from offset of entry table */
546static Py_ssize_t
547lookdict_index(PyDictKeysObject *k, Py_hash_t hash, Py_ssize_t index)
548{
549 size_t i, perturb;
550 size_t mask = DK_MASK(k);
551 Py_ssize_t ix;
552
553 i = (size_t)hash & mask;
554 ix = dk_get_index(k, i);
555 if (ix == index) {
556 return i;
557 }
558 if (ix == DKIX_EMPTY) {
559 return DKIX_EMPTY;
560 }
561
562 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
563 i = mask & ((i << 2) + i + perturb + 1);
564 ix = dk_get_index(k, i);
565 if (ix == index) {
566 return i;
567 }
568 if (ix == DKIX_EMPTY) {
569 return DKIX_EMPTY;
570 }
571 }
572 assert(0); /* NOT REACHED */
573 return DKIX_ERROR;
574}
575
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000576/*
577The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000578This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000579Open addressing is preferred over chaining since the link overhead for
580chaining would be substantial (100% with typical malloc overhead).
581
Tim Peterseb28ef22001-06-02 05:27:19 +0000582The initial probe index is computed as hash mod the table size. Subsequent
583probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000584
585All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000586
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000587The details in this version are due to Tim Peters, building on many past
Tim Peterseb28ef22001-06-02 05:27:19 +0000588contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000589Christian Tismer.
Fred Drake1bff34a2000-08-31 19:31:38 +0000590
Victor Stinner742da042016-09-07 17:40:12 -0700591lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a
Victor Stinnera4348cc2016-09-08 12:01:25 -0700592comparison raises an exception.
Guido van Rossum89d8c602007-09-18 17:26:56 +0000593lookdict_unicode() below is specialized to string keys, comparison of which can
Victor Stinner742da042016-09-07 17:40:12 -0700594never raise an exception; that function can never return DKIX_ERROR.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400595lookdict_unicode_nodummy is further specialized for string keys that cannot be
596the <dummy> value.
Victor Stinner742da042016-09-07 17:40:12 -0700597For both, when the key isn't found a DKIX_EMPTY is returned. hashpos returns
598where the key index should be inserted.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000599*/
Victor Stinner742da042016-09-07 17:40:12 -0700600static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400601lookdict(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700602 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000603{
Victor Stinner742da042016-09-07 17:40:12 -0700604 size_t i, perturb, mask;
605 Py_ssize_t ix, freeslot;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200606 int cmp;
Victor Stinner742da042016-09-07 17:40:12 -0700607 PyDictKeysObject *dk;
608 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 PyObject *startkey;
Tim Peterseb28ef22001-06-02 05:27:19 +0000610
Antoine Pitrou9a234902012-05-13 20:48:01 +0200611top:
Victor Stinner742da042016-09-07 17:40:12 -0700612 dk = mp->ma_keys;
613 mask = DK_MASK(dk);
614 ep0 = DK_ENTRIES(dk);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700616
617 ix = dk_get_index(dk, i);
618 if (ix == DKIX_EMPTY) {
619 if (hashpos != NULL)
620 *hashpos = i;
621 *value_addr = NULL;
622 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400623 }
Victor Stinner742da042016-09-07 17:40:12 -0700624 if (ix == DKIX_DUMMY) {
625 freeslot = i;
626 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 else {
Victor Stinner742da042016-09-07 17:40:12 -0700628 ep = &ep0[ix];
629 if (ep->me_key == key) {
630 *value_addr = &ep->me_value;
631 if (hashpos != NULL)
632 *hashpos = i;
633 return ix;
634 }
635 if (ep->me_key != NULL && ep->me_hash == hash) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 startkey = ep->me_key;
637 Py_INCREF(startkey);
638 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
639 Py_DECREF(startkey);
640 if (cmp < 0)
Victor Stinner742da042016-09-07 17:40:12 -0700641 return DKIX_ERROR;
642 if (dk == mp->ma_keys && ep->me_key == startkey) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400643 if (cmp > 0) {
644 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700645 if (hashpos != NULL)
646 *hashpos = i;
647 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400648 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 }
650 else {
Antoine Pitrou9a234902012-05-13 20:48:01 +0200651 /* The dict was mutated, restart */
652 goto top;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 }
654 }
Victor Stinner742da042016-09-07 17:40:12 -0700655 freeslot = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 }
Tim Peters15d49292001-05-27 07:39:22 +0000657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700659 i = ((i << 2) + i + perturb + 1) & mask;
660 ix = dk_get_index(dk, i);
661 if (ix == DKIX_EMPTY) {
662 if (hashpos != NULL) {
663 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400664 }
Victor Stinner742da042016-09-07 17:40:12 -0700665 *value_addr = NULL;
666 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400667 }
Victor Stinner742da042016-09-07 17:40:12 -0700668 if (ix == DKIX_DUMMY) {
669 if (freeslot == -1)
670 freeslot = i;
671 continue;
672 }
673 ep = &ep0[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400674 if (ep->me_key == key) {
Victor Stinner742da042016-09-07 17:40:12 -0700675 if (hashpos != NULL) {
676 *hashpos = i;
677 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400678 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700679 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400680 }
Victor Stinner742da042016-09-07 17:40:12 -0700681 if (ep->me_hash == hash && ep->me_key != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 startkey = ep->me_key;
683 Py_INCREF(startkey);
684 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
685 Py_DECREF(startkey);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400686 if (cmp < 0) {
687 *value_addr = NULL;
Victor Stinner742da042016-09-07 17:40:12 -0700688 return DKIX_ERROR;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400689 }
Victor Stinner742da042016-09-07 17:40:12 -0700690 if (dk == mp->ma_keys && ep->me_key == startkey) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400691 if (cmp > 0) {
Victor Stinner742da042016-09-07 17:40:12 -0700692 if (hashpos != NULL) {
693 *hashpos = i;
694 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400695 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700696 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400697 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 }
699 else {
Antoine Pitrou9a234902012-05-13 20:48:01 +0200700 /* The dict was mutated, restart */
701 goto top;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 }
703 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 }
705 assert(0); /* NOT REACHED */
706 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000707}
708
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400709/* Specialized version for string-only keys */
Victor Stinner742da042016-09-07 17:40:12 -0700710static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400711lookdict_unicode(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700712 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Fred Drake1bff34a2000-08-31 19:31:38 +0000713{
Victor Stinner742da042016-09-07 17:40:12 -0700714 size_t i, perturb;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200715 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700716 Py_ssize_t ix, freeslot;
717 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Fred Drake1bff34a2000-08-31 19:31:38 +0000718
Victor Stinner742da042016-09-07 17:40:12 -0700719 assert(mp->ma_values == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 /* Make sure this function doesn't have to handle non-unicode keys,
721 including subclasses of str; e.g., one reason to subclass
722 unicodes is to override __eq__, and for speed we don't cater to
723 that here. */
724 if (!PyUnicode_CheckExact(key)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400725 mp->ma_keys->dk_lookup = lookdict;
Victor Stinner742da042016-09-07 17:40:12 -0700726 return lookdict(mp, key, hash, value_addr, hashpos);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 }
Mark Dickinson57e683e2011-09-24 18:18:40 +0100728 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700729 ix = dk_get_index(mp->ma_keys, i);
730 if (ix == DKIX_EMPTY) {
731 if (hashpos != NULL)
732 *hashpos = i;
733 *value_addr = NULL;
734 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400735 }
Victor Stinner742da042016-09-07 17:40:12 -0700736 if (ix == DKIX_DUMMY) {
737 freeslot = i;
738 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 else {
Victor Stinner742da042016-09-07 17:40:12 -0700740 ep = &ep0[ix];
741 /* only split table can be ix != DKIX_DUMMY && me_key == NULL */
742 assert(ep->me_key != NULL);
743 if (ep->me_key == key || (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
744 if (hashpos != NULL)
745 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400746 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700747 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400748 }
Victor Stinner742da042016-09-07 17:40:12 -0700749 freeslot = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 }
Tim Peters15d49292001-05-27 07:39:22 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700753 i = mask & ((i << 2) + i + perturb + 1);
754 ix = dk_get_index(mp->ma_keys, i);
755 if (ix == DKIX_EMPTY) {
756 if (hashpos != NULL) {
757 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400758 }
Victor Stinner742da042016-09-07 17:40:12 -0700759 *value_addr = NULL;
760 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400761 }
Victor Stinner742da042016-09-07 17:40:12 -0700762 if (ix == DKIX_DUMMY) {
763 if (freeslot == -1)
764 freeslot = i;
765 continue;
766 }
767 ep = &ep0[ix];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 if (ep->me_key == key
769 || (ep->me_hash == hash
Victor Stinner742da042016-09-07 17:40:12 -0700770 && ep->me_key != NULL
771 && unicode_eq(ep->me_key, key))) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400772 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700773 if (hashpos != NULL) {
774 *hashpos = i;
775 }
776 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400777 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 }
779 assert(0); /* NOT REACHED */
780 return 0;
Fred Drake1bff34a2000-08-31 19:31:38 +0000781}
782
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400783/* Faster version of lookdict_unicode when it is known that no <dummy> keys
784 * will be present. */
Victor Stinner742da042016-09-07 17:40:12 -0700785static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400786lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700787 Py_hash_t hash, PyObject ***value_addr,
788 Py_ssize_t *hashpos)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400789{
Victor Stinner742da042016-09-07 17:40:12 -0700790 size_t i, perturb;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200791 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700792 Py_ssize_t ix;
793 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400794
Victor Stinner742da042016-09-07 17:40:12 -0700795 assert(mp->ma_values == NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400796 /* Make sure this function doesn't have to handle non-unicode keys,
797 including subclasses of str; e.g., one reason to subclass
798 unicodes is to override __eq__, and for speed we don't cater to
799 that here. */
800 if (!PyUnicode_CheckExact(key)) {
801 mp->ma_keys->dk_lookup = lookdict;
Victor Stinner742da042016-09-07 17:40:12 -0700802 return lookdict(mp, key, hash, value_addr, hashpos);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400803 }
804 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700805 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];
Victor Stinnerdee6e252016-09-08 11:16:07 -0700814 assert(ep->me_key != NULL);
815 assert(PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700816 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400817 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700818 if (hashpos != NULL)
819 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400820 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700821 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400822 }
823 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700824 i = mask & ((i << 2) + i + perturb + 1);
825 ix = dk_get_index(mp->ma_keys, i);
826 assert (ix != DKIX_DUMMY);
827 if (ix == DKIX_EMPTY) {
828 if (hashpos != NULL)
829 *hashpos = i;
830 *value_addr = NULL;
831 return DKIX_EMPTY;
832 }
833 ep = &ep0[ix];
834 assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
835 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400836 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700837 if (hashpos != NULL)
838 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400839 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700840 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400841 }
842 }
843 assert(0); /* NOT REACHED */
844 return 0;
845}
846
847/* Version of lookdict for split tables.
848 * All split tables and only split tables use this lookup function.
849 * Split tables only contain unicode keys and no dummy keys,
850 * so algorithm is the same as lookdict_unicode_nodummy.
851 */
Victor Stinner742da042016-09-07 17:40:12 -0700852static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400853lookdict_split(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700854 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400855{
Victor Stinner742da042016-09-07 17:40:12 -0700856 size_t i, perturb;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200857 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700858 Py_ssize_t ix;
859 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400860
Victor Stinner742da042016-09-07 17:40:12 -0700861 /* mp must split table */
862 assert(mp->ma_values != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400863 if (!PyUnicode_CheckExact(key)) {
Victor Stinner742da042016-09-07 17:40:12 -0700864 ix = lookdict(mp, key, hash, value_addr, hashpos);
865 if (ix >= 0) {
866 *value_addr = &mp->ma_values[ix];
867 }
868 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400869 }
Victor Stinner742da042016-09-07 17:40:12 -0700870
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400871 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700872 ix = dk_get_index(mp->ma_keys, i);
873 if (ix == DKIX_EMPTY) {
874 if (hashpos != NULL)
875 *hashpos = i;
876 *value_addr = NULL;
877 return DKIX_EMPTY;
878 }
879 assert(ix >= 0);
880 ep = &ep0[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400881 assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700882 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400883 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700884 if (hashpos != NULL)
885 *hashpos = i;
886 *value_addr = &mp->ma_values[ix];
887 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400888 }
889 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700890 i = mask & ((i << 2) + i + perturb + 1);
891 ix = dk_get_index(mp->ma_keys, i);
892 if (ix == DKIX_EMPTY) {
893 if (hashpos != NULL)
894 *hashpos = i;
895 *value_addr = NULL;
896 return DKIX_EMPTY;
897 }
898 assert(ix >= 0);
899 ep = &ep0[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400900 assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700901 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400902 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700903 if (hashpos != NULL)
904 *hashpos = i;
905 *value_addr = &mp->ma_values[ix];
906 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400907 }
908 }
909 assert(0); /* NOT REACHED */
910 return 0;
911}
912
Benjamin Petersonfb886362010-04-24 18:21:17 +0000913int
914_PyDict_HasOnlyStringKeys(PyObject *dict)
915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 Py_ssize_t pos = 0;
917 PyObject *key, *value;
Benjamin Petersonf6096542010-11-17 22:33:12 +0000918 assert(PyDict_Check(dict));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 /* Shortcut */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400920 if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 return 1;
922 while (PyDict_Next(dict, &pos, &key, &value))
923 if (!PyUnicode_Check(key))
924 return 0;
925 return 1;
Benjamin Petersonfb886362010-04-24 18:21:17 +0000926}
927
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000928#define MAINTAIN_TRACKING(mp, key, value) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 do { \
930 if (!_PyObject_GC_IS_TRACKED(mp)) { \
931 if (_PyObject_GC_MAY_BE_TRACKED(key) || \
932 _PyObject_GC_MAY_BE_TRACKED(value)) { \
933 _PyObject_GC_TRACK(mp); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 } \
935 } \
936 } while(0)
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000937
938void
939_PyDict_MaybeUntrack(PyObject *op)
940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 PyDictObject *mp;
942 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -0700943 Py_ssize_t i, numentries;
944 PyDictKeyEntry *ep0;
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
947 return;
948
949 mp = (PyDictObject *) op;
Victor Stinner742da042016-09-07 17:40:12 -0700950 ep0 = DK_ENTRIES(mp->ma_keys);
951 numentries = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400952 if (_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -0700953 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400954 if ((value = mp->ma_values[i]) == NULL)
955 continue;
956 if (_PyObject_GC_MAY_BE_TRACKED(value)) {
Victor Stinner742da042016-09-07 17:40:12 -0700957 assert(!_PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400958 return;
959 }
960 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400962 else {
Victor Stinner742da042016-09-07 17:40:12 -0700963 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400964 if ((value = ep0[i].me_value) == NULL)
965 continue;
966 if (_PyObject_GC_MAY_BE_TRACKED(value) ||
967 _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
968 return;
969 }
970 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 _PyObject_GC_UNTRACK(op);
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000972}
973
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400974/* Internal function to find slot for an item from its hash
975 * when it is known that the key is not present in the dict.
976 */
Victor Stinner742da042016-09-07 17:40:12 -0700977static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400978find_empty_slot(PyDictObject *mp, PyObject *key, Py_hash_t hash,
Victor Stinner742da042016-09-07 17:40:12 -0700979 PyObject ***value_addr, Py_ssize_t *hashpos)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000980{
Victor Stinner742da042016-09-07 17:40:12 -0700981 size_t i, perturb;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400982 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700983 Py_ssize_t ix;
984 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000985
Victor Stinner742da042016-09-07 17:40:12 -0700986 assert(hashpos != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400987 assert(key != NULL);
988 if (!PyUnicode_CheckExact(key))
989 mp->ma_keys->dk_lookup = lookdict;
990 i = hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700991 ix = dk_get_index(mp->ma_keys, i);
992 for (perturb = hash; ix != DKIX_EMPTY; perturb >>= PERTURB_SHIFT) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400993 i = (i << 2) + i + perturb + 1;
Victor Stinner742da042016-09-07 17:40:12 -0700994 ix = dk_get_index(mp->ma_keys, i & mask);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 }
Victor Stinner742da042016-09-07 17:40:12 -0700996 ep = &ep0[mp->ma_keys->dk_nentries];
997 *hashpos = i & mask;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400998 assert(ep->me_value == NULL);
999 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07001000 *value_addr = &mp->ma_values[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001001 else
1002 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -07001003 return ix;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001004}
1005
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001006static int
1007insertion_resize(PyDictObject *mp)
1008{
Raymond Hettinger36f74aa2013-05-17 03:01:13 -07001009 return dictresize(mp, GROWTH_RATE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001010}
Antoine Pitroue965d972012-02-27 00:45:12 +01001011
1012/*
1013Internal routine to insert a new item into the table.
1014Used both by the internal resize routine and by the public insert routine.
Antoine Pitroue965d972012-02-27 00:45:12 +01001015Returns -1 if an error occurred, or 0 on success.
1016*/
1017static int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001018insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001019{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001020 PyObject *old_value;
1021 PyObject **value_addr;
Victor Stinner742da042016-09-07 17:40:12 -07001022 PyDictKeyEntry *ep, *ep0;
1023 Py_ssize_t hashpos, ix;
Antoine Pitroue965d972012-02-27 00:45:12 +01001024
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001025 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
1026 if (insertion_resize(mp) < 0)
1027 return -1;
1028 }
1029
Victor Stinner742da042016-09-07 17:40:12 -07001030 ix = mp->ma_keys->dk_lookup(mp, key, hash, &value_addr, &hashpos);
1031 if (ix == DKIX_ERROR) {
Antoine Pitroue965d972012-02-27 00:45:12 +01001032 return -1;
1033 }
Victor Stinner742da042016-09-07 17:40:12 -07001034
Antoine Pitroud6967322014-10-18 00:35:00 +02001035 assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
Benjamin Petersona6f195e2012-04-30 10:23:40 -04001036 Py_INCREF(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001037 MAINTAIN_TRACKING(mp, key, value);
Victor Stinner742da042016-09-07 17:40:12 -07001038
1039 /* When insertion order is different from shared key, we can't share
1040 * the key anymore. Convert this instance to combine table.
1041 */
1042 if (_PyDict_HasSplitTable(mp) &&
1043 ((ix >= 0 && *value_addr == NULL && mp->ma_used != ix) ||
1044 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
1045 if (insertion_resize(mp) < 0) {
1046 Py_DECREF(value);
1047 return -1;
1048 }
1049 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
1050 ix = DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001051 }
Victor Stinner742da042016-09-07 17:40:12 -07001052
1053 if (ix == DKIX_EMPTY) {
1054 /* Insert into new slot. */
1055 if (mp->ma_keys->dk_usable <= 0) {
1056 /* Need to resize. */
1057 if (insertion_resize(mp) < 0) {
1058 Py_DECREF(value);
1059 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001060 }
Victor Stinner742da042016-09-07 17:40:12 -07001061 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
1062 }
1063 ep0 = DK_ENTRIES(mp->ma_keys);
1064 ep = &ep0[mp->ma_keys->dk_nentries];
1065 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
1066 Py_INCREF(key);
1067 ep->me_key = key;
1068 ep->me_hash = hash;
1069 if (mp->ma_values) {
1070 assert (mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
1071 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001072 }
1073 else {
Victor Stinner742da042016-09-07 17:40:12 -07001074 ep->me_value = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001075 }
1076 mp->ma_used++;
Victor Stinner742da042016-09-07 17:40:12 -07001077 mp->ma_keys->dk_usable--;
1078 mp->ma_keys->dk_nentries++;
1079 assert(mp->ma_keys->dk_usable >= 0);
1080 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001081 }
Victor Stinner742da042016-09-07 17:40:12 -07001082
1083 assert(value_addr != NULL);
1084
1085 old_value = *value_addr;
1086 if (old_value != NULL) {
1087 *value_addr = value;
1088 Py_DECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
1089 return 0;
1090 }
1091
1092 /* pending state */
1093 assert(_PyDict_HasSplitTable(mp));
1094 assert(ix == mp->ma_used);
1095 *value_addr = value;
1096 mp->ma_used++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001097 return 0;
Antoine Pitroue965d972012-02-27 00:45:12 +01001098}
1099
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001100/*
1101Internal routine used by dictresize() to insert an item which is
1102known to be absent from the dict. This routine also assumes that
1103the dict contains no deleted entries. Besides the performance benefit,
1104using insertdict() in dictresize() is dangerous (SF bug #1456209).
1105Note that no refcounts are changed by this routine; if needed, the caller
1106is responsible for incref'ing `key` and `value`.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001107Neither mp->ma_used nor k->dk_usable are modified by this routine; the caller
1108must set them correctly
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001109*/
1110static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001111insertdict_clean(PyDictObject *mp, PyObject *key, Py_hash_t hash,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 PyObject *value)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001113{
Victor Stinner742da042016-09-07 17:40:12 -07001114 size_t i, perturb;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001115 PyDictKeysObject *k = mp->ma_keys;
1116 size_t mask = (size_t)DK_SIZE(k)-1;
Victor Stinner742da042016-09-07 17:40:12 -07001117 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001118 PyDictKeyEntry *ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001119
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001120 assert(k->dk_lookup != NULL);
1121 assert(value != NULL);
1122 assert(key != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001123 assert(PyUnicode_CheckExact(key) || k->dk_lookup == lookdict);
1124 i = hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -07001125 for (perturb = hash; dk_get_index(k, i) != DKIX_EMPTY;
1126 perturb >>= PERTURB_SHIFT) {
1127 i = mask & ((i << 2) + i + perturb + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 }
Victor Stinner742da042016-09-07 17:40:12 -07001129 ep = &ep0[k->dk_nentries];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 assert(ep->me_value == NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001131 dk_set_index(k, i, k->dk_nentries);
1132 k->dk_nentries++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 ep->me_key = key;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001134 ep->me_hash = hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 ep->me_value = value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001136}
1137
1138/*
1139Restructure the table by allocating a new table and reinserting all
1140items again. When entries have been deleted, the new table may
1141actually be smaller than the old one.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001142If a table is split (its keys and hashes are shared, its values are not),
1143then the values are temporarily copied into the table, it is resized as
1144a combined table, then the me_value slots in the old table are NULLed out.
1145After resizing a table is always combined,
1146but can be resplit by make_keys_shared().
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001147*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001148static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001149dictresize(PyDictObject *mp, Py_ssize_t minused)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001150{
Victor Stinner742da042016-09-07 17:40:12 -07001151 Py_ssize_t i, newsize;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001152 PyDictKeysObject *oldkeys;
1153 PyObject **oldvalues;
Victor Stinner742da042016-09-07 17:40:12 -07001154 PyDictKeyEntry *ep0;
Tim Peters91a364d2001-05-19 07:04:38 +00001155
Victor Stinner742da042016-09-07 17:40:12 -07001156 /* Find the smallest table size > minused. */
1157 for (newsize = PyDict_MINSIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 newsize <= minused && newsize > 0;
1159 newsize <<= 1)
1160 ;
1161 if (newsize <= 0) {
1162 PyErr_NoMemory();
1163 return -1;
1164 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001165 oldkeys = mp->ma_keys;
1166 oldvalues = mp->ma_values;
1167 /* Allocate a new table. */
1168 mp->ma_keys = new_keys_object(newsize);
1169 if (mp->ma_keys == NULL) {
1170 mp->ma_keys = oldkeys;
1171 return -1;
1172 }
1173 if (oldkeys->dk_lookup == lookdict)
1174 mp->ma_keys->dk_lookup = lookdict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001175 mp->ma_values = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001176 ep0 = DK_ENTRIES(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001177 /* Main loop below assumes we can transfer refcount to new keys
1178 * and that value is stored in me_value.
1179 * Increment ref-counts and copy values here to compensate
1180 * This (resizing a split table) should be relatively rare */
1181 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001182 for (i = 0; i < oldkeys->dk_nentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001183 if (oldvalues[i] != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001184 Py_INCREF(ep0[i].me_key);
1185 ep0[i].me_value = oldvalues[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 }
1188 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001189 /* Main loop */
Victor Stinner742da042016-09-07 17:40:12 -07001190 for (i = 0; i < oldkeys->dk_nentries; i++) {
1191 PyDictKeyEntry *ep = &ep0[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001192 if (ep->me_value != NULL) {
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001193 insertdict_clean(mp, ep->me_key, ep->me_hash, ep->me_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001196 mp->ma_keys->dk_usable -= mp->ma_used;
1197 if (oldvalues != NULL) {
1198 /* NULL out me_value slot in oldkeys, in case it was shared */
Victor Stinner742da042016-09-07 17:40:12 -07001199 for (i = 0; i < oldkeys->dk_nentries; i++)
1200 ep0[i].me_value = NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001201 DK_DECREF(oldkeys);
Victor Stinner742da042016-09-07 17:40:12 -07001202 if (oldvalues != empty_values) {
1203 free_values(oldvalues);
1204 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001205 }
1206 else {
1207 assert(oldkeys->dk_lookup != lookdict_split);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001208 assert(oldkeys->dk_refcnt == 1);
Raymond Hettingerce5179f2016-01-31 08:56:21 -08001209 DK_DEBUG_DECREF PyObject_FREE(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001210 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001212}
1213
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001214/* Returns NULL if unable to split table.
1215 * A NULL return does not necessarily indicate an error */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001216static PyDictKeysObject *
1217make_keys_shared(PyObject *op)
1218{
1219 Py_ssize_t i;
1220 Py_ssize_t size;
1221 PyDictObject *mp = (PyDictObject *)op;
1222
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001223 if (!PyDict_CheckExact(op))
1224 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001225 if (!_PyDict_HasSplitTable(mp)) {
1226 PyDictKeyEntry *ep0;
1227 PyObject **values;
1228 assert(mp->ma_keys->dk_refcnt == 1);
1229 if (mp->ma_keys->dk_lookup == lookdict) {
1230 return NULL;
1231 }
1232 else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
1233 /* Remove dummy keys */
1234 if (dictresize(mp, DK_SIZE(mp->ma_keys)))
1235 return NULL;
1236 }
1237 assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
1238 /* Copy values into a new array */
Victor Stinner742da042016-09-07 17:40:12 -07001239 ep0 = DK_ENTRIES(mp->ma_keys);
1240 size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001241 values = new_values(size);
1242 if (values == NULL) {
1243 PyErr_SetString(PyExc_MemoryError,
1244 "Not enough memory to allocate new values array");
1245 return NULL;
1246 }
1247 for (i = 0; i < size; i++) {
1248 values[i] = ep0[i].me_value;
1249 ep0[i].me_value = NULL;
1250 }
1251 mp->ma_keys->dk_lookup = lookdict_split;
1252 mp->ma_values = values;
1253 }
1254 DK_INCREF(mp->ma_keys);
1255 return mp->ma_keys;
1256}
Christian Heimes99170a52007-12-19 02:07:34 +00001257
1258PyObject *
1259_PyDict_NewPresized(Py_ssize_t minused)
1260{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001261 Py_ssize_t newsize;
1262 PyDictKeysObject *new_keys;
Victor Stinner742da042016-09-07 17:40:12 -07001263 for (newsize = PyDict_MINSIZE;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001264 newsize <= minused && newsize > 0;
1265 newsize <<= 1)
1266 ;
1267 new_keys = new_keys_object(newsize);
1268 if (new_keys == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001270 return new_dict(new_keys, NULL);
Christian Heimes99170a52007-12-19 02:07:34 +00001271}
1272
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001273/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
1274 * that may occur (originally dicts supported only string keys, and exceptions
1275 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001276 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001277 * (suppressed) occurred while computing the key's hash, or that some error
1278 * (suppressed) occurred when comparing keys in the dict's internal probe
1279 * sequence. A nasty example of the latter is when a Python-coded comparison
1280 * function hits a stack-depth error, which can cause this to return NULL
1281 * even if the key is present.
1282 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001283PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001284PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001285{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001286 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001287 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 PyDictObject *mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 PyThreadState *tstate;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001290 PyObject **value_addr;
1291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 if (!PyDict_Check(op))
1293 return NULL;
1294 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001295 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 {
1297 hash = PyObject_Hash(key);
1298 if (hash == -1) {
1299 PyErr_Clear();
1300 return NULL;
1301 }
1302 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 /* We can arrive here with a NULL tstate during initialization: try
1305 running "python -Wi" for an example related to string interning.
1306 Let's just hope that no exception occurs then... This must be
1307 _PyThreadState_Current and not PyThreadState_GET() because in debug
1308 mode, the latter complains if tstate is NULL. */
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001309 tstate = _PyThreadState_UncheckedGet();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 if (tstate != NULL && tstate->curexc_type != NULL) {
1311 /* preserve the existing exception */
1312 PyObject *err_type, *err_value, *err_tb;
1313 PyErr_Fetch(&err_type, &err_value, &err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001314 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 /* ignore errors */
1316 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001317 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 return NULL;
1319 }
1320 else {
Victor Stinner742da042016-09-07 17:40:12 -07001321 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1322 if (ix < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 PyErr_Clear();
1324 return NULL;
1325 }
1326 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001327 return *value_addr;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001328}
1329
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001330PyObject *
1331_PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1332{
Victor Stinner742da042016-09-07 17:40:12 -07001333 Py_ssize_t ix;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001334 PyDictObject *mp = (PyDictObject *)op;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001335 PyThreadState *tstate;
1336 PyObject **value_addr;
1337
1338 if (!PyDict_Check(op))
1339 return NULL;
1340
1341 /* We can arrive here with a NULL tstate during initialization: try
1342 running "python -Wi" for an example related to string interning.
1343 Let's just hope that no exception occurs then... This must be
1344 _PyThreadState_Current and not PyThreadState_GET() because in debug
1345 mode, the latter complains if tstate is NULL. */
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001346 tstate = _PyThreadState_UncheckedGet();
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001347 if (tstate != NULL && tstate->curexc_type != NULL) {
1348 /* preserve the existing exception */
1349 PyObject *err_type, *err_value, *err_tb;
1350 PyErr_Fetch(&err_type, &err_value, &err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001351 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001352 /* ignore errors */
1353 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001354 if (ix == DKIX_EMPTY)
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001355 return NULL;
1356 }
1357 else {
Victor Stinner742da042016-09-07 17:40:12 -07001358 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1359 if (ix == DKIX_EMPTY) {
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001360 PyErr_Clear();
1361 return NULL;
1362 }
1363 }
1364 return *value_addr;
1365}
1366
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001367/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
1368 This returns NULL *with* an exception set if an exception occurred.
1369 It returns NULL *without* an exception set if the key wasn't present.
1370*/
1371PyObject *
1372PyDict_GetItemWithError(PyObject *op, PyObject *key)
1373{
Victor Stinner742da042016-09-07 17:40:12 -07001374 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001375 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 PyDictObject*mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001377 PyObject **value_addr;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 if (!PyDict_Check(op)) {
1380 PyErr_BadInternalCall();
1381 return NULL;
1382 }
1383 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001384 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 {
1386 hash = PyObject_Hash(key);
1387 if (hash == -1) {
1388 return NULL;
1389 }
1390 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001391
Victor Stinner742da042016-09-07 17:40:12 -07001392 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1393 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001395 return *value_addr;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001396}
1397
Brett Cannonfd074152012-04-14 14:10:13 -04001398PyObject *
1399_PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
1400{
1401 PyObject *kv;
1402 kv = _PyUnicode_FromId(key); /* borrowed */
1403 if (kv == NULL)
1404 return NULL;
1405 return PyDict_GetItemWithError(dp, kv);
1406}
1407
Victor Stinnerb4efc962015-11-20 09:24:02 +01001408/* Fast version of global value lookup (LOAD_GLOBAL).
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001409 * Lookup in globals, then builtins.
Victor Stinnerb4efc962015-11-20 09:24:02 +01001410 *
1411 * Raise an exception and return NULL if an error occurred (ex: computing the
1412 * key hash failed, key comparison failed, ...). Return NULL if the key doesn't
1413 * exist. Return the value if the key exists.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001414 */
1415PyObject *
1416_PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001417{
Victor Stinner742da042016-09-07 17:40:12 -07001418 Py_ssize_t ix;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001419 Py_hash_t hash;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001420 PyObject **value_addr;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001421
1422 if (!PyUnicode_CheckExact(key) ||
1423 (hash = ((PyASCIIObject *) key)->hash) == -1)
1424 {
1425 hash = PyObject_Hash(key);
1426 if (hash == -1)
1427 return NULL;
Antoine Pitroue965d972012-02-27 00:45:12 +01001428 }
Victor Stinnerb4efc962015-11-20 09:24:02 +01001429
1430 /* namespace 1: globals */
Victor Stinner742da042016-09-07 17:40:12 -07001431 ix = globals->ma_keys->dk_lookup(globals, key, hash, &value_addr, NULL);
1432 if (ix == DKIX_ERROR)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001433 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001434 if (ix != DKIX_EMPTY && *value_addr != NULL)
1435 return *value_addr;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001436
1437 /* namespace 2: builtins */
Victor Stinner742da042016-09-07 17:40:12 -07001438 ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value_addr, NULL);
1439 if (ix < 0)
Victor Stinnerb4efc962015-11-20 09:24:02 +01001440 return NULL;
1441 return *value_addr;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001442}
1443
Antoine Pitroue965d972012-02-27 00:45:12 +01001444/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
1445 * dictionary if it's merely replacing the value for an existing key.
1446 * This means that it's safe to loop over a dictionary with PyDict_Next()
1447 * and occasionally replace a value -- but you can't insert new keys or
1448 * remove them.
1449 */
1450int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001451PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001452{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001453 PyDictObject *mp;
1454 Py_hash_t hash;
Antoine Pitroue965d972012-02-27 00:45:12 +01001455 if (!PyDict_Check(op)) {
1456 PyErr_BadInternalCall();
1457 return -1;
1458 }
1459 assert(key);
1460 assert(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001461 mp = (PyDictObject *)op;
1462 if (!PyUnicode_CheckExact(key) ||
1463 (hash = ((PyASCIIObject *) key)->hash) == -1)
1464 {
Antoine Pitroue965d972012-02-27 00:45:12 +01001465 hash = PyObject_Hash(key);
1466 if (hash == -1)
1467 return -1;
1468 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001469
1470 /* insertdict() handles any resizing that might be necessary */
1471 return insertdict(mp, key, hash, value);
Antoine Pitroue965d972012-02-27 00:45:12 +01001472}
1473
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001474int
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001475_PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
1476 Py_hash_t hash)
1477{
1478 PyDictObject *mp;
1479
1480 if (!PyDict_Check(op)) {
1481 PyErr_BadInternalCall();
1482 return -1;
1483 }
1484 assert(key);
1485 assert(value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001486 assert(hash != -1);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001487 mp = (PyDictObject *)op;
1488
1489 /* insertdict() handles any resizing that might be necessary */
1490 return insertdict(mp, key, hash, value);
1491}
1492
1493int
Tim Peters1f5871e2000-07-04 17:44:48 +00001494PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001495{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001496 Py_hash_t hash;
Guido van Rossumd7047b31995-01-02 19:07:15 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 assert(key);
1499 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001500 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 hash = PyObject_Hash(key);
1502 if (hash == -1)
1503 return -1;
1504 }
Victor Stinner742da042016-09-07 17:40:12 -07001505
1506 return _PyDict_DelItem_KnownHash(op, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001507}
1508
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001509int
1510_PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1511{
Victor Stinner742da042016-09-07 17:40:12 -07001512 Py_ssize_t hashpos, ix;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001513 PyDictObject *mp;
1514 PyDictKeyEntry *ep;
1515 PyObject *old_key, *old_value;
1516 PyObject **value_addr;
1517
1518 if (!PyDict_Check(op)) {
1519 PyErr_BadInternalCall();
1520 return -1;
1521 }
1522 assert(key);
1523 assert(hash != -1);
1524 mp = (PyDictObject *)op;
Victor Stinner742da042016-09-07 17:40:12 -07001525 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1526 if (ix == DKIX_ERROR)
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001527 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07001528 if (ix == DKIX_EMPTY || *value_addr == NULL) {
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001529 _PyErr_SetKeyError(key);
1530 return -1;
1531 }
Victor Stinner742da042016-09-07 17:40:12 -07001532 assert(dk_get_index(mp->ma_keys, hashpos) == ix);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001533 old_value = *value_addr;
1534 *value_addr = NULL;
1535 mp->ma_used--;
Victor Stinner742da042016-09-07 17:40:12 -07001536 if (_PyDict_HasSplitTable(mp)) {
1537 mp->ma_keys->dk_usable = 0;
1538 }
1539 else {
1540 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1541 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001542 ENSURE_ALLOWS_DELETIONS(mp);
1543 old_key = ep->me_key;
Victor Stinner742da042016-09-07 17:40:12 -07001544 ep->me_key = NULL;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001545 Py_DECREF(old_key);
1546 }
1547 Py_DECREF(old_value);
1548 return 0;
1549}
1550
Guido van Rossum25831651993-05-19 14:50:45 +00001551void
Tim Peters1f5871e2000-07-04 17:44:48 +00001552PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 PyDictObject *mp;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001555 PyDictKeysObject *oldkeys;
1556 PyObject **oldvalues;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +00001558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 if (!PyDict_Check(op))
1560 return;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001561 mp = ((PyDictObject *)op);
1562 oldkeys = mp->ma_keys;
1563 oldvalues = mp->ma_values;
1564 if (oldvalues == empty_values)
1565 return;
1566 /* Empty the dict... */
1567 DK_INCREF(Py_EMPTY_KEYS);
1568 mp->ma_keys = Py_EMPTY_KEYS;
1569 mp->ma_values = empty_values;
1570 mp->ma_used = 0;
1571 /* ...then clear the keys and values */
1572 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001573 n = oldkeys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001574 for (i = 0; i < n; i++)
1575 Py_CLEAR(oldvalues[i]);
1576 free_values(oldvalues);
1577 DK_DECREF(oldkeys);
1578 }
1579 else {
1580 assert(oldkeys->dk_refcnt == 1);
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001581 DK_DECREF(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001582 }
1583}
1584
1585/* Returns -1 if no more items (or op is not a dict),
1586 * index of item otherwise. Stores value in pvalue
1587 */
Benjamin Peterson73222252016-09-08 09:58:47 -07001588static inline Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001589dict_next(PyObject *op, Py_ssize_t i, PyObject **pvalue)
1590{
Victor Stinner742da042016-09-07 17:40:12 -07001591 Py_ssize_t n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001592 PyDictObject *mp;
Victor Stinner742da042016-09-07 17:40:12 -07001593 PyObject **value_ptr = NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001594
1595 if (!PyDict_Check(op))
1596 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001598 if (i < 0)
1599 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07001600
1601 n = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001602 if (mp->ma_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001603 for (; i < n; i++) {
1604 value_ptr = &mp->ma_values[i];
1605 if (*value_ptr != NULL)
1606 break;
1607 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001609 else {
Victor Stinner742da042016-09-07 17:40:12 -07001610 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
1611 for (; i < n; i++) {
1612 value_ptr = &ep0[i].me_value;
1613 if (*value_ptr != NULL)
1614 break;
1615 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 }
Victor Stinner742da042016-09-07 17:40:12 -07001617 if (i >= n)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001618 return -1;
1619 if (pvalue)
1620 *pvalue = *value_ptr;
1621 return i;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001622}
1623
Tim Peters080c88b2003-02-15 03:01:11 +00001624/*
1625 * Iterate over a dict. Use like so:
1626 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001627 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +00001628 * PyObject *key, *value;
1629 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +00001630 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Tim Peters080c88b2003-02-15 03:01:11 +00001631 * Refer to borrowed references in key and value.
1632 * }
1633 *
1634 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +00001635 * mutates the dict. One exception: it is safe if the loop merely changes
1636 * the values associated with the keys (but doesn't insert new keys or
1637 * delete keys), via PyDict_SetItem().
1638 */
Guido van Rossum25831651993-05-19 14:50:45 +00001639int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001640PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001641{
Victor Stinner742da042016-09-07 17:40:12 -07001642 PyDictObject *mp = (PyDictObject*)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001643 Py_ssize_t i = dict_next(op, *ppos, pvalue);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 if (i < 0)
1645 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001646 mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 *ppos = i+1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 if (pkey)
Victor Stinner742da042016-09-07 17:40:12 -07001649 *pkey = DK_ENTRIES(mp->ma_keys)[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001651}
1652
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001653/* Internal version of PyDict_Next that returns a hash value in addition
1654 * to the key and value.
1655 */
Thomas Wouterscf297e42007-02-23 15:07:44 +00001656int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001657_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
1658 PyObject **pvalue, Py_hash_t *phash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001659{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001660 PyDictObject *mp;
Victor Stinner742da042016-09-07 17:40:12 -07001661 PyDictKeyEntry *ep0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001662 Py_ssize_t i = dict_next(op, *ppos, pvalue);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 if (i < 0)
1664 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001665 mp = (PyDictObject *)op;
Victor Stinner742da042016-09-07 17:40:12 -07001666 ep0 = DK_ENTRIES(mp->ma_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 *ppos = i+1;
Victor Stinner742da042016-09-07 17:40:12 -07001668 *phash = ep0[i].me_hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 if (pkey)
Victor Stinner742da042016-09-07 17:40:12 -07001670 *pkey = ep0[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 return 1;
Thomas Wouterscf297e42007-02-23 15:07:44 +00001672}
1673
Eric Snow96c6af92015-05-29 22:21:39 -06001674/* Internal version of dict.pop(). */
1675PyObject *
1676_PyDict_Pop(PyDictObject *mp, PyObject *key, PyObject *deflt)
1677{
1678 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001679 Py_ssize_t ix, hashpos;
Eric Snow96c6af92015-05-29 22:21:39 -06001680 PyObject *old_value, *old_key;
1681 PyDictKeyEntry *ep;
1682 PyObject **value_addr;
1683
1684 if (mp->ma_used == 0) {
1685 if (deflt) {
1686 Py_INCREF(deflt);
1687 return deflt;
1688 }
1689 _PyErr_SetKeyError(key);
1690 return NULL;
1691 }
1692 if (!PyUnicode_CheckExact(key) ||
1693 (hash = ((PyASCIIObject *) key)->hash) == -1) {
1694 hash = PyObject_Hash(key);
1695 if (hash == -1)
1696 return NULL;
1697 }
Victor Stinner742da042016-09-07 17:40:12 -07001698 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1699 if (ix == DKIX_ERROR)
Eric Snow96c6af92015-05-29 22:21:39 -06001700 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001701 if (ix == DKIX_EMPTY) {
Eric Snow96c6af92015-05-29 22:21:39 -06001702 if (deflt) {
1703 Py_INCREF(deflt);
1704 return deflt;
1705 }
1706 _PyErr_SetKeyError(key);
1707 return NULL;
1708 }
Victor Stinner742da042016-09-07 17:40:12 -07001709 old_value = *value_addr;
Eric Snow96c6af92015-05-29 22:21:39 -06001710 *value_addr = NULL;
1711 mp->ma_used--;
1712 if (!_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -07001713 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1714 ep = &DK_ENTRIES(mp->ma_keys)[ix];
Eric Snow96c6af92015-05-29 22:21:39 -06001715 ENSURE_ALLOWS_DELETIONS(mp);
1716 old_key = ep->me_key;
Victor Stinner742da042016-09-07 17:40:12 -07001717 ep->me_key = NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06001718 Py_DECREF(old_key);
1719 }
1720 return old_value;
1721}
1722
1723/* Internal version of dict.from_keys(). It is subclass-friendly. */
1724PyObject *
1725_PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
1726{
1727 PyObject *it; /* iter(iterable) */
1728 PyObject *key;
1729 PyObject *d;
1730 int status;
1731
1732 d = PyObject_CallObject(cls, NULL);
1733 if (d == NULL)
1734 return NULL;
1735
1736 if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
1737 if (PyDict_CheckExact(iterable)) {
1738 PyDictObject *mp = (PyDictObject *)d;
1739 PyObject *oldvalue;
1740 Py_ssize_t pos = 0;
1741 PyObject *key;
1742 Py_hash_t hash;
1743
Victor Stinner742da042016-09-07 17:40:12 -07001744 if (dictresize(mp, ESTIMATE_SIZE(Py_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001745 Py_DECREF(d);
1746 return NULL;
1747 }
1748
1749 while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
1750 if (insertdict(mp, key, hash, value)) {
1751 Py_DECREF(d);
1752 return NULL;
1753 }
1754 }
1755 return d;
1756 }
1757 if (PyAnySet_CheckExact(iterable)) {
1758 PyDictObject *mp = (PyDictObject *)d;
1759 Py_ssize_t pos = 0;
1760 PyObject *key;
1761 Py_hash_t hash;
1762
Victor Stinner742da042016-09-07 17:40:12 -07001763 if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001764 Py_DECREF(d);
1765 return NULL;
1766 }
1767
1768 while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
1769 if (insertdict(mp, key, hash, value)) {
1770 Py_DECREF(d);
1771 return NULL;
1772 }
1773 }
1774 return d;
1775 }
1776 }
1777
1778 it = PyObject_GetIter(iterable);
1779 if (it == NULL){
1780 Py_DECREF(d);
1781 return NULL;
1782 }
1783
1784 if (PyDict_CheckExact(d)) {
1785 while ((key = PyIter_Next(it)) != NULL) {
1786 status = PyDict_SetItem(d, key, value);
1787 Py_DECREF(key);
1788 if (status < 0)
1789 goto Fail;
1790 }
1791 } else {
1792 while ((key = PyIter_Next(it)) != NULL) {
1793 status = PyObject_SetItem(d, key, value);
1794 Py_DECREF(key);
1795 if (status < 0)
1796 goto Fail;
1797 }
1798 }
1799
1800 if (PyErr_Occurred())
1801 goto Fail;
1802 Py_DECREF(it);
1803 return d;
1804
1805Fail:
1806 Py_DECREF(it);
1807 Py_DECREF(d);
1808 return NULL;
1809}
1810
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001811/* Methods */
1812
1813static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001814dict_dealloc(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001815{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001816 PyObject **values = mp->ma_values;
1817 PyDictKeysObject *keys = mp->ma_keys;
1818 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 PyObject_GC_UnTrack(mp);
1820 Py_TRASHCAN_SAFE_BEGIN(mp)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001821 if (values != NULL) {
1822 if (values != empty_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001823 for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001824 Py_XDECREF(values[i]);
1825 }
1826 free_values(values);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001828 DK_DECREF(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 }
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02001830 else if (keys != NULL) {
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001831 assert(keys->dk_refcnt == 1);
1832 DK_DECREF(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001833 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
1835 free_list[numfree++] = mp;
1836 else
1837 Py_TYPE(mp)->tp_free((PyObject *)mp);
1838 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001839}
1840
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001841
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001842static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001843dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 Py_ssize_t i;
Victor Stinnerf91929b2013-11-19 13:07:38 +01001846 PyObject *key = NULL, *value = NULL;
1847 _PyUnicodeWriter writer;
1848 int first;
Guido van Rossum255443b1998-04-10 22:47:14 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 i = Py_ReprEnter((PyObject *)mp);
1851 if (i != 0) {
1852 return i > 0 ? PyUnicode_FromString("{...}") : NULL;
1853 }
Guido van Rossum255443b1998-04-10 22:47:14 +00001854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 if (mp->ma_used == 0) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01001856 Py_ReprLeave((PyObject *)mp);
1857 return PyUnicode_FromString("{}");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 }
Tim Petersa7259592001-06-16 05:11:17 +00001859
Victor Stinnerf91929b2013-11-19 13:07:38 +01001860 _PyUnicodeWriter_Init(&writer);
1861 writer.overallocate = 1;
1862 /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
1863 writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +00001864
Victor Stinnerf91929b2013-11-19 13:07:38 +01001865 if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
1866 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00001867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 /* Do repr() on each key+value pair, and insert ": " between them.
1869 Note that repr may mutate the dict. */
1870 i = 0;
Victor Stinnerf91929b2013-11-19 13:07:38 +01001871 first = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01001873 PyObject *s;
1874 int res;
1875
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001876 /* Prevent repr from deleting key or value during key format. */
1877 Py_INCREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 Py_INCREF(value);
Victor Stinnerf97dfd72013-07-18 01:00:45 +02001879
Victor Stinnerf91929b2013-11-19 13:07:38 +01001880 if (!first) {
1881 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
1882 goto error;
1883 }
1884 first = 0;
1885
1886 s = PyObject_Repr(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 if (s == NULL)
Victor Stinnerf91929b2013-11-19 13:07:38 +01001888 goto error;
1889 res = _PyUnicodeWriter_WriteStr(&writer, s);
1890 Py_DECREF(s);
1891 if (res < 0)
1892 goto error;
1893
1894 if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
1895 goto error;
1896
1897 s = PyObject_Repr(value);
1898 if (s == NULL)
1899 goto error;
1900 res = _PyUnicodeWriter_WriteStr(&writer, s);
1901 Py_DECREF(s);
1902 if (res < 0)
1903 goto error;
1904
1905 Py_CLEAR(key);
1906 Py_CLEAR(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 }
Tim Petersa7259592001-06-16 05:11:17 +00001908
Victor Stinnerf91929b2013-11-19 13:07:38 +01001909 writer.overallocate = 0;
1910 if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
1911 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 Py_ReprLeave((PyObject *)mp);
Victor Stinnerf91929b2013-11-19 13:07:38 +01001914
1915 return _PyUnicodeWriter_Finish(&writer);
1916
1917error:
1918 Py_ReprLeave((PyObject *)mp);
1919 _PyUnicodeWriter_Dealloc(&writer);
1920 Py_XDECREF(key);
1921 Py_XDECREF(value);
1922 return NULL;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001923}
1924
Martin v. Löwis18e16552006-02-15 17:27:45 +00001925static Py_ssize_t
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001926dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 return mp->ma_used;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001929}
1930
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001931static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001932dict_subscript(PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 PyObject *v;
Victor Stinner742da042016-09-07 17:40:12 -07001935 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001936 Py_hash_t hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001937 PyObject **value_addr;
1938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001940 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 hash = PyObject_Hash(key);
1942 if (hash == -1)
1943 return NULL;
1944 }
Victor Stinner742da042016-09-07 17:40:12 -07001945 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1946 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001948 if (ix == DKIX_EMPTY || *value_addr == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 if (!PyDict_CheckExact(mp)) {
1950 /* Look up __missing__ method if we're a subclass. */
1951 PyObject *missing, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05001952 _Py_IDENTIFIER(__missing__);
1953 missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 if (missing != NULL) {
1955 res = PyObject_CallFunctionObjArgs(missing,
1956 key, NULL);
1957 Py_DECREF(missing);
1958 return res;
1959 }
1960 else if (PyErr_Occurred())
1961 return NULL;
1962 }
Raymond Hettinger69492da2013-09-02 15:59:26 -07001963 _PyErr_SetKeyError(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 return NULL;
1965 }
Victor Stinner742da042016-09-07 17:40:12 -07001966 v = *value_addr;
1967 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001969}
1970
1971static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001972dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 if (w == NULL)
1975 return PyDict_DelItem((PyObject *)mp, v);
1976 else
1977 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001978}
1979
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001980static PyMappingMethods dict_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 (lenfunc)dict_length, /*mp_length*/
1982 (binaryfunc)dict_subscript, /*mp_subscript*/
1983 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001984};
1985
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001986static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001987dict_keys(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001988{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001989 PyObject *v;
1990 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001991 PyDictKeyEntry *ep;
1992 Py_ssize_t size, n, offset;
1993 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001994
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001995 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 n = mp->ma_used;
1997 v = PyList_New(n);
1998 if (v == NULL)
1999 return NULL;
2000 if (n != mp->ma_used) {
2001 /* Durnit. The allocations caused the dict to resize.
2002 * Just start over, this shouldn't normally happen.
2003 */
2004 Py_DECREF(v);
2005 goto again;
2006 }
Victor Stinner742da042016-09-07 17:40:12 -07002007 ep = DK_ENTRIES(mp->ma_keys);
2008 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002009 if (mp->ma_values) {
2010 value_ptr = mp->ma_values;
2011 offset = sizeof(PyObject *);
2012 }
2013 else {
2014 value_ptr = &ep[0].me_value;
2015 offset = sizeof(PyDictKeyEntry);
2016 }
2017 for (i = 0, j = 0; i < size; i++) {
2018 if (*value_ptr != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 PyObject *key = ep[i].me_key;
2020 Py_INCREF(key);
2021 PyList_SET_ITEM(v, j, key);
2022 j++;
2023 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002024 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 }
2026 assert(j == n);
2027 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002028}
2029
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002030static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002031dict_values(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002032{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002033 PyObject *v;
2034 Py_ssize_t i, j;
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002035 PyDictKeyEntry *ep;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002036 Py_ssize_t size, n, offset;
2037 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002038
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002039 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 n = mp->ma_used;
2041 v = PyList_New(n);
2042 if (v == NULL)
2043 return NULL;
2044 if (n != mp->ma_used) {
2045 /* Durnit. The allocations caused the dict to resize.
2046 * Just start over, this shouldn't normally happen.
2047 */
2048 Py_DECREF(v);
2049 goto again;
2050 }
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002051 ep = DK_ENTRIES(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002052 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002053 if (mp->ma_values) {
2054 value_ptr = mp->ma_values;
2055 offset = sizeof(PyObject *);
2056 }
2057 else {
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002058 value_ptr = &ep[0].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002059 offset = sizeof(PyDictKeyEntry);
2060 }
2061 for (i = 0, j = 0; i < size; i++) {
2062 PyObject *value = *value_ptr;
2063 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2064 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 Py_INCREF(value);
2066 PyList_SET_ITEM(v, j, value);
2067 j++;
2068 }
2069 }
2070 assert(j == n);
2071 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002072}
2073
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002074static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002075dict_items(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002076{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002077 PyObject *v;
2078 Py_ssize_t i, j, n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002079 Py_ssize_t size, offset;
2080 PyObject *item, *key;
2081 PyDictKeyEntry *ep;
2082 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 /* Preallocate the list of tuples, to avoid allocations during
2085 * the loop over the items, which could trigger GC, which
2086 * could resize the dict. :-(
2087 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002088 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 n = mp->ma_used;
2090 v = PyList_New(n);
2091 if (v == NULL)
2092 return NULL;
2093 for (i = 0; i < n; i++) {
2094 item = PyTuple_New(2);
2095 if (item == NULL) {
2096 Py_DECREF(v);
2097 return NULL;
2098 }
2099 PyList_SET_ITEM(v, i, item);
2100 }
2101 if (n != mp->ma_used) {
2102 /* Durnit. The allocations caused the dict to resize.
2103 * Just start over, this shouldn't normally happen.
2104 */
2105 Py_DECREF(v);
2106 goto again;
2107 }
2108 /* Nothing we do below makes any function calls. */
Victor Stinner742da042016-09-07 17:40:12 -07002109 ep = DK_ENTRIES(mp->ma_keys);
2110 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002111 if (mp->ma_values) {
2112 value_ptr = mp->ma_values;
2113 offset = sizeof(PyObject *);
2114 }
2115 else {
2116 value_ptr = &ep[0].me_value;
2117 offset = sizeof(PyDictKeyEntry);
2118 }
2119 for (i = 0, j = 0; i < size; i++) {
2120 PyObject *value = *value_ptr;
2121 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2122 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 key = ep[i].me_key;
2124 item = PyList_GET_ITEM(v, j);
2125 Py_INCREF(key);
2126 PyTuple_SET_ITEM(item, 0, key);
2127 Py_INCREF(value);
2128 PyTuple_SET_ITEM(item, 1, value);
2129 j++;
2130 }
2131 }
2132 assert(j == n);
2133 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002134}
2135
Larry Hastings5c661892014-01-24 06:17:25 -08002136/*[clinic input]
2137@classmethod
2138dict.fromkeys
Larry Hastings5c661892014-01-24 06:17:25 -08002139 iterable: object
2140 value: object=None
2141 /
2142
2143Returns a new dict with keys from iterable and values equal to value.
2144[clinic start generated code]*/
2145
Larry Hastings5c661892014-01-24 06:17:25 -08002146static PyObject *
2147dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002148/*[clinic end generated code: output=8fb98e4b10384999 input=b85a667f9bf4669d]*/
Larry Hastings5c661892014-01-24 06:17:25 -08002149{
Eric Snow96c6af92015-05-29 22:21:39 -06002150 return _PyDict_FromKeys((PyObject *)type, iterable, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002151}
2152
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002153static int
Victor Stinner742da042016-09-07 17:40:12 -07002154dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
2155 const char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 PyObject *arg = NULL;
2158 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
2161 result = -1;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 else if (arg != NULL) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02002164 _Py_IDENTIFIER(keys);
2165 if (_PyObject_HasAttrId(arg, &PyId_keys))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 result = PyDict_Merge(self, arg, 1);
2167 else
2168 result = PyDict_MergeFromSeq2(self, arg, 1);
2169 }
2170 if (result == 0 && kwds != NULL) {
2171 if (PyArg_ValidateKeywordArguments(kwds))
2172 result = PyDict_Merge(self, kwds, 1);
2173 else
2174 result = -1;
2175 }
2176 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002177}
2178
2179static PyObject *
2180dict_update(PyObject *self, PyObject *args, PyObject *kwds)
2181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 if (dict_update_common(self, args, kwds, "update") != -1)
2183 Py_RETURN_NONE;
2184 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002185}
2186
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002187/* Update unconditionally replaces existing items.
2188 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00002189 otherwise it leaves existing items unchanged.
2190
2191 PyDict_{Update,Merge} update/merge from a mapping object.
2192
Tim Petersf582b822001-12-11 18:51:08 +00002193 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00002194 producing iterable objects of length 2.
2195*/
2196
Tim Petersf582b822001-12-11 18:51:08 +00002197int
Tim Peters1fc240e2001-10-26 05:06:50 +00002198PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
2199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 PyObject *it; /* iter(seq2) */
2201 Py_ssize_t i; /* index into seq2 of current element */
2202 PyObject *item; /* seq2[i] */
2203 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 assert(d != NULL);
2206 assert(PyDict_Check(d));
2207 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 it = PyObject_GetIter(seq2);
2210 if (it == NULL)
2211 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 for (i = 0; ; ++i) {
2214 PyObject *key, *value;
2215 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 fast = NULL;
2218 item = PyIter_Next(it);
2219 if (item == NULL) {
2220 if (PyErr_Occurred())
2221 goto Fail;
2222 break;
2223 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 /* Convert item to sequence, and verify length 2. */
2226 fast = PySequence_Fast(item, "");
2227 if (fast == NULL) {
2228 if (PyErr_ExceptionMatches(PyExc_TypeError))
2229 PyErr_Format(PyExc_TypeError,
2230 "cannot convert dictionary update "
2231 "sequence element #%zd to a sequence",
2232 i);
2233 goto Fail;
2234 }
2235 n = PySequence_Fast_GET_SIZE(fast);
2236 if (n != 2) {
2237 PyErr_Format(PyExc_ValueError,
2238 "dictionary update sequence element #%zd "
2239 "has length %zd; 2 is required",
2240 i, n);
2241 goto Fail;
2242 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 /* Update/merge with this (key, value) pair. */
2245 key = PySequence_Fast_GET_ITEM(fast, 0);
2246 value = PySequence_Fast_GET_ITEM(fast, 1);
2247 if (override || PyDict_GetItem(d, key) == NULL) {
2248 int status = PyDict_SetItem(d, key, value);
2249 if (status < 0)
2250 goto Fail;
2251 }
2252 Py_DECREF(fast);
2253 Py_DECREF(item);
2254 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 i = 0;
2257 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00002258Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 Py_XDECREF(item);
2260 Py_XDECREF(fast);
2261 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002262Return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 Py_DECREF(it);
2264 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00002265}
2266
Tim Peters6d6c1a32001-08-02 04:15:00 +00002267int
2268PyDict_Update(PyObject *a, PyObject *b)
2269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 return PyDict_Merge(a, b, 1);
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002271}
2272
2273int
2274PyDict_Merge(PyObject *a, PyObject *b, int override)
2275{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002276 PyDictObject *mp, *other;
2277 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -07002278 PyDictKeyEntry *entry, *ep0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 /* We accept for the argument either a concrete dictionary object,
2281 * or an abstract "mapping" object. For the former, we can do
2282 * things quite efficiently. For the latter, we only require that
2283 * PyMapping_Keys() and PyObject_GetItem() be supported.
2284 */
2285 if (a == NULL || !PyDict_Check(a) || b == NULL) {
2286 PyErr_BadInternalCall();
2287 return -1;
2288 }
2289 mp = (PyDictObject*)a;
2290 if (PyDict_Check(b)) {
2291 other = (PyDictObject*)b;
2292 if (other == mp || other->ma_used == 0)
2293 /* a.update(a) or a.update({}); nothing to do */
2294 return 0;
2295 if (mp->ma_used == 0)
2296 /* Since the target dict is empty, PyDict_GetItem()
2297 * always returns NULL. Setting override to 1
2298 * skips the unnecessary test.
2299 */
2300 override = 1;
2301 /* Do one big resize at the start, rather than
2302 * incrementally resizing as we insert new items. Expect
2303 * that there will be no (or few) overlapping keys.
2304 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002305 if (mp->ma_keys->dk_usable * 3 < other->ma_used * 2)
2306 if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07002308 ep0 = DK_ENTRIES(other->ma_keys);
2309 for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002310 PyObject *key, *value;
2311 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002312 entry = &ep0[i];
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002313 key = entry->me_key;
2314 hash = entry->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002315 if (other->ma_values)
2316 value = other->ma_values[i];
2317 else
2318 value = entry->me_value;
2319
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002320 if (value != NULL) {
2321 int err = 0;
2322 Py_INCREF(key);
2323 Py_INCREF(value);
2324 if (override || PyDict_GetItem(a, key) == NULL)
2325 err = insertdict(mp, key, hash, value);
2326 Py_DECREF(value);
2327 Py_DECREF(key);
2328 if (err != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 return -1;
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002330
Victor Stinner742da042016-09-07 17:40:12 -07002331 if (n != other->ma_keys->dk_nentries) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002332 PyErr_SetString(PyExc_RuntimeError,
2333 "dict mutated during update");
2334 return -1;
2335 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 }
2337 }
2338 }
2339 else {
2340 /* Do it the generic, slower way */
2341 PyObject *keys = PyMapping_Keys(b);
2342 PyObject *iter;
2343 PyObject *key, *value;
2344 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 if (keys == NULL)
2347 /* Docstring says this is equivalent to E.keys() so
2348 * if E doesn't have a .keys() method we want
2349 * AttributeError to percolate up. Might as well
2350 * do the same for any other error.
2351 */
2352 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 iter = PyObject_GetIter(keys);
2355 Py_DECREF(keys);
2356 if (iter == NULL)
2357 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
2360 if (!override && PyDict_GetItem(a, key) != NULL) {
2361 Py_DECREF(key);
2362 continue;
2363 }
2364 value = PyObject_GetItem(b, key);
2365 if (value == NULL) {
2366 Py_DECREF(iter);
2367 Py_DECREF(key);
2368 return -1;
2369 }
2370 status = PyDict_SetItem(a, key, value);
2371 Py_DECREF(key);
2372 Py_DECREF(value);
2373 if (status < 0) {
2374 Py_DECREF(iter);
2375 return -1;
2376 }
2377 }
2378 Py_DECREF(iter);
2379 if (PyErr_Occurred())
2380 /* Iterator completed, via error */
2381 return -1;
2382 }
2383 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002384}
2385
2386static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002387dict_copy(PyDictObject *mp)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002390}
2391
2392PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002393PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 PyObject *copy;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002396 PyDictObject *mp;
2397 Py_ssize_t i, n;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 if (o == NULL || !PyDict_Check(o)) {
2400 PyErr_BadInternalCall();
2401 return NULL;
2402 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002403 mp = (PyDictObject *)o;
2404 if (_PyDict_HasSplitTable(mp)) {
2405 PyDictObject *split_copy;
Victor Stinner742da042016-09-07 17:40:12 -07002406 Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
2407 PyObject **newvalues;
2408 newvalues = new_values(size);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002409 if (newvalues == NULL)
2410 return PyErr_NoMemory();
2411 split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
2412 if (split_copy == NULL) {
2413 free_values(newvalues);
2414 return NULL;
2415 }
2416 split_copy->ma_values = newvalues;
2417 split_copy->ma_keys = mp->ma_keys;
2418 split_copy->ma_used = mp->ma_used;
2419 DK_INCREF(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002420 for (i = 0, n = size; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002421 PyObject *value = mp->ma_values[i];
2422 Py_XINCREF(value);
2423 split_copy->ma_values[i] = value;
2424 }
Benjamin Peterson7ce67e42012-04-24 10:32:57 -04002425 if (_PyObject_GC_IS_TRACKED(mp))
2426 _PyObject_GC_TRACK(split_copy);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002427 return (PyObject *)split_copy;
2428 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 copy = PyDict_New();
2430 if (copy == NULL)
2431 return NULL;
2432 if (PyDict_Merge(copy, o, 1) == 0)
2433 return copy;
2434 Py_DECREF(copy);
2435 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002436}
2437
Martin v. Löwis18e16552006-02-15 17:27:45 +00002438Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00002439PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00002440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 if (mp == NULL || !PyDict_Check(mp)) {
2442 PyErr_BadInternalCall();
2443 return -1;
2444 }
2445 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00002446}
2447
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002448PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002449PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 if (mp == NULL || !PyDict_Check(mp)) {
2452 PyErr_BadInternalCall();
2453 return NULL;
2454 }
2455 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002456}
2457
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002458PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002459PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 if (mp == NULL || !PyDict_Check(mp)) {
2462 PyErr_BadInternalCall();
2463 return NULL;
2464 }
2465 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002466}
2467
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002468PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002469PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 if (mp == NULL || !PyDict_Check(mp)) {
2472 PyErr_BadInternalCall();
2473 return NULL;
2474 }
2475 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002476}
2477
Tim Peterse63415e2001-05-08 04:38:29 +00002478/* Return 1 if dicts equal, 0 if not, -1 if error.
2479 * Gets out as soon as any difference is detected.
2480 * Uses only Py_EQ comparison.
2481 */
2482static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002483dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00002484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00002486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 if (a->ma_used != b->ma_used)
2488 /* can't be equal if # of entries differ */
2489 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Victor Stinner742da042016-09-07 17:40:12 -07002491 for (i = 0; i < a->ma_keys->dk_nentries; i++) {
2492 PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002493 PyObject *aval;
2494 if (a->ma_values)
2495 aval = a->ma_values[i];
2496 else
2497 aval = ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 if (aval != NULL) {
2499 int cmp;
2500 PyObject *bval;
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002501 PyObject **vaddr;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002502 PyObject *key = ep->me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 /* temporarily bump aval's refcount to ensure it stays
2504 alive until we're done with it */
2505 Py_INCREF(aval);
2506 /* ditto for key */
2507 Py_INCREF(key);
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002508 /* reuse the known hash value */
Victor Stinner742da042016-09-07 17:40:12 -07002509 if ((b->ma_keys->dk_lookup)(b, key, ep->me_hash, &vaddr, NULL) < 0)
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002510 bval = NULL;
2511 else
2512 bval = *vaddr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 Py_DECREF(key);
2514 if (bval == NULL) {
2515 Py_DECREF(aval);
2516 if (PyErr_Occurred())
2517 return -1;
2518 return 0;
2519 }
2520 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
2521 Py_DECREF(aval);
2522 if (cmp <= 0) /* error or not equal */
2523 return cmp;
2524 }
2525 }
2526 return 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002527}
Tim Peterse63415e2001-05-08 04:38:29 +00002528
2529static PyObject *
2530dict_richcompare(PyObject *v, PyObject *w, int op)
2531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 int cmp;
2533 PyObject *res;
Tim Peterse63415e2001-05-08 04:38:29 +00002534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 if (!PyDict_Check(v) || !PyDict_Check(w)) {
2536 res = Py_NotImplemented;
2537 }
2538 else if (op == Py_EQ || op == Py_NE) {
2539 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
2540 if (cmp < 0)
2541 return NULL;
2542 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
2543 }
2544 else
2545 res = Py_NotImplemented;
2546 Py_INCREF(res);
2547 return res;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002548}
Tim Peterse63415e2001-05-08 04:38:29 +00002549
Larry Hastings61272b72014-01-07 12:41:53 -08002550/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002551
2552@coexist
2553dict.__contains__
2554
2555 key: object
2556 /
2557
Meador Ingee02de8c2014-01-14 16:48:31 -06002558True if D has a key k, else False.
Larry Hastings61272b72014-01-07 12:41:53 -08002559[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002560
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002561static PyObject *
Larry Hastingsc2047262014-01-25 20:43:29 -08002562dict___contains__(PyDictObject *self, PyObject *key)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002563/*[clinic end generated code: output=a3d03db709ed6e6b input=b852b2a19b51ab24]*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002564{
Larry Hastingsc2047262014-01-25 20:43:29 -08002565 register PyDictObject *mp = self;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002566 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002567 Py_ssize_t ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002568 PyObject **value_addr;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002571 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 hash = PyObject_Hash(key);
2573 if (hash == -1)
2574 return NULL;
2575 }
Victor Stinner742da042016-09-07 17:40:12 -07002576 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2577 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002579 if (ix == DKIX_EMPTY || *value_addr == NULL)
2580 Py_RETURN_FALSE;
2581 Py_RETURN_TRUE;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002582}
2583
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002584static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002585dict_get(PyDictObject *mp, PyObject *args)
Barry Warsawc38c5da1997-10-06 17:49:20 +00002586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 PyObject *key;
2588 PyObject *failobj = Py_None;
2589 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002590 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002591 Py_ssize_t ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002592 PyObject **value_addr;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
2595 return NULL;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002598 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 hash = PyObject_Hash(key);
2600 if (hash == -1)
2601 return NULL;
2602 }
Victor Stinner742da042016-09-07 17:40:12 -07002603 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2604 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002606 if (ix == DKIX_EMPTY || *value_addr == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 val = failobj;
Victor Stinner742da042016-09-07 17:40:12 -07002608 else
2609 val = *value_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 Py_INCREF(val);
2611 return val;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002612}
2613
Benjamin Peterson00e98862013-03-07 22:16:29 -05002614PyObject *
2615PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
Guido van Rossum164452c2000-08-08 16:12:54 +00002616{
Benjamin Peterson00e98862013-03-07 22:16:29 -05002617 PyDictObject *mp = (PyDictObject *)d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002619 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002620 Py_ssize_t hashpos, ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002621 PyDictKeyEntry *ep;
2622 PyObject **value_addr;
Guido van Rossum164452c2000-08-08 16:12:54 +00002623
Benjamin Peterson00e98862013-03-07 22:16:29 -05002624 if (!PyDict_Check(d)) {
2625 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 return NULL;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002627 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002629 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 hash = PyObject_Hash(key);
2631 if (hash == -1)
2632 return NULL;
2633 }
Victor Stinner742da042016-09-07 17:40:12 -07002634 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
2635 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002637 if (ix == DKIX_EMPTY || *value_addr == NULL) {
2638 val = defaultobj;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002639 if (mp->ma_keys->dk_usable <= 0) {
2640 /* Need to resize. */
2641 if (insertion_resize(mp) < 0)
2642 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002643 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002644 }
Victor Stinner742da042016-09-07 17:40:12 -07002645 ix = mp->ma_keys->dk_nentries;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002646 Py_INCREF(defaultobj);
Benjamin Petersonb1efa532013-03-04 09:47:50 -05002647 Py_INCREF(key);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002648 MAINTAIN_TRACKING(mp, key, defaultobj);
Victor Stinner742da042016-09-07 17:40:12 -07002649 dk_set_index(mp->ma_keys, hashpos, ix);
2650 ep = &DK_ENTRIES(mp->ma_keys)[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002651 ep->me_key = key;
2652 ep->me_hash = hash;
Victor Stinner742da042016-09-07 17:40:12 -07002653 if (mp->ma_values) {
2654 mp->ma_values[ix] = val;
2655 }
2656 else {
2657 ep->me_value = val;
2658 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002659 mp->ma_keys->dk_usable--;
Victor Stinner742da042016-09-07 17:40:12 -07002660 mp->ma_keys->dk_nentries++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002661 mp->ma_used++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 }
Victor Stinner742da042016-09-07 17:40:12 -07002663 else
2664 val = *value_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 return val;
Guido van Rossum164452c2000-08-08 16:12:54 +00002666}
2667
Benjamin Peterson00e98862013-03-07 22:16:29 -05002668static PyObject *
2669dict_setdefault(PyDictObject *mp, PyObject *args)
2670{
2671 PyObject *key, *val;
2672 PyObject *defaultobj = Py_None;
2673
2674 if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &defaultobj))
2675 return NULL;
2676
Benjamin Peterson55898502013-03-08 08:36:49 -05002677 val = PyDict_SetDefault((PyObject *)mp, key, defaultobj);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002678 Py_XINCREF(val);
2679 return val;
2680}
Guido van Rossum164452c2000-08-08 16:12:54 +00002681
2682static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002683dict_clear(PyDictObject *mp)
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 PyDict_Clear((PyObject *)mp);
2686 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002687}
2688
Guido van Rossumba6ab842000-12-12 22:02:18 +00002689static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002690dict_pop(PyDictObject *mp, PyObject *args)
Guido van Rossume027d982002-04-12 15:11:59 +00002691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 PyObject *key, *deflt = NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00002693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
2695 return NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06002696
2697 return _PyDict_Pop(mp, key, deflt);
Guido van Rossume027d982002-04-12 15:11:59 +00002698}
2699
2700static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002701dict_popitem(PyDictObject *mp)
Guido van Rossumba6ab842000-12-12 22:02:18 +00002702{
Victor Stinner742da042016-09-07 17:40:12 -07002703 Py_ssize_t i, j;
2704 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 PyObject *res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 /* Allocate the result tuple before checking the size. Believe it
2708 * or not, this allocation could trigger a garbage collection which
2709 * could empty the dict, so if we checked the size first and that
2710 * happened, the result would be an infinite loop (searching for an
2711 * entry that no longer exists). Note that the usual popitem()
2712 * idiom is "while d: k, v = d.popitem()". so needing to throw the
2713 * tuple away if the dict *is* empty isn't a significant
2714 * inefficiency -- possible, but unlikely in practice.
2715 */
2716 res = PyTuple_New(2);
2717 if (res == NULL)
2718 return NULL;
2719 if (mp->ma_used == 0) {
2720 Py_DECREF(res);
2721 PyErr_SetString(PyExc_KeyError,
2722 "popitem(): dictionary is empty");
2723 return NULL;
2724 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002725 /* Convert split table to combined table */
2726 if (mp->ma_keys->dk_lookup == lookdict_split) {
2727 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
2728 Py_DECREF(res);
2729 return NULL;
2730 }
2731 }
2732 ENSURE_ALLOWS_DELETIONS(mp);
Victor Stinner742da042016-09-07 17:40:12 -07002733
2734 /* Pop last item */
2735 ep0 = DK_ENTRIES(mp->ma_keys);
2736 i = mp->ma_keys->dk_nentries - 1;
2737 while (i >= 0 && ep0[i].me_value == NULL) {
2738 i--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 }
Victor Stinner742da042016-09-07 17:40:12 -07002740 assert(i >= 0);
2741
2742 ep = &ep0[i];
2743 j = lookdict_index(mp->ma_keys, ep->me_hash, i);
2744 assert(j >= 0);
2745 assert(dk_get_index(mp->ma_keys, j) == i);
2746 dk_set_index(mp->ma_keys, j, DKIX_DUMMY);
2747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 PyTuple_SET_ITEM(res, 0, ep->me_key);
2749 PyTuple_SET_ITEM(res, 1, ep->me_value);
Victor Stinner742da042016-09-07 17:40:12 -07002750 ep->me_key = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 ep->me_value = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002752 /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
2753 mp->ma_keys->dk_nentries = i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 mp->ma_used--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 return res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002756}
2757
Jeremy Hylton8caad492000-06-23 14:18:11 +00002758static int
2759dict_traverse(PyObject *op, visitproc visit, void *arg)
2760{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002761 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson55f44522016-09-05 12:12:59 -07002762 PyDictKeysObject *keys = mp->ma_keys;
Victor Stinner742da042016-09-07 17:40:12 -07002763 PyDictKeyEntry *entries = DK_ENTRIES(mp->ma_keys);
2764 Py_ssize_t i, n = keys->dk_nentries;
2765
Benjamin Peterson55f44522016-09-05 12:12:59 -07002766 if (keys->dk_lookup == lookdict) {
2767 for (i = 0; i < n; i++) {
2768 if (entries[i].me_value != NULL) {
2769 Py_VISIT(entries[i].me_value);
2770 Py_VISIT(entries[i].me_key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002771 }
2772 }
Victor Stinner742da042016-09-07 17:40:12 -07002773 }
2774 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002775 if (mp->ma_values != NULL) {
Benjamin Peterson55f44522016-09-05 12:12:59 -07002776 for (i = 0; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002777 Py_VISIT(mp->ma_values[i]);
2778 }
2779 }
2780 else {
Benjamin Peterson55f44522016-09-05 12:12:59 -07002781 for (i = 0; i < n; i++) {
2782 Py_VISIT(entries[i].me_value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002783 }
2784 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 }
2786 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002787}
2788
2789static int
2790dict_tp_clear(PyObject *op)
2791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 PyDict_Clear(op);
2793 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002794}
2795
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002796static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00002797
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002798Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06002799_PyDict_SizeOf(PyDictObject *mp)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002800{
Victor Stinner742da042016-09-07 17:40:12 -07002801 Py_ssize_t size, usable, res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002802
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002803 size = DK_SIZE(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002804 usable = USABLE_FRACTION(size);
2805
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002806 res = _PyObject_SIZE(Py_TYPE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002807 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07002808 res += usable * sizeof(PyObject*);
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002809 /* If the dictionary is split, the keys portion is accounted-for
2810 in the type object. */
2811 if (mp->ma_keys->dk_refcnt == 1)
Victor Stinner98ee9d52016-09-08 09:33:56 -07002812 res += (sizeof(PyDictKeysObject)
2813 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
2814 + DK_IXSIZE(mp->ma_keys) * size
2815 + sizeof(PyDictKeyEntry) * usable);
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002816 return res;
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002817}
2818
2819Py_ssize_t
2820_PyDict_KeysSize(PyDictKeysObject *keys)
2821{
Victor Stinner98ee9d52016-09-08 09:33:56 -07002822 return (sizeof(PyDictKeysObject)
2823 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
2824 + DK_IXSIZE(keys) * DK_SIZE(keys)
2825 + USABLE_FRACTION(DK_SIZE(keys)) * sizeof(PyDictKeyEntry));
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002826}
2827
doko@ubuntu.com17210f52016-01-14 14:04:59 +01002828static PyObject *
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002829dict_sizeof(PyDictObject *mp)
2830{
2831 return PyLong_FromSsize_t(_PyDict_SizeOf(mp));
2832}
2833
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002834PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
2835
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002836PyDoc_STRVAR(sizeof__doc__,
2837"D.__sizeof__() -> size of D in memory, in bytes");
2838
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002839PyDoc_STRVAR(get__doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00002840"D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002841
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002842PyDoc_STRVAR(setdefault_doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00002843"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 +00002844
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002845PyDoc_STRVAR(pop__doc__,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002846"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00002847If key is not found, d is returned if given, otherwise KeyError is raised");
Guido van Rossume027d982002-04-12 15:11:59 +00002848
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002849PyDoc_STRVAR(popitem__doc__,
Tim Petersf7f88b12000-12-13 23:18:45 +00002850"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000028512-tuple; but raise KeyError if D is empty.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002852
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002853PyDoc_STRVAR(update__doc__,
Brett Cannonf2754162013-05-11 14:46:48 -04002854"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n\
2855If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]\n\
2856If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n\
2857In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00002858
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002859PyDoc_STRVAR(clear__doc__,
2860"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002861
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002862PyDoc_STRVAR(copy__doc__,
2863"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00002864
Guido van Rossumb90c8482007-02-10 01:11:45 +00002865/* Forward */
2866static PyObject *dictkeys_new(PyObject *);
2867static PyObject *dictitems_new(PyObject *);
2868static PyObject *dictvalues_new(PyObject *);
2869
Guido van Rossum45c85d12007-07-27 16:31:40 +00002870PyDoc_STRVAR(keys__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 "D.keys() -> a set-like object providing a view on D's keys");
Guido van Rossum45c85d12007-07-27 16:31:40 +00002872PyDoc_STRVAR(items__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 "D.items() -> a set-like object providing a view on D's items");
Guido van Rossum45c85d12007-07-27 16:31:40 +00002874PyDoc_STRVAR(values__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 "D.values() -> an object providing a view on D's values");
Guido van Rossumb90c8482007-02-10 01:11:45 +00002876
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002877static PyMethodDef mapp_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -07002878 DICT___CONTAINS___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
2880 getitem__doc__},
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002881 {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 sizeof__doc__},
2883 {"get", (PyCFunction)dict_get, METH_VARARGS,
2884 get__doc__},
2885 {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS,
2886 setdefault_doc__},
2887 {"pop", (PyCFunction)dict_pop, METH_VARARGS,
2888 pop__doc__},
2889 {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
2890 popitem__doc__},
2891 {"keys", (PyCFunction)dictkeys_new, METH_NOARGS,
2892 keys__doc__},
2893 {"items", (PyCFunction)dictitems_new, METH_NOARGS,
2894 items__doc__},
2895 {"values", (PyCFunction)dictvalues_new, METH_NOARGS,
2896 values__doc__},
2897 {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
2898 update__doc__},
Larry Hastings5c661892014-01-24 06:17:25 -08002899 DICT_FROMKEYS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
2901 clear__doc__},
2902 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
2903 copy__doc__},
2904 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002905};
2906
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002907/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00002908int
2909PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002910{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002911 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002912 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002914 PyObject **value_addr;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002917 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 hash = PyObject_Hash(key);
2919 if (hash == -1)
2920 return -1;
2921 }
Victor Stinner742da042016-09-07 17:40:12 -07002922 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2923 if (ix == DKIX_ERROR)
2924 return -1;
2925 return (ix != DKIX_EMPTY && *value_addr != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002926}
2927
Thomas Wouterscf297e42007-02-23 15:07:44 +00002928/* Internal version of PyDict_Contains used when the hash value is already known */
2929int
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002930_PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00002931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002933 PyObject **value_addr;
Victor Stinner742da042016-09-07 17:40:12 -07002934 Py_ssize_t ix;
Thomas Wouterscf297e42007-02-23 15:07:44 +00002935
Victor Stinner742da042016-09-07 17:40:12 -07002936 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2937 if (ix == DKIX_ERROR)
2938 return -1;
2939 return (ix != DKIX_EMPTY && *value_addr != NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00002940}
2941
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002942/* Hack to implement "key in dict" */
2943static PySequenceMethods dict_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944 0, /* sq_length */
2945 0, /* sq_concat */
2946 0, /* sq_repeat */
2947 0, /* sq_item */
2948 0, /* sq_slice */
2949 0, /* sq_ass_item */
2950 0, /* sq_ass_slice */
2951 PyDict_Contains, /* sq_contains */
2952 0, /* sq_inplace_concat */
2953 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002954};
2955
Guido van Rossum09e563a2001-05-01 12:10:21 +00002956static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002957dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 PyObject *self;
Victor Stinnera9f61a52013-07-16 22:17:26 +02002960 PyDictObject *d;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 assert(type != NULL && type->tp_alloc != NULL);
2963 self = type->tp_alloc(type, 0);
Victor Stinnera9f61a52013-07-16 22:17:26 +02002964 if (self == NULL)
2965 return NULL;
Victor Stinnera9f61a52013-07-16 22:17:26 +02002966 d = (PyDictObject *)self;
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02002967
Victor Stinnera9f61a52013-07-16 22:17:26 +02002968 /* The object has been implicitly tracked by tp_alloc */
2969 if (type == &PyDict_Type)
2970 _PyObject_GC_UNTRACK(d);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02002971
2972 d->ma_used = 0;
Victor Stinner742da042016-09-07 17:40:12 -07002973 d->ma_keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02002974 if (d->ma_keys == NULL) {
2975 Py_DECREF(self);
2976 return NULL;
2977 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 return self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002979}
2980
Tim Peters25786c02001-09-02 08:22:48 +00002981static int
2982dict_init(PyObject *self, PyObject *args, PyObject *kwds)
2983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00002985}
2986
Tim Peters6d6c1a32001-08-02 04:15:00 +00002987static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002988dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00002989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00002991}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002992
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002993PyDoc_STRVAR(dictionary_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00002994"dict() -> new empty dictionary\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00002995"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00002996" (key, value) pairs\n"
2997"dict(iterable) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00002998" d = {}\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00002999" for k, v in iterable:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00003000" d[k] = v\n"
3001"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
3002" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00003003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003004PyTypeObject PyDict_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3006 "dict",
3007 sizeof(PyDictObject),
3008 0,
3009 (destructor)dict_dealloc, /* tp_dealloc */
3010 0, /* tp_print */
3011 0, /* tp_getattr */
3012 0, /* tp_setattr */
3013 0, /* tp_reserved */
3014 (reprfunc)dict_repr, /* tp_repr */
3015 0, /* tp_as_number */
3016 &dict_as_sequence, /* tp_as_sequence */
3017 &dict_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003018 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 0, /* tp_call */
3020 0, /* tp_str */
3021 PyObject_GenericGetAttr, /* tp_getattro */
3022 0, /* tp_setattro */
3023 0, /* tp_as_buffer */
3024 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3025 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
3026 dictionary_doc, /* tp_doc */
3027 dict_traverse, /* tp_traverse */
3028 dict_tp_clear, /* tp_clear */
3029 dict_richcompare, /* tp_richcompare */
3030 0, /* tp_weaklistoffset */
3031 (getiterfunc)dict_iter, /* tp_iter */
3032 0, /* tp_iternext */
3033 mapp_methods, /* tp_methods */
3034 0, /* tp_members */
3035 0, /* tp_getset */
3036 0, /* tp_base */
3037 0, /* tp_dict */
3038 0, /* tp_descr_get */
3039 0, /* tp_descr_set */
3040 0, /* tp_dictoffset */
3041 dict_init, /* tp_init */
3042 PyType_GenericAlloc, /* tp_alloc */
3043 dict_new, /* tp_new */
3044 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003045};
3046
Victor Stinner3c1e4812012-03-26 22:10:51 +02003047PyObject *
3048_PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
3049{
3050 PyObject *kv;
3051 kv = _PyUnicode_FromId(key); /* borrowed */
Victor Stinner5b3b1002013-07-22 23:50:57 +02003052 if (kv == NULL) {
3053 PyErr_Clear();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003054 return NULL;
Victor Stinner5b3b1002013-07-22 23:50:57 +02003055 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003056 return PyDict_GetItem(dp, kv);
3057}
3058
Guido van Rossum3cca2451997-05-16 14:23:33 +00003059/* For backward compatibility with old dictionary interface */
3060
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003061PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003062PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 PyObject *kv, *rv;
3065 kv = PyUnicode_FromString(key);
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003066 if (kv == NULL) {
3067 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 return NULL;
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003069 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 rv = PyDict_GetItem(v, kv);
3071 Py_DECREF(kv);
3072 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003073}
3074
3075int
Victor Stinner3c1e4812012-03-26 22:10:51 +02003076_PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
3077{
3078 PyObject *kv;
3079 kv = _PyUnicode_FromId(key); /* borrowed */
3080 if (kv == NULL)
3081 return -1;
3082 return PyDict_SetItem(v, kv, item);
3083}
3084
3085int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003086PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 PyObject *kv;
3089 int err;
3090 kv = PyUnicode_FromString(key);
3091 if (kv == NULL)
3092 return -1;
3093 PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
3094 err = PyDict_SetItem(v, kv, item);
3095 Py_DECREF(kv);
3096 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003097}
3098
3099int
Victor Stinner5fd2e5a2013-11-06 18:58:22 +01003100_PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
3101{
3102 PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
3103 if (kv == NULL)
3104 return -1;
3105 return PyDict_DelItem(v, kv);
3106}
3107
3108int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003109PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 PyObject *kv;
3112 int err;
3113 kv = PyUnicode_FromString(key);
3114 if (kv == NULL)
3115 return -1;
3116 err = PyDict_DelItem(v, kv);
3117 Py_DECREF(kv);
3118 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003119}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003120
Raymond Hettinger019a1482004-03-18 02:41:19 +00003121/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003122
3123typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 PyObject_HEAD
3125 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
3126 Py_ssize_t di_used;
3127 Py_ssize_t di_pos;
3128 PyObject* di_result; /* reusable result tuple for iteritems */
3129 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003130} dictiterobject;
3131
3132static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003133dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 dictiterobject *di;
3136 di = PyObject_GC_New(dictiterobject, itertype);
3137 if (di == NULL)
3138 return NULL;
3139 Py_INCREF(dict);
3140 di->di_dict = dict;
3141 di->di_used = dict->ma_used;
3142 di->di_pos = 0;
3143 di->len = dict->ma_used;
3144 if (itertype == &PyDictIterItem_Type) {
3145 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
3146 if (di->di_result == NULL) {
3147 Py_DECREF(di);
3148 return NULL;
3149 }
3150 }
3151 else
3152 di->di_result = NULL;
3153 _PyObject_GC_TRACK(di);
3154 return (PyObject *)di;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003155}
3156
3157static void
3158dictiter_dealloc(dictiterobject *di)
3159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 Py_XDECREF(di->di_dict);
3161 Py_XDECREF(di->di_result);
3162 PyObject_GC_Del(di);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003163}
3164
3165static int
3166dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
3167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 Py_VISIT(di->di_dict);
3169 Py_VISIT(di->di_result);
3170 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003171}
3172
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003173static PyObject *
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003174dictiter_len(dictiterobject *di)
3175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 Py_ssize_t len = 0;
3177 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
3178 len = di->len;
3179 return PyLong_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003180}
3181
Guido van Rossumb90c8482007-02-10 01:11:45 +00003182PyDoc_STRVAR(length_hint_doc,
3183 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003184
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003185static PyObject *
3186dictiter_reduce(dictiterobject *di);
3187
3188PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3189
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003190static PyMethodDef dictiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS,
3192 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003193 {"__reduce__", (PyCFunction)dictiter_reduce, METH_NOARGS,
3194 reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003196};
3197
Raymond Hettinger019a1482004-03-18 02:41:19 +00003198static PyObject *dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00003199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 PyObject *key;
Victor Stinner742da042016-09-07 17:40:12 -07003201 Py_ssize_t i, n, offset;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003202 PyDictKeysObject *k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003204 PyObject **value_ptr;
Guido van Rossum213c7a62001-04-23 14:08:49 +00003205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 if (d == NULL)
3207 return NULL;
3208 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00003209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 if (di->di_used != d->ma_used) {
3211 PyErr_SetString(PyExc_RuntimeError,
3212 "dictionary changed size during iteration");
3213 di->di_used = -1; /* Make this state sticky */
3214 return NULL;
3215 }
Guido van Rossum2147df72002-07-16 20:30:22 +00003216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 i = di->di_pos;
3218 if (i < 0)
3219 goto fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003220 k = d->ma_keys;
3221 if (d->ma_values) {
3222 value_ptr = &d->ma_values[i];
3223 offset = sizeof(PyObject *);
3224 }
3225 else {
Victor Stinner742da042016-09-07 17:40:12 -07003226 value_ptr = &DK_ENTRIES(k)[i].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003227 offset = sizeof(PyDictKeyEntry);
3228 }
Victor Stinner742da042016-09-07 17:40:12 -07003229 n = k->dk_nentries - 1;
3230 while (i <= n && *value_ptr == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003231 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 i++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003233 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 di->di_pos = i+1;
Victor Stinner742da042016-09-07 17:40:12 -07003235 if (i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003236 goto fail;
3237 di->len--;
Victor Stinner742da042016-09-07 17:40:12 -07003238 key = DK_ENTRIES(k)[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 Py_INCREF(key);
3240 return key;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003241
3242fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003244 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003246}
3247
Raymond Hettinger019a1482004-03-18 02:41:19 +00003248PyTypeObject PyDictIterKey_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003249 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3250 "dict_keyiterator", /* tp_name */
3251 sizeof(dictiterobject), /* tp_basicsize */
3252 0, /* tp_itemsize */
3253 /* methods */
3254 (destructor)dictiter_dealloc, /* tp_dealloc */
3255 0, /* tp_print */
3256 0, /* tp_getattr */
3257 0, /* tp_setattr */
3258 0, /* tp_reserved */
3259 0, /* tp_repr */
3260 0, /* tp_as_number */
3261 0, /* tp_as_sequence */
3262 0, /* tp_as_mapping */
3263 0, /* tp_hash */
3264 0, /* tp_call */
3265 0, /* tp_str */
3266 PyObject_GenericGetAttr, /* tp_getattro */
3267 0, /* tp_setattro */
3268 0, /* tp_as_buffer */
3269 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3270 0, /* tp_doc */
3271 (traverseproc)dictiter_traverse, /* tp_traverse */
3272 0, /* tp_clear */
3273 0, /* tp_richcompare */
3274 0, /* tp_weaklistoffset */
3275 PyObject_SelfIter, /* tp_iter */
3276 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
3277 dictiter_methods, /* tp_methods */
3278 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003279};
3280
3281static PyObject *dictiter_iternextvalue(dictiterobject *di)
3282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -07003284 Py_ssize_t i, n, offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003286 PyObject **value_ptr;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 if (d == NULL)
3289 return NULL;
3290 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 if (di->di_used != d->ma_used) {
3293 PyErr_SetString(PyExc_RuntimeError,
3294 "dictionary changed size during iteration");
3295 di->di_used = -1; /* Make this state sticky */
3296 return NULL;
3297 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 i = di->di_pos;
Victor Stinner742da042016-09-07 17:40:12 -07003300 n = d->ma_keys->dk_nentries - 1;
3301 if (i < 0 || i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 goto fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003303 if (d->ma_values) {
3304 value_ptr = &d->ma_values[i];
3305 offset = sizeof(PyObject *);
3306 }
3307 else {
Victor Stinner742da042016-09-07 17:40:12 -07003308 value_ptr = &DK_ENTRIES(d->ma_keys)[i].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003309 offset = sizeof(PyDictKeyEntry);
3310 }
Victor Stinner742da042016-09-07 17:40:12 -07003311 while (i <= n && *value_ptr == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003312 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 i++;
Victor Stinner742da042016-09-07 17:40:12 -07003314 if (i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 goto fail;
3316 }
3317 di->di_pos = i+1;
3318 di->len--;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003319 value = *value_ptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 Py_INCREF(value);
3321 return value;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003322
3323fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003325 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003327}
3328
3329PyTypeObject PyDictIterValue_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3331 "dict_valueiterator", /* tp_name */
3332 sizeof(dictiterobject), /* tp_basicsize */
3333 0, /* tp_itemsize */
3334 /* methods */
3335 (destructor)dictiter_dealloc, /* tp_dealloc */
3336 0, /* tp_print */
3337 0, /* tp_getattr */
3338 0, /* tp_setattr */
3339 0, /* tp_reserved */
3340 0, /* tp_repr */
3341 0, /* tp_as_number */
3342 0, /* tp_as_sequence */
3343 0, /* tp_as_mapping */
3344 0, /* tp_hash */
3345 0, /* tp_call */
3346 0, /* tp_str */
3347 PyObject_GenericGetAttr, /* tp_getattro */
3348 0, /* tp_setattro */
3349 0, /* tp_as_buffer */
3350 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3351 0, /* tp_doc */
3352 (traverseproc)dictiter_traverse, /* tp_traverse */
3353 0, /* tp_clear */
3354 0, /* tp_richcompare */
3355 0, /* tp_weaklistoffset */
3356 PyObject_SelfIter, /* tp_iter */
3357 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
3358 dictiter_methods, /* tp_methods */
3359 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003360};
3361
3362static PyObject *dictiter_iternextitem(dictiterobject *di)
3363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 PyObject *key, *value, *result = di->di_result;
Victor Stinner742da042016-09-07 17:40:12 -07003365 Py_ssize_t i, n, offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003367 PyObject **value_ptr;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 if (d == NULL)
3370 return NULL;
3371 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 if (di->di_used != d->ma_used) {
3374 PyErr_SetString(PyExc_RuntimeError,
3375 "dictionary changed size during iteration");
3376 di->di_used = -1; /* Make this state sticky */
3377 return NULL;
3378 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 i = di->di_pos;
3381 if (i < 0)
3382 goto fail;
Victor Stinner742da042016-09-07 17:40:12 -07003383 n = d->ma_keys->dk_nentries - 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003384 if (d->ma_values) {
3385 value_ptr = &d->ma_values[i];
3386 offset = sizeof(PyObject *);
3387 }
3388 else {
Victor Stinner742da042016-09-07 17:40:12 -07003389 value_ptr = &DK_ENTRIES(d->ma_keys)[i].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003390 offset = sizeof(PyDictKeyEntry);
3391 }
Victor Stinner742da042016-09-07 17:40:12 -07003392 while (i <= n && *value_ptr == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003393 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 i++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003395 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 di->di_pos = i+1;
Victor Stinner742da042016-09-07 17:40:12 -07003397 if (i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 goto fail;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003400 if (result->ob_refcnt == 1) {
3401 Py_INCREF(result);
3402 Py_DECREF(PyTuple_GET_ITEM(result, 0));
3403 Py_DECREF(PyTuple_GET_ITEM(result, 1));
3404 } else {
3405 result = PyTuple_New(2);
3406 if (result == NULL)
3407 return NULL;
3408 }
3409 di->len--;
Victor Stinner742da042016-09-07 17:40:12 -07003410 key = DK_ENTRIES(d->ma_keys)[i].me_key;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003411 value = *value_ptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003412 Py_INCREF(key);
3413 Py_INCREF(value);
Eric Snow96c6af92015-05-29 22:21:39 -06003414 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3415 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003417
3418fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003420 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003422}
3423
3424PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3426 "dict_itemiterator", /* tp_name */
3427 sizeof(dictiterobject), /* tp_basicsize */
3428 0, /* tp_itemsize */
3429 /* methods */
3430 (destructor)dictiter_dealloc, /* tp_dealloc */
3431 0, /* tp_print */
3432 0, /* tp_getattr */
3433 0, /* tp_setattr */
3434 0, /* tp_reserved */
3435 0, /* tp_repr */
3436 0, /* tp_as_number */
3437 0, /* tp_as_sequence */
3438 0, /* tp_as_mapping */
3439 0, /* tp_hash */
3440 0, /* tp_call */
3441 0, /* tp_str */
3442 PyObject_GenericGetAttr, /* tp_getattro */
3443 0, /* tp_setattro */
3444 0, /* tp_as_buffer */
3445 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3446 0, /* tp_doc */
3447 (traverseproc)dictiter_traverse, /* tp_traverse */
3448 0, /* tp_clear */
3449 0, /* tp_richcompare */
3450 0, /* tp_weaklistoffset */
3451 PyObject_SelfIter, /* tp_iter */
3452 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
3453 dictiter_methods, /* tp_methods */
3454 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003455};
Guido van Rossumb90c8482007-02-10 01:11:45 +00003456
3457
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003458static PyObject *
3459dictiter_reduce(dictiterobject *di)
3460{
3461 PyObject *list;
3462 dictiterobject tmp;
3463
3464 list = PyList_New(0);
3465 if (!list)
3466 return NULL;
3467
3468 /* copy the itertor state */
3469 tmp = *di;
3470 Py_XINCREF(tmp.di_dict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003471
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003472 /* iterate the temporary into a list */
3473 for(;;) {
3474 PyObject *element = 0;
3475 if (Py_TYPE(di) == &PyDictIterItem_Type)
3476 element = dictiter_iternextitem(&tmp);
3477 else if (Py_TYPE(di) == &PyDictIterKey_Type)
3478 element = dictiter_iternextkey(&tmp);
3479 else if (Py_TYPE(di) == &PyDictIterValue_Type)
3480 element = dictiter_iternextvalue(&tmp);
3481 else
3482 assert(0);
3483 if (element) {
3484 if (PyList_Append(list, element)) {
3485 Py_DECREF(element);
3486 Py_DECREF(list);
3487 Py_XDECREF(tmp.di_dict);
3488 return NULL;
3489 }
3490 Py_DECREF(element);
3491 } else
3492 break;
3493 }
3494 Py_XDECREF(tmp.di_dict);
3495 /* check for error */
3496 if (tmp.di_dict != NULL) {
3497 /* we have an error */
3498 Py_DECREF(list);
3499 return NULL;
3500 }
Antoine Pitroua7013882012-04-05 00:04:20 +02003501 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003502}
3503
Guido van Rossum3ac67412007-02-10 18:55:06 +00003504/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003505/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00003506/***********************************************/
3507
Guido van Rossumb90c8482007-02-10 01:11:45 +00003508/* The instance lay-out is the same for all three; but the type differs. */
3509
Guido van Rossumb90c8482007-02-10 01:11:45 +00003510static void
Eric Snow96c6af92015-05-29 22:21:39 -06003511dictview_dealloc(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 Py_XDECREF(dv->dv_dict);
3514 PyObject_GC_Del(dv);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003515}
3516
3517static int
Eric Snow96c6af92015-05-29 22:21:39 -06003518dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 Py_VISIT(dv->dv_dict);
3521 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003522}
3523
Guido van Rossum83825ac2007-02-10 04:54:19 +00003524static Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003525dictview_len(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 Py_ssize_t len = 0;
3528 if (dv->dv_dict != NULL)
3529 len = dv->dv_dict->ma_used;
3530 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003531}
3532
Eric Snow96c6af92015-05-29 22:21:39 -06003533PyObject *
3534_PyDictView_New(PyObject *dict, PyTypeObject *type)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003535{
Eric Snow96c6af92015-05-29 22:21:39 -06003536 _PyDictViewObject *dv;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 if (dict == NULL) {
3538 PyErr_BadInternalCall();
3539 return NULL;
3540 }
3541 if (!PyDict_Check(dict)) {
3542 /* XXX Get rid of this restriction later */
3543 PyErr_Format(PyExc_TypeError,
3544 "%s() requires a dict argument, not '%s'",
3545 type->tp_name, dict->ob_type->tp_name);
3546 return NULL;
3547 }
Eric Snow96c6af92015-05-29 22:21:39 -06003548 dv = PyObject_GC_New(_PyDictViewObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 if (dv == NULL)
3550 return NULL;
3551 Py_INCREF(dict);
3552 dv->dv_dict = (PyDictObject *)dict;
3553 _PyObject_GC_TRACK(dv);
3554 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003555}
3556
Neal Norwitze36f2ba2007-02-26 23:12:28 +00003557/* TODO(guido): The views objects are not complete:
3558
3559 * support more set operations
3560 * support arbitrary mappings?
3561 - either these should be static or exported in dictobject.h
3562 - if public then they should probably be in builtins
3563*/
3564
Guido van Rossumaac530c2007-08-24 22:33:45 +00003565/* Return 1 if self is a subset of other, iterating over self;
3566 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00003567static int
3568all_contained_in(PyObject *self, PyObject *other)
3569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 PyObject *iter = PyObject_GetIter(self);
3571 int ok = 1;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 if (iter == NULL)
3574 return -1;
3575 for (;;) {
3576 PyObject *next = PyIter_Next(iter);
3577 if (next == NULL) {
3578 if (PyErr_Occurred())
3579 ok = -1;
3580 break;
3581 }
3582 ok = PySequence_Contains(other, next);
3583 Py_DECREF(next);
3584 if (ok <= 0)
3585 break;
3586 }
3587 Py_DECREF(iter);
3588 return ok;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003589}
3590
3591static PyObject *
3592dictview_richcompare(PyObject *self, PyObject *other, int op)
3593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 Py_ssize_t len_self, len_other;
3595 int ok;
3596 PyObject *result;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 assert(self != NULL);
3599 assert(PyDictViewSet_Check(self));
3600 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00003601
Brian Curtindfc80e32011-08-10 20:28:54 -05003602 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
3603 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 len_self = PyObject_Size(self);
3606 if (len_self < 0)
3607 return NULL;
3608 len_other = PyObject_Size(other);
3609 if (len_other < 0)
3610 return NULL;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003612 ok = 0;
3613 switch(op) {
Guido van Rossumaac530c2007-08-24 22:33:45 +00003614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 case Py_NE:
3616 case Py_EQ:
3617 if (len_self == len_other)
3618 ok = all_contained_in(self, other);
3619 if (op == Py_NE && ok >= 0)
3620 ok = !ok;
3621 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003623 case Py_LT:
3624 if (len_self < len_other)
3625 ok = all_contained_in(self, other);
3626 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 case Py_LE:
3629 if (len_self <= len_other)
3630 ok = all_contained_in(self, other);
3631 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 case Py_GT:
3634 if (len_self > len_other)
3635 ok = all_contained_in(other, self);
3636 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003638 case Py_GE:
3639 if (len_self >= len_other)
3640 ok = all_contained_in(other, self);
3641 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643 }
3644 if (ok < 0)
3645 return NULL;
3646 result = ok ? Py_True : Py_False;
3647 Py_INCREF(result);
3648 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003649}
3650
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003651static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003652dictview_repr(_PyDictViewObject *dv)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 PyObject *seq;
3655 PyObject *result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 seq = PySequence_List((PyObject *)dv);
3658 if (seq == NULL)
3659 return NULL;
3660
3661 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
3662 Py_DECREF(seq);
3663 return result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003664}
3665
Guido van Rossum3ac67412007-02-10 18:55:06 +00003666/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003667
3668static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003669dictkeys_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 if (dv->dv_dict == NULL) {
3672 Py_RETURN_NONE;
3673 }
3674 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003675}
3676
3677static int
Eric Snow96c6af92015-05-29 22:21:39 -06003678dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00003679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003680 if (dv->dv_dict == NULL)
3681 return 0;
3682 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003683}
3684
Guido van Rossum83825ac2007-02-10 04:54:19 +00003685static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 (lenfunc)dictview_len, /* sq_length */
3687 0, /* sq_concat */
3688 0, /* sq_repeat */
3689 0, /* sq_item */
3690 0, /* sq_slice */
3691 0, /* sq_ass_item */
3692 0, /* sq_ass_slice */
3693 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003694};
3695
Guido van Rossum523259b2007-08-24 23:41:22 +00003696static PyObject*
3697dictviews_sub(PyObject* self, PyObject *other)
3698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 PyObject *result = PySet_New(self);
3700 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003701 _Py_IDENTIFIER(difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003703 if (result == NULL)
3704 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003705
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003706 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003707 if (tmp == NULL) {
3708 Py_DECREF(result);
3709 return NULL;
3710 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003712 Py_DECREF(tmp);
3713 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003714}
3715
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003716PyObject*
3717_PyDictView_Intersect(PyObject* self, PyObject *other)
Guido van Rossum523259b2007-08-24 23:41:22 +00003718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 PyObject *result = PySet_New(self);
3720 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003721 _Py_IDENTIFIER(intersection_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003723 if (result == NULL)
3724 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003725
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003726 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_intersection_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 if (tmp == NULL) {
3728 Py_DECREF(result);
3729 return NULL;
3730 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 Py_DECREF(tmp);
3733 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003734}
3735
3736static PyObject*
3737dictviews_or(PyObject* self, PyObject *other)
3738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 PyObject *result = PySet_New(self);
3740 PyObject *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02003741 _Py_IDENTIFIER(update);
Victor Stinnerd1a9cc22011-10-13 22:51:17 +02003742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 if (result == NULL)
3744 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003745
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003746 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003747 if (tmp == NULL) {
3748 Py_DECREF(result);
3749 return NULL;
3750 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 Py_DECREF(tmp);
3753 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003754}
3755
3756static PyObject*
3757dictviews_xor(PyObject* self, PyObject *other)
3758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003759 PyObject *result = PySet_New(self);
3760 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003761 _Py_IDENTIFIER(symmetric_difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 if (result == NULL)
3764 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003765
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003766 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_symmetric_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003767 if (tmp == NULL) {
3768 Py_DECREF(result);
3769 return NULL;
3770 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772 Py_DECREF(tmp);
3773 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003774}
3775
3776static PyNumberMethods dictviews_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 0, /*nb_add*/
3778 (binaryfunc)dictviews_sub, /*nb_subtract*/
3779 0, /*nb_multiply*/
3780 0, /*nb_remainder*/
3781 0, /*nb_divmod*/
3782 0, /*nb_power*/
3783 0, /*nb_negative*/
3784 0, /*nb_positive*/
3785 0, /*nb_absolute*/
3786 0, /*nb_bool*/
3787 0, /*nb_invert*/
3788 0, /*nb_lshift*/
3789 0, /*nb_rshift*/
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003790 (binaryfunc)_PyDictView_Intersect, /*nb_and*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 (binaryfunc)dictviews_xor, /*nb_xor*/
3792 (binaryfunc)dictviews_or, /*nb_or*/
Guido van Rossum523259b2007-08-24 23:41:22 +00003793};
3794
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003795static PyObject*
3796dictviews_isdisjoint(PyObject *self, PyObject *other)
3797{
3798 PyObject *it;
3799 PyObject *item = NULL;
3800
3801 if (self == other) {
Eric Snow96c6af92015-05-29 22:21:39 -06003802 if (dictview_len((_PyDictViewObject *)self) == 0)
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003803 Py_RETURN_TRUE;
3804 else
3805 Py_RETURN_FALSE;
3806 }
3807
3808 /* Iterate over the shorter object (only if other is a set,
3809 * because PySequence_Contains may be expensive otherwise): */
3810 if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
Eric Snow96c6af92015-05-29 22:21:39 -06003811 Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003812 Py_ssize_t len_other = PyObject_Size(other);
3813 if (len_other == -1)
3814 return NULL;
3815
3816 if ((len_other > len_self)) {
3817 PyObject *tmp = other;
3818 other = self;
3819 self = tmp;
3820 }
3821 }
3822
3823 it = PyObject_GetIter(other);
3824 if (it == NULL)
3825 return NULL;
3826
3827 while ((item = PyIter_Next(it)) != NULL) {
3828 int contains = PySequence_Contains(self, item);
3829 Py_DECREF(item);
3830 if (contains == -1) {
3831 Py_DECREF(it);
3832 return NULL;
3833 }
3834
3835 if (contains) {
3836 Py_DECREF(it);
3837 Py_RETURN_FALSE;
3838 }
3839 }
3840 Py_DECREF(it);
3841 if (PyErr_Occurred())
3842 return NULL; /* PyIter_Next raised an exception. */
3843 Py_RETURN_TRUE;
3844}
3845
3846PyDoc_STRVAR(isdisjoint_doc,
3847"Return True if the view and the given iterable have a null intersection.");
3848
Guido van Rossumb90c8482007-02-10 01:11:45 +00003849static PyMethodDef dictkeys_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003850 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
3851 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00003853};
3854
3855PyTypeObject PyDictKeys_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003856 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3857 "dict_keys", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06003858 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003859 0, /* tp_itemsize */
3860 /* methods */
3861 (destructor)dictview_dealloc, /* tp_dealloc */
3862 0, /* tp_print */
3863 0, /* tp_getattr */
3864 0, /* tp_setattr */
3865 0, /* tp_reserved */
3866 (reprfunc)dictview_repr, /* tp_repr */
3867 &dictviews_as_number, /* tp_as_number */
3868 &dictkeys_as_sequence, /* tp_as_sequence */
3869 0, /* tp_as_mapping */
3870 0, /* tp_hash */
3871 0, /* tp_call */
3872 0, /* tp_str */
3873 PyObject_GenericGetAttr, /* tp_getattro */
3874 0, /* tp_setattro */
3875 0, /* tp_as_buffer */
3876 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3877 0, /* tp_doc */
3878 (traverseproc)dictview_traverse, /* tp_traverse */
3879 0, /* tp_clear */
3880 dictview_richcompare, /* tp_richcompare */
3881 0, /* tp_weaklistoffset */
3882 (getiterfunc)dictkeys_iter, /* tp_iter */
3883 0, /* tp_iternext */
3884 dictkeys_methods, /* tp_methods */
3885 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00003886};
3887
3888static PyObject *
3889dictkeys_new(PyObject *dict)
3890{
Eric Snow96c6af92015-05-29 22:21:39 -06003891 return _PyDictView_New(dict, &PyDictKeys_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003892}
3893
Guido van Rossum3ac67412007-02-10 18:55:06 +00003894/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003895
3896static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003897dictitems_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 if (dv->dv_dict == NULL) {
3900 Py_RETURN_NONE;
3901 }
3902 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003903}
3904
3905static int
Eric Snow96c6af92015-05-29 22:21:39 -06003906dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00003907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 PyObject *key, *value, *found;
3909 if (dv->dv_dict == NULL)
3910 return 0;
3911 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
3912 return 0;
3913 key = PyTuple_GET_ITEM(obj, 0);
3914 value = PyTuple_GET_ITEM(obj, 1);
3915 found = PyDict_GetItem((PyObject *)dv->dv_dict, key);
3916 if (found == NULL) {
3917 if (PyErr_Occurred())
3918 return -1;
3919 return 0;
3920 }
3921 return PyObject_RichCompareBool(value, found, Py_EQ);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003922}
3923
Guido van Rossum83825ac2007-02-10 04:54:19 +00003924static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003925 (lenfunc)dictview_len, /* sq_length */
3926 0, /* sq_concat */
3927 0, /* sq_repeat */
3928 0, /* sq_item */
3929 0, /* sq_slice */
3930 0, /* sq_ass_item */
3931 0, /* sq_ass_slice */
3932 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003933};
3934
Guido van Rossumb90c8482007-02-10 01:11:45 +00003935static PyMethodDef dictitems_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003936 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
3937 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00003939};
3940
3941PyTypeObject PyDictItems_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003942 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3943 "dict_items", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06003944 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 0, /* tp_itemsize */
3946 /* methods */
3947 (destructor)dictview_dealloc, /* tp_dealloc */
3948 0, /* tp_print */
3949 0, /* tp_getattr */
3950 0, /* tp_setattr */
3951 0, /* tp_reserved */
3952 (reprfunc)dictview_repr, /* tp_repr */
3953 &dictviews_as_number, /* tp_as_number */
3954 &dictitems_as_sequence, /* tp_as_sequence */
3955 0, /* tp_as_mapping */
3956 0, /* tp_hash */
3957 0, /* tp_call */
3958 0, /* tp_str */
3959 PyObject_GenericGetAttr, /* tp_getattro */
3960 0, /* tp_setattro */
3961 0, /* tp_as_buffer */
3962 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3963 0, /* tp_doc */
3964 (traverseproc)dictview_traverse, /* tp_traverse */
3965 0, /* tp_clear */
3966 dictview_richcompare, /* tp_richcompare */
3967 0, /* tp_weaklistoffset */
3968 (getiterfunc)dictitems_iter, /* tp_iter */
3969 0, /* tp_iternext */
3970 dictitems_methods, /* tp_methods */
3971 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00003972};
3973
3974static PyObject *
3975dictitems_new(PyObject *dict)
3976{
Eric Snow96c6af92015-05-29 22:21:39 -06003977 return _PyDictView_New(dict, &PyDictItems_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003978}
3979
Guido van Rossum3ac67412007-02-10 18:55:06 +00003980/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003981
3982static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003983dictvalues_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003985 if (dv->dv_dict == NULL) {
3986 Py_RETURN_NONE;
3987 }
3988 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003989}
3990
Guido van Rossum83825ac2007-02-10 04:54:19 +00003991static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003992 (lenfunc)dictview_len, /* sq_length */
3993 0, /* sq_concat */
3994 0, /* sq_repeat */
3995 0, /* sq_item */
3996 0, /* sq_slice */
3997 0, /* sq_ass_item */
3998 0, /* sq_ass_slice */
3999 (objobjproc)0, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004000};
4001
Guido van Rossumb90c8482007-02-10 01:11:45 +00004002static PyMethodDef dictvalues_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004003 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004004};
4005
4006PyTypeObject PyDictValues_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004007 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4008 "dict_values", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004009 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004010 0, /* tp_itemsize */
4011 /* methods */
4012 (destructor)dictview_dealloc, /* tp_dealloc */
4013 0, /* tp_print */
4014 0, /* tp_getattr */
4015 0, /* tp_setattr */
4016 0, /* tp_reserved */
4017 (reprfunc)dictview_repr, /* tp_repr */
4018 0, /* tp_as_number */
4019 &dictvalues_as_sequence, /* tp_as_sequence */
4020 0, /* tp_as_mapping */
4021 0, /* tp_hash */
4022 0, /* tp_call */
4023 0, /* tp_str */
4024 PyObject_GenericGetAttr, /* tp_getattro */
4025 0, /* tp_setattro */
4026 0, /* tp_as_buffer */
4027 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4028 0, /* tp_doc */
4029 (traverseproc)dictview_traverse, /* tp_traverse */
4030 0, /* tp_clear */
4031 0, /* tp_richcompare */
4032 0, /* tp_weaklistoffset */
4033 (getiterfunc)dictvalues_iter, /* tp_iter */
4034 0, /* tp_iternext */
4035 dictvalues_methods, /* tp_methods */
4036 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004037};
4038
4039static PyObject *
4040dictvalues_new(PyObject *dict)
4041{
Eric Snow96c6af92015-05-29 22:21:39 -06004042 return _PyDictView_New(dict, &PyDictValues_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004043}
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004044
4045/* Returns NULL if cannot allocate a new PyDictKeysObject,
4046 but does not set an error */
4047PyDictKeysObject *
4048_PyDict_NewKeysForClass(void)
4049{
Victor Stinner742da042016-09-07 17:40:12 -07004050 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004051 if (keys == NULL)
4052 PyErr_Clear();
4053 else
4054 keys->dk_lookup = lookdict_split;
4055 return keys;
4056}
4057
4058#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
4059
4060PyObject *
4061PyObject_GenericGetDict(PyObject *obj, void *context)
4062{
4063 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
4064 if (dictptr == NULL) {
4065 PyErr_SetString(PyExc_AttributeError,
4066 "This object has no __dict__");
4067 return NULL;
4068 }
4069 dict = *dictptr;
4070 if (dict == NULL) {
4071 PyTypeObject *tp = Py_TYPE(obj);
4072 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
4073 DK_INCREF(CACHED_KEYS(tp));
4074 *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
4075 }
4076 else {
4077 *dictptr = dict = PyDict_New();
4078 }
4079 }
4080 Py_XINCREF(dict);
4081 return dict;
4082}
4083
4084int
4085_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
Victor Stinner742da042016-09-07 17:40:12 -07004086 PyObject *key, PyObject *value)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004087{
4088 PyObject *dict;
4089 int res;
4090 PyDictKeysObject *cached;
4091
4092 assert(dictptr != NULL);
4093 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
4094 assert(dictptr != NULL);
4095 dict = *dictptr;
4096 if (dict == NULL) {
4097 DK_INCREF(cached);
4098 dict = new_dict_with_shared_keys(cached);
4099 if (dict == NULL)
4100 return -1;
4101 *dictptr = dict;
4102 }
4103 if (value == NULL) {
4104 res = PyDict_DelItem(dict, key);
4105 if (cached != ((PyDictObject *)dict)->ma_keys) {
4106 CACHED_KEYS(tp) = NULL;
4107 DK_DECREF(cached);
4108 }
4109 } else {
4110 res = PyDict_SetItem(dict, key, value);
4111 if (cached != ((PyDictObject *)dict)->ma_keys) {
4112 /* Either update tp->ht_cached_keys or delete it */
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004113 if (cached->dk_refcnt == 1) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004114 CACHED_KEYS(tp) = make_keys_shared(dict);
Victor Stinner742da042016-09-07 17:40:12 -07004115 }
4116 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004117 CACHED_KEYS(tp) = NULL;
4118 }
4119 DK_DECREF(cached);
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004120 if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
4121 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004122 }
4123 }
4124 } else {
4125 dict = *dictptr;
4126 if (dict == NULL) {
4127 dict = PyDict_New();
4128 if (dict == NULL)
4129 return -1;
4130 *dictptr = dict;
4131 }
4132 if (value == NULL) {
4133 res = PyDict_DelItem(dict, key);
4134 } else {
4135 res = PyDict_SetItem(dict, key, value);
4136 }
4137 }
4138 return res;
4139}
4140
4141void
4142_PyDictKeys_DecRef(PyDictKeysObject *keys)
4143{
4144 DK_DECREF(keys);
4145}