blob: 8b88ec6eef2ff56b2e44fbf6d85c7c711a38954a [file] [log] [blame]
Guido van Rossum2bc13791999-03-24 19:06:42 +00001/* Dictionary object implementation using a hash table */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002
Raymond Hettinger930427b2003-05-03 06:51:59 +00003/* The distribution includes a separate file, Objects/dictnotes.txt,
Tim Peters60b29962006-01-01 01:19:23 +00004 describing explorations into dictionary design and optimization.
Raymond Hettinger930427b2003-05-03 06:51:59 +00005 It covers typical dictionary use patterns, the parameters for
6 tuning dictionaries, and several ideas for possible optimizations.
7*/
8
Victor Stinner742da042016-09-07 17:40:12 -07009/* PyDictKeysObject
10
11This implements the dictionary's hashtable.
12
Berker Peksag71c01d42016-09-09 03:57:23 +030013As of Python 3.6, this is compact and ordered. Basic idea is described here.
Benjamin Peterson003f0592016-09-08 10:14:31 -070014https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html
Victor Stinner742da042016-09-07 17:40:12 -070015
16layout:
17
18+---------------+
19| dk_refcnt |
20| dk_size |
21| dk_lookup |
22| dk_usable |
23| dk_nentries |
24+---------------+
25| dk_indices |
26| |
27+---------------+
28| dk_entries |
29| |
30+---------------+
31
32dk_indices is actual hashtable. It holds index in entries, or DKIX_EMPTY(-1)
33or DKIX_DUMMY(-2).
34Size of indices is dk_size. Type of each index in indices is vary on dk_size:
35
36* int8 for dk_size <= 128
37* int16 for 256 <= dk_size <= 2**15
38* int32 for 2**16 <= dk_size <= 2**31
39* int64 for 2**32 <= dk_size
40
41dk_entries is array of PyDictKeyEntry. It's size is USABLE_FRACTION(dk_size).
42DK_ENTRIES(dk) can be used to get pointer to entries.
43
44NOTE: Since negative value is used for DKIX_EMPTY and DKIX_DUMMY, type of
45dk_indices entry is signed integer and int16 is used for table which
46dk_size == 256.
47*/
48
Benjamin Peterson7d95e402012-04-23 11:24:50 -040049
50/*
Benjamin Peterson7d95e402012-04-23 11:24:50 -040051The DictObject can be in one of two forms.
Victor Stinner742da042016-09-07 17:40:12 -070052
Benjamin Peterson7d95e402012-04-23 11:24:50 -040053Either:
54 A combined table:
55 ma_values == NULL, dk_refcnt == 1.
56 Values are stored in the me_value field of the PyDictKeysObject.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040057Or:
58 A split table:
59 ma_values != NULL, dk_refcnt >= 1
60 Values are stored in the ma_values array.
Victor Stinner742da042016-09-07 17:40:12 -070061 Only string (unicode) keys are allowed.
62 All dicts sharing same key must have same insertion order.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040063
Victor Stinner742da042016-09-07 17:40:12 -070064There are four kinds of slots in the table (slot is index, and
65DK_ENTRIES(keys)[index] if index >= 0):
66
671. Unused. index == DKIX_EMPTY
68 Does not hold an active (key, value) pair now and never did. Unused can
69 transition to Active upon key insertion. This is each slot's initial state.
70
712. Active. index >= 0, me_key != NULL and me_value != NULL
72 Holds an active (key, value) pair. Active can transition to Dummy or
73 Pending upon key deletion (for combined and split tables respectively).
74 This is the only case in which me_value != NULL.
75
763. Dummy. index == DKIX_DUMMY (combined only)
77 Previously held an active (key, value) pair, but that was deleted and an
78 active pair has not yet overwritten the slot. Dummy can transition to
79 Active upon key insertion. Dummy slots cannot be made Unused again
80 else the probe sequence in case of collision would have no way to know
81 they were once active.
82
834. Pending. index >= 0, key != NULL, and value == NULL (split only)
84 Not yet inserted in split-table.
Benjamin Peterson7d95e402012-04-23 11:24:50 -040085*/
86
Victor Stinner742da042016-09-07 17:40:12 -070087/*
88Preserving insertion order
Benjamin Peterson7d95e402012-04-23 11:24:50 -040089
Victor Stinner742da042016-09-07 17:40:12 -070090It's simple for combined table. Since dk_entries is mostly append only, we can
91get insertion order by just iterating dk_entries.
92
93One exception is .popitem(). It removes last item in dk_entries and decrement
94dk_nentries to achieve amortized O(1). Since there are DKIX_DUMMY remains in
95dk_indices, we can't increment dk_usable even though dk_nentries is
96decremented.
97
98In split table, inserting into pending entry is allowed only for dk_entries[ix]
99where ix == mp->ma_used. Inserting into other index and deleting item cause
100converting the dict to the combined table.
101*/
102
103/* PyDict_MINSIZE is the starting size for any new dict.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400104 * 8 allows dicts with no more than 5 active entries; experiments suggested
105 * this suffices for the majority of dicts (consisting mostly of usually-small
106 * dicts created to pass keyword arguments).
107 * Making this 8, rather than 4 reduces the number of resizes for most
108 * dictionaries, without any significant extra memory use.
109 */
Victor Stinner742da042016-09-07 17:40:12 -0700110#define PyDict_MINSIZE 8
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400111
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112#include "Python.h"
Eric Snow96c6af92015-05-29 22:21:39 -0600113#include "dict-common.h"
Victor Stinner990397e2016-09-09 20:22:59 -0700114#include "stringlib/eq.h" /* to get unicode_eq() */
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000115
Larry Hastings61272b72014-01-07 12:41:53 -0800116/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -0800117class dict "PyDictObject *" "&PyDict_Type"
Larry Hastings61272b72014-01-07 12:41:53 -0800118[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -0800119/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f157a5a0ce9589d6]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800120
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400121
122/*
123To ensure the lookup algorithm terminates, there must be at least one Unused
124slot (NULL key) in the table.
125To avoid slowing down lookups on a near-full table, we resize the table when
126it's USABLE_FRACTION (currently two-thirds) full.
127*/
Guido van Rossum16e93a81997-01-28 00:00:11 +0000128
Tim Peterseb28ef22001-06-02 05:27:19 +0000129#define PERTURB_SHIFT 5
130
Guido van Rossum16e93a81997-01-28 00:00:11 +0000131/*
Tim Peterseb28ef22001-06-02 05:27:19 +0000132Major subtleties ahead: Most hash schemes depend on having a "good" hash
133function, in the sense of simulating randomness. Python doesn't: its most
R David Murray537ad7a2016-07-10 12:33:18 -0400134important hash functions (for ints) are very regular in common
Tim Peterseb28ef22001-06-02 05:27:19 +0000135cases:
Tim Peters15d49292001-05-27 07:39:22 +0000136
R David Murray537ad7a2016-07-10 12:33:18 -0400137 >>>[hash(i) for i in range(4)]
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000138 [0, 1, 2, 3]
Tim Peters15d49292001-05-27 07:39:22 +0000139
Tim Peterseb28ef22001-06-02 05:27:19 +0000140This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
141the low-order i bits as the initial table index is extremely fast, and there
R David Murray537ad7a2016-07-10 12:33:18 -0400142are no collisions at all for dicts indexed by a contiguous range of ints. So
143this gives better-than-random behavior in common cases, and that's very
144desirable.
Tim Peters15d49292001-05-27 07:39:22 +0000145
Tim Peterseb28ef22001-06-02 05:27:19 +0000146OTOH, when collisions occur, the tendency to fill contiguous slices of the
147hash table makes a good collision resolution strategy crucial. Taking only
148the last i bits of the hash code is also vulnerable: for example, consider
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149the list [i << 16 for i in range(20000)] as a set of keys. Since ints are
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000150their own hash codes, and this fits in a dict of size 2**15, the last 15 bits
151 of every hash code are all 0: they *all* map to the same table index.
Tim Peters15d49292001-05-27 07:39:22 +0000152
Tim Peterseb28ef22001-06-02 05:27:19 +0000153But catering to unusual cases should not slow the usual ones, so we just take
154the last i bits anyway. It's up to collision resolution to do the rest. If
155we *usually* find the key we're looking for on the first try (and, it turns
156out, we usually do -- the table load factor is kept under 2/3, so the odds
157are solidly in our favor), then it makes best sense to keep the initial index
158computation dirt cheap.
Tim Peters15d49292001-05-27 07:39:22 +0000159
Tim Peterseb28ef22001-06-02 05:27:19 +0000160The first half of collision resolution is to visit table indices via this
161recurrence:
Tim Peters15d49292001-05-27 07:39:22 +0000162
Tim Peterseb28ef22001-06-02 05:27:19 +0000163 j = ((5*j) + 1) mod 2**i
Tim Peters15d49292001-05-27 07:39:22 +0000164
Tim Peterseb28ef22001-06-02 05:27:19 +0000165For any initial j in range(2**i), repeating that 2**i times generates each
166int in range(2**i) exactly once (see any text on random-number generation for
167proof). By itself, this doesn't help much: like linear probing (setting
168j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
169order. This would be bad, except that's not the only thing we do, and it's
170actually *good* in the common cases where hash keys are consecutive. In an
171example that's really too small to make this entirely clear, for a table of
172size 2**3 the order of indices is:
Tim Peters15d49292001-05-27 07:39:22 +0000173
Tim Peterseb28ef22001-06-02 05:27:19 +0000174 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
175
176If two things come in at index 5, the first place we look after is index 2,
177not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
178Linear probing is deadly in this case because there the fixed probe order
179is the *same* as the order consecutive keys are likely to arrive. But it's
180extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
181and certain that consecutive hash codes do not.
182
183The other half of the strategy is to get the other bits of the hash code
184into play. This is done by initializing a (unsigned) vrbl "perturb" to the
185full hash code, and changing the recurrence to:
186
187 j = (5*j) + 1 + perturb;
188 perturb >>= PERTURB_SHIFT;
189 use j % 2**i as the next table index;
190
191Now the probe sequence depends (eventually) on every bit in the hash code,
192and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
193because it quickly magnifies small differences in the bits that didn't affect
194the initial index. Note that because perturb is unsigned, if the recurrence
195is executed often enough perturb eventually becomes and remains 0. At that
196point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
197that's certain to find an empty slot eventually (since it generates every int
198in range(2**i), and we make sure there's always at least one empty slot).
199
200Selecting a good value for PERTURB_SHIFT is a balancing act. You want it
201small so that the high bits of the hash code continue to affect the probe
202sequence across iterations; but you want it large so that in really bad cases
203the high-order hash bits have an effect on early iterations. 5 was "the
204best" in minimizing total collisions across experiments Tim Peters ran (on
205both normal and pathological cases), but 4 and 6 weren't significantly worse.
206
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000207Historical: Reimer Behrends contributed the idea of using a polynomial-based
Tim Peterseb28ef22001-06-02 05:27:19 +0000208approach, using repeated multiplication by x in GF(2**n) where an irreducible
209polynomial for each table size was chosen such that x was a primitive root.
210Christian Tismer later extended that to use division by x instead, as an
211efficient way to get the high bits of the hash code into play. This scheme
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000212also gave excellent collision statistics, but was more expensive: two
213if-tests were required inside the loop; computing "the next" index took about
214the same number of operations but without as much potential parallelism
215(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
216above, and then shifting perturb can be done while the table index is being
217masked); and the PyDictObject struct required a member to hold the table's
218polynomial. In Tim's experiments the current scheme ran faster, produced
219equally good collision statistics, needed less code & used less memory.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000220
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000221*/
Tim Petersdea48ec2001-05-22 20:40:22 +0000222
Fred Drake1bff34a2000-08-31 19:31:38 +0000223/* forward declarations */
Victor Stinner742da042016-09-07 17:40:12 -0700224static Py_ssize_t lookdict(PyDictObject *mp, PyObject *key,
225 Py_hash_t hash, PyObject ***value_addr,
226 Py_ssize_t *hashpos);
227static Py_ssize_t lookdict_unicode(PyDictObject *mp, PyObject *key,
228 Py_hash_t hash, PyObject ***value_addr,
229 Py_ssize_t *hashpos);
230static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400231lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700232 Py_hash_t hash, PyObject ***value_addr,
233 Py_ssize_t *hashpos);
234static Py_ssize_t lookdict_split(PyDictObject *mp, PyObject *key,
235 Py_hash_t hash, PyObject ***value_addr,
236 Py_ssize_t *hashpos);
Fred Drake1bff34a2000-08-31 19:31:38 +0000237
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400238static int dictresize(PyDictObject *mp, Py_ssize_t minused);
Tim Petersdea48ec2001-05-22 20:40:22 +0000239
Benjamin Peterson3c569292016-09-08 13:16:41 -0700240/*Global counter used to set ma_version_tag field of dictionary.
Victor Stinner3b6a6b42016-09-08 12:51:24 -0700241 * It is incremented each time that a dictionary is created and each
242 * time that a dictionary is modified. */
243static uint64_t pydict_global_version = 0;
244
245#define DICT_NEXT_VERSION() (++pydict_global_version)
246
Victor Stinner742da042016-09-07 17:40:12 -0700247/* Dictionary reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +0000248#ifndef PyDict_MAXFREELIST
249#define PyDict_MAXFREELIST 80
250#endif
251static PyDictObject *free_list[PyDict_MAXFREELIST];
252static int numfree = 0;
Victor Stinner742da042016-09-07 17:40:12 -0700253static PyDictKeysObject *keys_free_list[PyDict_MAXFREELIST];
254static int numfreekeys = 0;
Raymond Hettinger43442782004-03-17 21:55:03 +0000255
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300256#include "clinic/dictobject.c.h"
257
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100258int
259PyDict_ClearFreeList(void)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 PyDictObject *op;
Victor Stinner742da042016-09-07 17:40:12 -0700262 int ret = numfree + numfreekeys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 while (numfree) {
264 op = free_list[--numfree];
265 assert(PyDict_CheckExact(op));
266 PyObject_GC_Del(op);
267 }
Victor Stinner742da042016-09-07 17:40:12 -0700268 while (numfreekeys) {
269 PyObject_FREE(keys_free_list[--numfreekeys]);
270 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100271 return ret;
272}
273
David Malcolm49526f42012-06-22 14:55:41 -0400274/* Print summary info about the state of the optimized allocator */
275void
276_PyDict_DebugMallocStats(FILE *out)
277{
278 _PyDebugAllocatorStats(out,
279 "free PyDictObject", numfree, sizeof(PyDictObject));
280}
281
282
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100283void
284PyDict_Fini(void)
285{
286 PyDict_ClearFreeList();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000287}
288
Victor Stinner742da042016-09-07 17:40:12 -0700289#define DK_SIZE(dk) ((dk)->dk_size)
290#if SIZEOF_VOID_P > 4
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700291#define DK_IXSIZE(dk) \
292 (DK_SIZE(dk) <= 0xff ? \
293 1 : DK_SIZE(dk) <= 0xffff ? \
294 2 : DK_SIZE(dk) <= 0xffffffff ? \
Benjamin Peterson3c569292016-09-08 13:16:41 -0700295 4 : sizeof(int64_t))
Victor Stinner742da042016-09-07 17:40:12 -0700296#else
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700297#define DK_IXSIZE(dk) \
298 (DK_SIZE(dk) <= 0xff ? \
299 1 : DK_SIZE(dk) <= 0xffff ? \
Benjamin Peterson3c569292016-09-08 13:16:41 -0700300 2 : sizeof(int32_t))
Victor Stinner742da042016-09-07 17:40:12 -0700301#endif
Victor Stinner58f7c5a2016-09-08 11:37:36 -0700302#define DK_ENTRIES(dk) \
Benjamin Peterson186122e2016-09-08 12:20:12 -0700303 ((PyDictKeyEntry*)(&(dk)->dk_indices.as_1[DK_SIZE(dk) * DK_IXSIZE(dk)]))
Victor Stinner742da042016-09-07 17:40:12 -0700304
Antoine Pitrou2d169b22012-05-12 23:43:44 +0200305#define DK_DEBUG_INCREF _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA
306#define DK_DEBUG_DECREF _Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA
307
308#define DK_INCREF(dk) (DK_DEBUG_INCREF ++(dk)->dk_refcnt)
309#define DK_DECREF(dk) if (DK_DEBUG_DECREF (--(dk)->dk_refcnt) == 0) free_keys_object(dk)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400310#define DK_MASK(dk) (((dk)->dk_size)-1)
311#define IS_POWER_OF_2(x) (((x) & (x-1)) == 0)
312
Victor Stinner742da042016-09-07 17:40:12 -0700313
314/* lookup indices. returns DKIX_EMPTY, DKIX_DUMMY, or ix >=0 */
Benjamin Peterson73222252016-09-08 09:58:47 -0700315static inline Py_ssize_t
Victor Stinner742da042016-09-07 17:40:12 -0700316dk_get_index(PyDictKeysObject *keys, Py_ssize_t i)
317{
318 Py_ssize_t s = DK_SIZE(keys);
Victor Stinner71211e32016-09-08 10:52:46 -0700319 Py_ssize_t ix;
320
Victor Stinner742da042016-09-07 17:40:12 -0700321 if (s <= 0xff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700322 int8_t *indices = keys->dk_indices.as_1;
Victor Stinner208857e2016-09-08 11:35:46 -0700323 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700324 }
325 else if (s <= 0xffff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700326 int16_t *indices = keys->dk_indices.as_2;
Victor Stinner208857e2016-09-08 11:35:46 -0700327 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700328 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700329#if SIZEOF_VOID_P > 4
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300330 else if (s > 0xffffffff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700331 int64_t *indices = keys->dk_indices.as_8;
Victor Stinner208857e2016-09-08 11:35:46 -0700332 ix = indices[i];
Victor Stinner742da042016-09-07 17:40:12 -0700333 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700334#endif
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300335 else {
336 int32_t *indices = keys->dk_indices.as_4;
337 ix = indices[i];
338 }
Victor Stinner71211e32016-09-08 10:52:46 -0700339 assert(ix >= DKIX_DUMMY);
340 return ix;
Victor Stinner742da042016-09-07 17:40:12 -0700341}
342
343/* write to indices. */
Benjamin Peterson73222252016-09-08 09:58:47 -0700344static inline void
Victor Stinner742da042016-09-07 17:40:12 -0700345dk_set_index(PyDictKeysObject *keys, Py_ssize_t i, Py_ssize_t ix)
346{
347 Py_ssize_t s = DK_SIZE(keys);
Victor Stinner71211e32016-09-08 10:52:46 -0700348
349 assert(ix >= DKIX_DUMMY);
350
Victor Stinner742da042016-09-07 17:40:12 -0700351 if (s <= 0xff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700352 int8_t *indices = keys->dk_indices.as_1;
Victor Stinner71211e32016-09-08 10:52:46 -0700353 assert(ix <= 0x7f);
Victor Stinner208857e2016-09-08 11:35:46 -0700354 indices[i] = (char)ix;
Victor Stinner742da042016-09-07 17:40:12 -0700355 }
356 else if (s <= 0xffff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700357 int16_t *indices = keys->dk_indices.as_2;
Victor Stinner71211e32016-09-08 10:52:46 -0700358 assert(ix <= 0x7fff);
Victor Stinner208857e2016-09-08 11:35:46 -0700359 indices[i] = (int16_t)ix;
Victor Stinner742da042016-09-07 17:40:12 -0700360 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700361#if SIZEOF_VOID_P > 4
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300362 else if (s > 0xffffffff) {
Benjamin Peterson186122e2016-09-08 12:20:12 -0700363 int64_t *indices = keys->dk_indices.as_8;
Victor Stinner208857e2016-09-08 11:35:46 -0700364 indices[i] = ix;
Victor Stinner742da042016-09-07 17:40:12 -0700365 }
Benjamin Peterson3c569292016-09-08 13:16:41 -0700366#endif
Serhiy Storchaka473e0e42016-09-10 21:34:43 +0300367 else {
368 int32_t *indices = keys->dk_indices.as_4;
369 assert(ix <= 0x7fffffff);
370 indices[i] = (int32_t)ix;
371 }
Victor Stinner742da042016-09-07 17:40:12 -0700372}
373
374
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200375/* USABLE_FRACTION is the maximum dictionary load.
Victor Stinner742da042016-09-07 17:40:12 -0700376 * Increasing this ratio makes dictionaries more dense resulting in more
377 * collisions. Decreasing it improves sparseness at the expense of spreading
378 * indices over more cache lines and at the cost of total memory consumed.
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200379 *
380 * USABLE_FRACTION must obey the following:
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400381 * (0 < USABLE_FRACTION(n) < n) for all n >= 2
382 *
Victor Stinner742da042016-09-07 17:40:12 -0700383 * USABLE_FRACTION should be quick to calculate.
384 * Fractions around 1/2 to 2/3 seem to work well in practice.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400385 */
Victor Stinner742da042016-09-07 17:40:12 -0700386#define USABLE_FRACTION(n) (((n) << 1)/3)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400387
Victor Stinner742da042016-09-07 17:40:12 -0700388/* ESTIMATE_SIZE is reverse function of USABLE_FRACTION.
389 * This can be used to reserve enough size to insert n entries without
390 * resizing.
391 */
392#define ESTIMATE_SIZE(n) (((n)*3) >> 1)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400393
Victor Stinner742da042016-09-07 17:40:12 -0700394/* Alternative fraction that is otherwise close enough to 2n/3 to make
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400395 * little difference. 8 * 2/3 == 8 * 5/8 == 5. 16 * 2/3 == 16 * 5/8 == 10.
396 * 32 * 2/3 = 21, 32 * 5/8 = 20.
397 * Its advantage is that it is faster to compute on machines with slow division.
398 * #define USABLE_FRACTION(n) (((n) >> 1) + ((n) >> 2) - ((n) >> 3))
Victor Stinner742da042016-09-07 17:40:12 -0700399 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400400
Victor Stinnera9f61a52013-07-16 22:17:26 +0200401/* GROWTH_RATE. Growth rate upon hitting maximum load.
402 * Currently set to used*2 + capacity/2.
403 * This means that dicts double in size when growing without deletions,
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700404 * but have more head room when the number of deletions is on a par with the
405 * number of insertions.
406 * Raising this to used*4 doubles memory consumption depending on the size of
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200407 * the dictionary, but results in half the number of resizes, less effort to
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700408 * resize.
409 * GROWTH_RATE was set to used*4 up to version 3.2.
410 * GROWTH_RATE was set to used*2 in version 3.3.0
Antoine Pitroua504a7a2012-06-24 21:03:45 +0200411 */
Raymond Hettinger36f74aa2013-05-17 03:01:13 -0700412#define GROWTH_RATE(d) (((d)->ma_used*2)+((d)->ma_keys->dk_size>>1))
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400413
414#define ENSURE_ALLOWS_DELETIONS(d) \
415 if ((d)->ma_keys->dk_lookup == lookdict_unicode_nodummy) { \
416 (d)->ma_keys->dk_lookup = lookdict_unicode; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400418
419/* This immutable, empty PyDictKeysObject is used for PyDict_Clear()
420 * (which cannot fail and thus can do no allocation).
421 */
422static PyDictKeysObject empty_keys_struct = {
423 2, /* dk_refcnt 1 for this struct, 1 for dummy_struct */
424 1, /* dk_size */
425 lookdict_split, /* dk_lookup */
426 0, /* dk_usable (immutable) */
Victor Stinner742da042016-09-07 17:40:12 -0700427 0, /* dk_nentries */
Benjamin Peterson186122e2016-09-08 12:20:12 -0700428 .dk_indices = { .as_1 = {DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY,
429 DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY}},
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400430};
431
432static PyObject *empty_values[1] = { NULL };
433
434#define Py_EMPTY_KEYS &empty_keys_struct
435
436static PyDictKeysObject *new_keys_object(Py_ssize_t size)
437{
438 PyDictKeysObject *dk;
Victor Stinner742da042016-09-07 17:40:12 -0700439 Py_ssize_t es, usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400440
Victor Stinner742da042016-09-07 17:40:12 -0700441 assert(size >= PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400442 assert(IS_POWER_OF_2(size));
Victor Stinner742da042016-09-07 17:40:12 -0700443
444 usable = USABLE_FRACTION(size);
445 if (size <= 0xff) {
446 es = 1;
447 }
448 else if (size <= 0xffff) {
449 es = 2;
450 }
451#if SIZEOF_VOID_P > 4
452 else if (size <= 0xffffffff) {
453 es = 4;
454 }
455#endif
456 else {
457 es = sizeof(Py_ssize_t);
458 }
459
460 if (size == PyDict_MINSIZE && numfreekeys > 0) {
461 dk = keys_free_list[--numfreekeys];
462 }
463 else {
Victor Stinner98ee9d52016-09-08 09:33:56 -0700464 dk = PyObject_MALLOC(sizeof(PyDictKeysObject)
465 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
466 + es * size
467 + sizeof(PyDictKeyEntry) * usable);
Victor Stinner742da042016-09-07 17:40:12 -0700468 if (dk == NULL) {
469 PyErr_NoMemory();
470 return NULL;
471 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400472 }
Antoine Pitrou2d169b22012-05-12 23:43:44 +0200473 DK_DEBUG_INCREF dk->dk_refcnt = 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400474 dk->dk_size = size;
Victor Stinner742da042016-09-07 17:40:12 -0700475 dk->dk_usable = usable;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400476 dk->dk_lookup = lookdict_unicode_nodummy;
Victor Stinner742da042016-09-07 17:40:12 -0700477 dk->dk_nentries = 0;
Benjamin Peterson186122e2016-09-08 12:20:12 -0700478 memset(&dk->dk_indices.as_1[0], 0xff, es * size);
Victor Stinner742da042016-09-07 17:40:12 -0700479 memset(DK_ENTRIES(dk), 0, sizeof(PyDictKeyEntry) * usable);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400480 return dk;
481}
482
483static void
484free_keys_object(PyDictKeysObject *keys)
485{
Victor Stinner742da042016-09-07 17:40:12 -0700486 PyDictKeyEntry *entries = DK_ENTRIES(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400487 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -0700488 for (i = 0, n = keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400489 Py_XDECREF(entries[i].me_key);
490 Py_XDECREF(entries[i].me_value);
491 }
Victor Stinner742da042016-09-07 17:40:12 -0700492 if (keys->dk_size == PyDict_MINSIZE && numfreekeys < PyDict_MAXFREELIST) {
493 keys_free_list[numfreekeys++] = keys;
494 return;
495 }
Raymond Hettingerce5179f2016-01-31 08:56:21 -0800496 PyObject_FREE(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400497}
498
499#define new_values(size) PyMem_NEW(PyObject *, size)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400500#define free_values(values) PyMem_FREE(values)
501
502/* Consumes a reference to the keys object */
503static PyObject *
504new_dict(PyDictKeysObject *keys, PyObject **values)
505{
506 PyDictObject *mp;
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200507 assert(keys != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 if (numfree) {
509 mp = free_list[--numfree];
510 assert (mp != NULL);
511 assert (Py_TYPE(mp) == &PyDict_Type);
512 _Py_NewReference((PyObject *)mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400514 else {
515 mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
516 if (mp == NULL) {
517 DK_DECREF(keys);
518 free_values(values);
519 return NULL;
520 }
521 }
522 mp->ma_keys = keys;
523 mp->ma_values = values;
524 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -0700525 mp->ma_version_tag = DICT_NEXT_VERSION();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000527}
528
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400529/* Consumes a reference to the keys object */
530static PyObject *
531new_dict_with_shared_keys(PyDictKeysObject *keys)
532{
533 PyObject **values;
534 Py_ssize_t i, size;
535
Victor Stinner742da042016-09-07 17:40:12 -0700536 size = USABLE_FRACTION(DK_SIZE(keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400537 values = new_values(size);
538 if (values == NULL) {
539 DK_DECREF(keys);
540 return PyErr_NoMemory();
541 }
542 for (i = 0; i < size; i++) {
543 values[i] = NULL;
544 }
545 return new_dict(keys, values);
546}
547
548PyObject *
549PyDict_New(void)
550{
Victor Stinner742da042016-09-07 17:40:12 -0700551 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerc9b7f512013-07-08 22:19:20 +0200552 if (keys == NULL)
553 return NULL;
554 return new_dict(keys, NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400555}
556
Victor Stinner742da042016-09-07 17:40:12 -0700557/* Search index of hash table from offset of entry table */
558static Py_ssize_t
559lookdict_index(PyDictKeysObject *k, Py_hash_t hash, Py_ssize_t index)
560{
561 size_t i, perturb;
562 size_t mask = DK_MASK(k);
563 Py_ssize_t ix;
564
565 i = (size_t)hash & mask;
566 ix = dk_get_index(k, i);
567 if (ix == index) {
568 return i;
569 }
570 if (ix == DKIX_EMPTY) {
571 return DKIX_EMPTY;
572 }
573
574 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
575 i = mask & ((i << 2) + i + perturb + 1);
576 ix = dk_get_index(k, i);
577 if (ix == index) {
578 return i;
579 }
580 if (ix == DKIX_EMPTY) {
581 return DKIX_EMPTY;
582 }
583 }
584 assert(0); /* NOT REACHED */
585 return DKIX_ERROR;
586}
587
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000588/*
589The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000590This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000591Open addressing is preferred over chaining since the link overhead for
592chaining would be substantial (100% with typical malloc overhead).
593
Tim Peterseb28ef22001-06-02 05:27:19 +0000594The initial probe index is computed as hash mod the table size. Subsequent
595probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000596
597All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000598
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000599The details in this version are due to Tim Peters, building on many past
Tim Peterseb28ef22001-06-02 05:27:19 +0000600contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000601Christian Tismer.
Fred Drake1bff34a2000-08-31 19:31:38 +0000602
Victor Stinner742da042016-09-07 17:40:12 -0700603lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a
Victor Stinnera4348cc2016-09-08 12:01:25 -0700604comparison raises an exception.
Guido van Rossum89d8c602007-09-18 17:26:56 +0000605lookdict_unicode() below is specialized to string keys, comparison of which can
Victor Stinner742da042016-09-07 17:40:12 -0700606never raise an exception; that function can never return DKIX_ERROR.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400607lookdict_unicode_nodummy is further specialized for string keys that cannot be
608the <dummy> value.
Victor Stinner742da042016-09-07 17:40:12 -0700609For both, when the key isn't found a DKIX_EMPTY is returned. hashpos returns
610where the key index should be inserted.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000611*/
Victor Stinner742da042016-09-07 17:40:12 -0700612static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400613lookdict(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700614 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000615{
Victor Stinner742da042016-09-07 17:40:12 -0700616 size_t i, perturb, mask;
617 Py_ssize_t ix, freeslot;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200618 int cmp;
Victor Stinner742da042016-09-07 17:40:12 -0700619 PyDictKeysObject *dk;
620 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 PyObject *startkey;
Tim Peterseb28ef22001-06-02 05:27:19 +0000622
Antoine Pitrou9a234902012-05-13 20:48:01 +0200623top:
Victor Stinner742da042016-09-07 17:40:12 -0700624 dk = mp->ma_keys;
625 mask = DK_MASK(dk);
626 ep0 = DK_ENTRIES(dk);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700628
629 ix = dk_get_index(dk, i);
630 if (ix == DKIX_EMPTY) {
631 if (hashpos != NULL)
632 *hashpos = i;
633 *value_addr = NULL;
634 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400635 }
Victor Stinner742da042016-09-07 17:40:12 -0700636 if (ix == DKIX_DUMMY) {
637 freeslot = i;
638 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 else {
Victor Stinner742da042016-09-07 17:40:12 -0700640 ep = &ep0[ix];
641 if (ep->me_key == key) {
642 *value_addr = &ep->me_value;
643 if (hashpos != NULL)
644 *hashpos = i;
645 return ix;
646 }
647 if (ep->me_key != NULL && ep->me_hash == hash) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 startkey = ep->me_key;
649 Py_INCREF(startkey);
650 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
651 Py_DECREF(startkey);
652 if (cmp < 0)
Victor Stinner742da042016-09-07 17:40:12 -0700653 return DKIX_ERROR;
654 if (dk == mp->ma_keys && ep->me_key == startkey) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400655 if (cmp > 0) {
656 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700657 if (hashpos != NULL)
658 *hashpos = i;
659 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400660 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 }
662 else {
Antoine Pitrou9a234902012-05-13 20:48:01 +0200663 /* The dict was mutated, restart */
664 goto top;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 }
666 }
Victor Stinner742da042016-09-07 17:40:12 -0700667 freeslot = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 }
Tim Peters15d49292001-05-27 07:39:22 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700671 i = ((i << 2) + i + perturb + 1) & mask;
672 ix = dk_get_index(dk, i);
673 if (ix == DKIX_EMPTY) {
674 if (hashpos != NULL) {
675 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400676 }
Victor Stinner742da042016-09-07 17:40:12 -0700677 *value_addr = NULL;
678 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400679 }
Victor Stinner742da042016-09-07 17:40:12 -0700680 if (ix == DKIX_DUMMY) {
681 if (freeslot == -1)
682 freeslot = i;
683 continue;
684 }
685 ep = &ep0[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400686 if (ep->me_key == key) {
Victor Stinner742da042016-09-07 17:40:12 -0700687 if (hashpos != NULL) {
688 *hashpos = i;
689 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400690 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700691 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400692 }
Victor Stinner742da042016-09-07 17:40:12 -0700693 if (ep->me_hash == hash && ep->me_key != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 startkey = ep->me_key;
695 Py_INCREF(startkey);
696 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
697 Py_DECREF(startkey);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400698 if (cmp < 0) {
699 *value_addr = NULL;
Victor Stinner742da042016-09-07 17:40:12 -0700700 return DKIX_ERROR;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400701 }
Victor Stinner742da042016-09-07 17:40:12 -0700702 if (dk == mp->ma_keys && ep->me_key == startkey) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400703 if (cmp > 0) {
Victor Stinner742da042016-09-07 17:40:12 -0700704 if (hashpos != NULL) {
705 *hashpos = i;
706 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400707 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700708 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400709 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 }
711 else {
Antoine Pitrou9a234902012-05-13 20:48:01 +0200712 /* The dict was mutated, restart */
713 goto top;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 }
715 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 }
717 assert(0); /* NOT REACHED */
718 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000719}
720
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400721/* Specialized version for string-only keys */
Victor Stinner742da042016-09-07 17:40:12 -0700722static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400723lookdict_unicode(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700724 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Fred Drake1bff34a2000-08-31 19:31:38 +0000725{
Victor Stinner742da042016-09-07 17:40:12 -0700726 size_t i, perturb;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200727 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700728 Py_ssize_t ix, freeslot;
729 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Fred Drake1bff34a2000-08-31 19:31:38 +0000730
Victor Stinner742da042016-09-07 17:40:12 -0700731 assert(mp->ma_values == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 /* Make sure this function doesn't have to handle non-unicode keys,
733 including subclasses of str; e.g., one reason to subclass
734 unicodes is to override __eq__, and for speed we don't cater to
735 that here. */
736 if (!PyUnicode_CheckExact(key)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400737 mp->ma_keys->dk_lookup = lookdict;
Victor Stinner742da042016-09-07 17:40:12 -0700738 return lookdict(mp, key, hash, value_addr, hashpos);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 }
Mark Dickinson57e683e2011-09-24 18:18:40 +0100740 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700741 ix = dk_get_index(mp->ma_keys, i);
742 if (ix == DKIX_EMPTY) {
743 if (hashpos != NULL)
744 *hashpos = i;
745 *value_addr = NULL;
746 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400747 }
Victor Stinner742da042016-09-07 17:40:12 -0700748 if (ix == DKIX_DUMMY) {
749 freeslot = i;
750 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 else {
Victor Stinner742da042016-09-07 17:40:12 -0700752 ep = &ep0[ix];
753 /* only split table can be ix != DKIX_DUMMY && me_key == NULL */
754 assert(ep->me_key != NULL);
755 if (ep->me_key == key || (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
756 if (hashpos != NULL)
757 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400758 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700759 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400760 }
Victor Stinner742da042016-09-07 17:40:12 -0700761 freeslot = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 }
Tim Peters15d49292001-05-27 07:39:22 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700765 i = mask & ((i << 2) + i + perturb + 1);
766 ix = dk_get_index(mp->ma_keys, i);
767 if (ix == DKIX_EMPTY) {
768 if (hashpos != NULL) {
769 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400770 }
Victor Stinner742da042016-09-07 17:40:12 -0700771 *value_addr = NULL;
772 return DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400773 }
Victor Stinner742da042016-09-07 17:40:12 -0700774 if (ix == DKIX_DUMMY) {
775 if (freeslot == -1)
776 freeslot = i;
777 continue;
778 }
779 ep = &ep0[ix];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 if (ep->me_key == key
781 || (ep->me_hash == hash
Victor Stinner742da042016-09-07 17:40:12 -0700782 && ep->me_key != NULL
783 && unicode_eq(ep->me_key, key))) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400784 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700785 if (hashpos != NULL) {
786 *hashpos = i;
787 }
788 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400789 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 }
791 assert(0); /* NOT REACHED */
792 return 0;
Fred Drake1bff34a2000-08-31 19:31:38 +0000793}
794
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400795/* Faster version of lookdict_unicode when it is known that no <dummy> keys
796 * will be present. */
Victor Stinner742da042016-09-07 17:40:12 -0700797static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400798lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700799 Py_hash_t hash, PyObject ***value_addr,
800 Py_ssize_t *hashpos)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400801{
Victor Stinner742da042016-09-07 17:40:12 -0700802 size_t i, perturb;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200803 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700804 Py_ssize_t ix;
805 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400806
Victor Stinner742da042016-09-07 17:40:12 -0700807 assert(mp->ma_values == NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400808 /* Make sure this function doesn't have to handle non-unicode keys,
809 including subclasses of str; e.g., one reason to subclass
810 unicodes is to override __eq__, and for speed we don't cater to
811 that here. */
812 if (!PyUnicode_CheckExact(key)) {
813 mp->ma_keys->dk_lookup = lookdict;
Victor Stinner742da042016-09-07 17:40:12 -0700814 return lookdict(mp, key, hash, value_addr, hashpos);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400815 }
816 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700817 ix = dk_get_index(mp->ma_keys, i);
818 assert (ix != DKIX_DUMMY);
819 if (ix == DKIX_EMPTY) {
820 if (hashpos != NULL)
821 *hashpos = i;
822 *value_addr = NULL;
823 return DKIX_EMPTY;
824 }
825 ep = &ep0[ix];
Victor Stinnerdee6e252016-09-08 11:16:07 -0700826 assert(ep->me_key != NULL);
827 assert(PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700828 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400829 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700830 if (hashpos != NULL)
831 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400832 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700833 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400834 }
835 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700836 i = mask & ((i << 2) + i + perturb + 1);
837 ix = dk_get_index(mp->ma_keys, i);
838 assert (ix != DKIX_DUMMY);
839 if (ix == DKIX_EMPTY) {
840 if (hashpos != NULL)
841 *hashpos = i;
842 *value_addr = NULL;
843 return DKIX_EMPTY;
844 }
845 ep = &ep0[ix];
846 assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
847 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400848 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700849 if (hashpos != NULL)
850 *hashpos = i;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400851 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -0700852 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400853 }
854 }
855 assert(0); /* NOT REACHED */
856 return 0;
857}
858
859/* Version of lookdict for split tables.
860 * All split tables and only split tables use this lookup function.
861 * Split tables only contain unicode keys and no dummy keys,
862 * so algorithm is the same as lookdict_unicode_nodummy.
863 */
Victor Stinner742da042016-09-07 17:40:12 -0700864static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400865lookdict_split(PyDictObject *mp, PyObject *key,
Victor Stinner742da042016-09-07 17:40:12 -0700866 Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400867{
Victor Stinner742da042016-09-07 17:40:12 -0700868 size_t i, perturb;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200869 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700870 Py_ssize_t ix;
871 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400872
Victor Stinner742da042016-09-07 17:40:12 -0700873 /* mp must split table */
874 assert(mp->ma_values != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400875 if (!PyUnicode_CheckExact(key)) {
Victor Stinner742da042016-09-07 17:40:12 -0700876 ix = lookdict(mp, key, hash, value_addr, hashpos);
877 if (ix >= 0) {
878 *value_addr = &mp->ma_values[ix];
879 }
880 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400881 }
Victor Stinner742da042016-09-07 17:40:12 -0700882
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400883 i = (size_t)hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -0700884 ix = dk_get_index(mp->ma_keys, i);
885 if (ix == DKIX_EMPTY) {
886 if (hashpos != NULL)
887 *hashpos = i;
888 *value_addr = NULL;
889 return DKIX_EMPTY;
890 }
891 assert(ix >= 0);
892 ep = &ep0[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400893 assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700894 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400895 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700896 if (hashpos != NULL)
897 *hashpos = i;
898 *value_addr = &mp->ma_values[ix];
899 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400900 }
901 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
Victor Stinner742da042016-09-07 17:40:12 -0700902 i = mask & ((i << 2) + i + perturb + 1);
903 ix = dk_get_index(mp->ma_keys, i);
904 if (ix == DKIX_EMPTY) {
905 if (hashpos != NULL)
906 *hashpos = i;
907 *value_addr = NULL;
908 return DKIX_EMPTY;
909 }
910 assert(ix >= 0);
911 ep = &ep0[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400912 assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
Victor Stinner742da042016-09-07 17:40:12 -0700913 if (ep->me_key == key ||
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400914 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
Victor Stinner742da042016-09-07 17:40:12 -0700915 if (hashpos != NULL)
916 *hashpos = i;
917 *value_addr = &mp->ma_values[ix];
918 return ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400919 }
920 }
921 assert(0); /* NOT REACHED */
922 return 0;
923}
924
Benjamin Petersonfb886362010-04-24 18:21:17 +0000925int
926_PyDict_HasOnlyStringKeys(PyObject *dict)
927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 Py_ssize_t pos = 0;
929 PyObject *key, *value;
Benjamin Petersonf6096542010-11-17 22:33:12 +0000930 assert(PyDict_Check(dict));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* Shortcut */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400932 if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 return 1;
934 while (PyDict_Next(dict, &pos, &key, &value))
935 if (!PyUnicode_Check(key))
936 return 0;
937 return 1;
Benjamin Petersonfb886362010-04-24 18:21:17 +0000938}
939
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000940#define MAINTAIN_TRACKING(mp, key, value) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 do { \
942 if (!_PyObject_GC_IS_TRACKED(mp)) { \
943 if (_PyObject_GC_MAY_BE_TRACKED(key) || \
944 _PyObject_GC_MAY_BE_TRACKED(value)) { \
945 _PyObject_GC_TRACK(mp); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 } \
947 } \
948 } while(0)
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000949
950void
951_PyDict_MaybeUntrack(PyObject *op)
952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 PyDictObject *mp;
954 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -0700955 Py_ssize_t i, numentries;
956 PyDictKeyEntry *ep0;
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
959 return;
960
961 mp = (PyDictObject *) op;
Victor Stinner742da042016-09-07 17:40:12 -0700962 ep0 = DK_ENTRIES(mp->ma_keys);
963 numentries = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400964 if (_PyDict_HasSplitTable(mp)) {
Victor Stinner742da042016-09-07 17:40:12 -0700965 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400966 if ((value = mp->ma_values[i]) == NULL)
967 continue;
968 if (_PyObject_GC_MAY_BE_TRACKED(value)) {
Victor Stinner742da042016-09-07 17:40:12 -0700969 assert(!_PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key));
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400970 return;
971 }
972 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400974 else {
Victor Stinner742da042016-09-07 17:40:12 -0700975 for (i = 0; i < numentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400976 if ((value = ep0[i].me_value) == NULL)
977 continue;
978 if (_PyObject_GC_MAY_BE_TRACKED(value) ||
979 _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
980 return;
981 }
982 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 _PyObject_GC_UNTRACK(op);
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000984}
985
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400986/* Internal function to find slot for an item from its hash
Victor Stinner3c336c52016-09-12 14:17:40 +0200987 when it is known that the key is not present in the dict.
988
989 The dict must be combined. */
Victor Stinner742da042016-09-07 17:40:12 -0700990static Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400991find_empty_slot(PyDictObject *mp, PyObject *key, Py_hash_t hash,
Victor Stinner742da042016-09-07 17:40:12 -0700992 PyObject ***value_addr, Py_ssize_t *hashpos)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000993{
Victor Stinner742da042016-09-07 17:40:12 -0700994 size_t i, perturb;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400995 size_t mask = DK_MASK(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -0700996 Py_ssize_t ix;
997 PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000998
Victor Stinner3c336c52016-09-12 14:17:40 +0200999 assert(!_PyDict_HasSplitTable(mp));
Victor Stinner742da042016-09-07 17:40:12 -07001000 assert(hashpos != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001001 assert(key != NULL);
Victor Stinner3c336c52016-09-12 14:17:40 +02001002
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001003 if (!PyUnicode_CheckExact(key))
1004 mp->ma_keys->dk_lookup = lookdict;
1005 i = hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -07001006 ix = dk_get_index(mp->ma_keys, i);
1007 for (perturb = hash; ix != DKIX_EMPTY; perturb >>= PERTURB_SHIFT) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001008 i = (i << 2) + i + perturb + 1;
Victor Stinner742da042016-09-07 17:40:12 -07001009 ix = dk_get_index(mp->ma_keys, i & mask);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 }
Victor Stinner742da042016-09-07 17:40:12 -07001011 ep = &ep0[mp->ma_keys->dk_nentries];
1012 *hashpos = i & mask;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001013 assert(ep->me_value == NULL);
1014 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07001015 *value_addr = &mp->ma_values[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001016 else
1017 *value_addr = &ep->me_value;
Victor Stinner742da042016-09-07 17:40:12 -07001018 return ix;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001019}
1020
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001021static int
1022insertion_resize(PyDictObject *mp)
1023{
Raymond Hettinger36f74aa2013-05-17 03:01:13 -07001024 return dictresize(mp, GROWTH_RATE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001025}
Antoine Pitroue965d972012-02-27 00:45:12 +01001026
1027/*
1028Internal routine to insert a new item into the table.
1029Used both by the internal resize routine and by the public insert routine.
Antoine Pitroue965d972012-02-27 00:45:12 +01001030Returns -1 if an error occurred, or 0 on success.
1031*/
1032static int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001033insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001034{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001035 PyObject *old_value;
1036 PyObject **value_addr;
Victor Stinner742da042016-09-07 17:40:12 -07001037 PyDictKeyEntry *ep, *ep0;
1038 Py_ssize_t hashpos, ix;
Antoine Pitroue965d972012-02-27 00:45:12 +01001039
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001040 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
1041 if (insertion_resize(mp) < 0)
1042 return -1;
1043 }
1044
Victor Stinner742da042016-09-07 17:40:12 -07001045 ix = mp->ma_keys->dk_lookup(mp, key, hash, &value_addr, &hashpos);
1046 if (ix == DKIX_ERROR) {
Antoine Pitroue965d972012-02-27 00:45:12 +01001047 return -1;
1048 }
Victor Stinner742da042016-09-07 17:40:12 -07001049
Antoine Pitroud6967322014-10-18 00:35:00 +02001050 assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
Benjamin Petersona6f195e2012-04-30 10:23:40 -04001051 Py_INCREF(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001052 MAINTAIN_TRACKING(mp, key, value);
Victor Stinner742da042016-09-07 17:40:12 -07001053
1054 /* When insertion order is different from shared key, we can't share
1055 * the key anymore. Convert this instance to combine table.
1056 */
1057 if (_PyDict_HasSplitTable(mp) &&
1058 ((ix >= 0 && *value_addr == NULL && mp->ma_used != ix) ||
1059 (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
1060 if (insertion_resize(mp) < 0) {
1061 Py_DECREF(value);
1062 return -1;
1063 }
1064 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
1065 ix = DKIX_EMPTY;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001066 }
Victor Stinner742da042016-09-07 17:40:12 -07001067
1068 if (ix == DKIX_EMPTY) {
1069 /* Insert into new slot. */
1070 if (mp->ma_keys->dk_usable <= 0) {
1071 /* Need to resize. */
1072 if (insertion_resize(mp) < 0) {
1073 Py_DECREF(value);
1074 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001075 }
Victor Stinner742da042016-09-07 17:40:12 -07001076 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
1077 }
1078 ep0 = DK_ENTRIES(mp->ma_keys);
1079 ep = &ep0[mp->ma_keys->dk_nentries];
1080 dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
1081 Py_INCREF(key);
1082 ep->me_key = key;
1083 ep->me_hash = hash;
1084 if (mp->ma_values) {
1085 assert (mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
1086 mp->ma_values[mp->ma_keys->dk_nentries] = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001087 }
1088 else {
Victor Stinner742da042016-09-07 17:40:12 -07001089 ep->me_value = value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001090 }
1091 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001092 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07001093 mp->ma_keys->dk_usable--;
1094 mp->ma_keys->dk_nentries++;
1095 assert(mp->ma_keys->dk_usable >= 0);
1096 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001097 }
Victor Stinner742da042016-09-07 17:40:12 -07001098
1099 assert(value_addr != NULL);
1100
1101 old_value = *value_addr;
1102 if (old_value != NULL) {
1103 *value_addr = value;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001104 mp->ma_version_tag = DICT_NEXT_VERSION();
1105
Victor Stinner742da042016-09-07 17:40:12 -07001106 Py_DECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
1107 return 0;
1108 }
1109
1110 /* pending state */
1111 assert(_PyDict_HasSplitTable(mp));
1112 assert(ix == mp->ma_used);
1113 *value_addr = value;
1114 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001115 mp->ma_version_tag = DICT_NEXT_VERSION();
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001116 return 0;
Antoine Pitroue965d972012-02-27 00:45:12 +01001117}
1118
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001119/*
1120Internal routine used by dictresize() to insert an item which is
1121known to be absent from the dict. This routine also assumes that
1122the dict contains no deleted entries. Besides the performance benefit,
1123using insertdict() in dictresize() is dangerous (SF bug #1456209).
1124Note that no refcounts are changed by this routine; if needed, the caller
1125is responsible for incref'ing `key` and `value`.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001126Neither mp->ma_used nor k->dk_usable are modified by this routine; the caller
1127must set them correctly
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001128*/
1129static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001130insertdict_clean(PyDictObject *mp, PyObject *key, Py_hash_t hash,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 PyObject *value)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001132{
Victor Stinner742da042016-09-07 17:40:12 -07001133 size_t i, perturb;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001134 PyDictKeysObject *k = mp->ma_keys;
1135 size_t mask = (size_t)DK_SIZE(k)-1;
Victor Stinner742da042016-09-07 17:40:12 -07001136 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001137 PyDictKeyEntry *ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001138
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001139 assert(k->dk_lookup != NULL);
1140 assert(value != NULL);
1141 assert(key != NULL);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001142 assert(PyUnicode_CheckExact(key) || k->dk_lookup == lookdict);
1143 i = hash & mask;
Victor Stinner742da042016-09-07 17:40:12 -07001144 for (perturb = hash; dk_get_index(k, i) != DKIX_EMPTY;
1145 perturb >>= PERTURB_SHIFT) {
1146 i = mask & ((i << 2) + i + perturb + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 }
Victor Stinner742da042016-09-07 17:40:12 -07001148 ep = &ep0[k->dk_nentries];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 assert(ep->me_value == NULL);
Victor Stinner742da042016-09-07 17:40:12 -07001150 dk_set_index(k, i, k->dk_nentries);
1151 k->dk_nentries++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 ep->me_key = key;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001153 ep->me_hash = hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 ep->me_value = value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001155}
1156
1157/*
1158Restructure the table by allocating a new table and reinserting all
1159items again. When entries have been deleted, the new table may
1160actually be smaller than the old one.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001161If a table is split (its keys and hashes are shared, its values are not),
1162then the values are temporarily copied into the table, it is resized as
1163a combined table, then the me_value slots in the old table are NULLed out.
1164After resizing a table is always combined,
1165but can be resplit by make_keys_shared().
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001166*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001167static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001168dictresize(PyDictObject *mp, Py_ssize_t minused)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001169{
Victor Stinner742da042016-09-07 17:40:12 -07001170 Py_ssize_t i, newsize;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001171 PyDictKeysObject *oldkeys;
1172 PyObject **oldvalues;
Victor Stinner742da042016-09-07 17:40:12 -07001173 PyDictKeyEntry *ep0;
Tim Peters91a364d2001-05-19 07:04:38 +00001174
Victor Stinner742da042016-09-07 17:40:12 -07001175 /* Find the smallest table size > minused. */
1176 for (newsize = PyDict_MINSIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 newsize <= minused && newsize > 0;
1178 newsize <<= 1)
1179 ;
1180 if (newsize <= 0) {
1181 PyErr_NoMemory();
1182 return -1;
1183 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001184 oldkeys = mp->ma_keys;
1185 oldvalues = mp->ma_values;
1186 /* Allocate a new table. */
1187 mp->ma_keys = new_keys_object(newsize);
1188 if (mp->ma_keys == NULL) {
1189 mp->ma_keys = oldkeys;
1190 return -1;
1191 }
1192 if (oldkeys->dk_lookup == lookdict)
1193 mp->ma_keys->dk_lookup = lookdict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001194 mp->ma_values = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001195 ep0 = DK_ENTRIES(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001196 /* Main loop below assumes we can transfer refcount to new keys
1197 * and that value is stored in me_value.
1198 * Increment ref-counts and copy values here to compensate
1199 * This (resizing a split table) should be relatively rare */
1200 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001201 for (i = 0; i < oldkeys->dk_nentries; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001202 if (oldvalues[i] != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001203 Py_INCREF(ep0[i].me_key);
1204 ep0[i].me_value = oldvalues[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 }
1207 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001208 /* Main loop */
Victor Stinner742da042016-09-07 17:40:12 -07001209 for (i = 0; i < oldkeys->dk_nentries; i++) {
1210 PyDictKeyEntry *ep = &ep0[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001211 if (ep->me_value != NULL) {
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001212 insertdict_clean(mp, ep->me_key, ep->me_hash, ep->me_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001215 mp->ma_keys->dk_usable -= mp->ma_used;
1216 if (oldvalues != NULL) {
1217 /* NULL out me_value slot in oldkeys, in case it was shared */
Victor Stinner742da042016-09-07 17:40:12 -07001218 for (i = 0; i < oldkeys->dk_nentries; i++)
1219 ep0[i].me_value = NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001220 DK_DECREF(oldkeys);
Victor Stinner742da042016-09-07 17:40:12 -07001221 if (oldvalues != empty_values) {
1222 free_values(oldvalues);
1223 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001224 }
1225 else {
1226 assert(oldkeys->dk_lookup != lookdict_split);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001227 assert(oldkeys->dk_refcnt == 1);
Raymond Hettingerce5179f2016-01-31 08:56:21 -08001228 DK_DEBUG_DECREF PyObject_FREE(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001229 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001231}
1232
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001233/* Returns NULL if unable to split table.
1234 * A NULL return does not necessarily indicate an error */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001235static PyDictKeysObject *
1236make_keys_shared(PyObject *op)
1237{
1238 Py_ssize_t i;
1239 Py_ssize_t size;
1240 PyDictObject *mp = (PyDictObject *)op;
1241
Benjamin Peterson15ee8212012-04-24 14:44:18 -04001242 if (!PyDict_CheckExact(op))
1243 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001244 if (!_PyDict_HasSplitTable(mp)) {
1245 PyDictKeyEntry *ep0;
1246 PyObject **values;
1247 assert(mp->ma_keys->dk_refcnt == 1);
1248 if (mp->ma_keys->dk_lookup == lookdict) {
1249 return NULL;
1250 }
1251 else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
1252 /* Remove dummy keys */
1253 if (dictresize(mp, DK_SIZE(mp->ma_keys)))
1254 return NULL;
1255 }
1256 assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
1257 /* Copy values into a new array */
Victor Stinner742da042016-09-07 17:40:12 -07001258 ep0 = DK_ENTRIES(mp->ma_keys);
1259 size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001260 values = new_values(size);
1261 if (values == NULL) {
1262 PyErr_SetString(PyExc_MemoryError,
1263 "Not enough memory to allocate new values array");
1264 return NULL;
1265 }
1266 for (i = 0; i < size; i++) {
1267 values[i] = ep0[i].me_value;
1268 ep0[i].me_value = NULL;
1269 }
1270 mp->ma_keys->dk_lookup = lookdict_split;
1271 mp->ma_values = values;
1272 }
1273 DK_INCREF(mp->ma_keys);
1274 return mp->ma_keys;
1275}
Christian Heimes99170a52007-12-19 02:07:34 +00001276
1277PyObject *
1278_PyDict_NewPresized(Py_ssize_t minused)
1279{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001280 Py_ssize_t newsize;
1281 PyDictKeysObject *new_keys;
Victor Stinner742da042016-09-07 17:40:12 -07001282 for (newsize = PyDict_MINSIZE;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001283 newsize <= minused && newsize > 0;
1284 newsize <<= 1)
1285 ;
1286 new_keys = new_keys_object(newsize);
1287 if (new_keys == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001289 return new_dict(new_keys, NULL);
Christian Heimes99170a52007-12-19 02:07:34 +00001290}
1291
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001292/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
1293 * that may occur (originally dicts supported only string keys, and exceptions
1294 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001295 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001296 * (suppressed) occurred while computing the key's hash, or that some error
1297 * (suppressed) occurred when comparing keys in the dict's internal probe
1298 * sequence. A nasty example of the latter is when a Python-coded comparison
1299 * function hits a stack-depth error, which can cause this to return NULL
1300 * even if the key is present.
1301 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001302PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001303PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001304{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001305 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001306 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 PyDictObject *mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 PyThreadState *tstate;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001309 PyObject **value_addr;
1310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 if (!PyDict_Check(op))
1312 return NULL;
1313 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001314 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 {
1316 hash = PyObject_Hash(key);
1317 if (hash == -1) {
1318 PyErr_Clear();
1319 return NULL;
1320 }
1321 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 /* We can arrive here with a NULL tstate during initialization: try
1324 running "python -Wi" for an example related to string interning.
1325 Let's just hope that no exception occurs then... This must be
1326 _PyThreadState_Current and not PyThreadState_GET() because in debug
1327 mode, the latter complains if tstate is NULL. */
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001328 tstate = _PyThreadState_UncheckedGet();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 if (tstate != NULL && tstate->curexc_type != NULL) {
1330 /* preserve the existing exception */
1331 PyObject *err_type, *err_value, *err_tb;
1332 PyErr_Fetch(&err_type, &err_value, &err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001333 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 /* ignore errors */
1335 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001336 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 return NULL;
1338 }
1339 else {
Victor Stinner742da042016-09-07 17:40:12 -07001340 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1341 if (ix < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 PyErr_Clear();
1343 return NULL;
1344 }
1345 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001346 return *value_addr;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001347}
1348
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001349PyObject *
1350_PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1351{
Victor Stinner742da042016-09-07 17:40:12 -07001352 Py_ssize_t ix;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001353 PyDictObject *mp = (PyDictObject *)op;
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001354 PyThreadState *tstate;
1355 PyObject **value_addr;
1356
1357 if (!PyDict_Check(op))
1358 return NULL;
1359
1360 /* We can arrive here with a NULL tstate during initialization: try
1361 running "python -Wi" for an example related to string interning.
1362 Let's just hope that no exception occurs then... This must be
1363 _PyThreadState_Current and not PyThreadState_GET() because in debug
1364 mode, the latter complains if tstate is NULL. */
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001365 tstate = _PyThreadState_UncheckedGet();
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001366 if (tstate != NULL && tstate->curexc_type != NULL) {
1367 /* preserve the existing exception */
1368 PyObject *err_type, *err_value, *err_tb;
1369 PyErr_Fetch(&err_type, &err_value, &err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001370 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001371 /* ignore errors */
1372 PyErr_Restore(err_type, err_value, err_tb);
Victor Stinner742da042016-09-07 17:40:12 -07001373 if (ix == DKIX_EMPTY)
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001374 return NULL;
1375 }
1376 else {
Victor Stinner742da042016-09-07 17:40:12 -07001377 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1378 if (ix == DKIX_EMPTY) {
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001379 PyErr_Clear();
1380 return NULL;
1381 }
1382 }
1383 return *value_addr;
1384}
1385
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001386/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
1387 This returns NULL *with* an exception set if an exception occurred.
1388 It returns NULL *without* an exception set if the key wasn't present.
1389*/
1390PyObject *
1391PyDict_GetItemWithError(PyObject *op, PyObject *key)
1392{
Victor Stinner742da042016-09-07 17:40:12 -07001393 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001394 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 PyDictObject*mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001396 PyObject **value_addr;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 if (!PyDict_Check(op)) {
1399 PyErr_BadInternalCall();
1400 return NULL;
1401 }
1402 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001403 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 {
1405 hash = PyObject_Hash(key);
1406 if (hash == -1) {
1407 return NULL;
1408 }
1409 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001410
Victor Stinner742da042016-09-07 17:40:12 -07001411 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1412 if (ix < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001414 return *value_addr;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001415}
1416
Brett Cannonfd074152012-04-14 14:10:13 -04001417PyObject *
1418_PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
1419{
1420 PyObject *kv;
1421 kv = _PyUnicode_FromId(key); /* borrowed */
1422 if (kv == NULL)
1423 return NULL;
1424 return PyDict_GetItemWithError(dp, kv);
1425}
1426
Victor Stinnerb4efc962015-11-20 09:24:02 +01001427/* Fast version of global value lookup (LOAD_GLOBAL).
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001428 * Lookup in globals, then builtins.
Victor Stinnerb4efc962015-11-20 09:24:02 +01001429 *
1430 * Raise an exception and return NULL if an error occurred (ex: computing the
1431 * key hash failed, key comparison failed, ...). Return NULL if the key doesn't
1432 * exist. Return the value if the key exists.
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001433 */
1434PyObject *
1435_PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001436{
Victor Stinner742da042016-09-07 17:40:12 -07001437 Py_ssize_t ix;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001438 Py_hash_t hash;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001439 PyObject **value_addr;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001440
1441 if (!PyUnicode_CheckExact(key) ||
1442 (hash = ((PyASCIIObject *) key)->hash) == -1)
1443 {
1444 hash = PyObject_Hash(key);
1445 if (hash == -1)
1446 return NULL;
Antoine Pitroue965d972012-02-27 00:45:12 +01001447 }
Victor Stinnerb4efc962015-11-20 09:24:02 +01001448
1449 /* namespace 1: globals */
Victor Stinner742da042016-09-07 17:40:12 -07001450 ix = globals->ma_keys->dk_lookup(globals, key, hash, &value_addr, NULL);
1451 if (ix == DKIX_ERROR)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001452 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001453 if (ix != DKIX_EMPTY && *value_addr != NULL)
1454 return *value_addr;
Victor Stinnerb4efc962015-11-20 09:24:02 +01001455
1456 /* namespace 2: builtins */
Victor Stinner742da042016-09-07 17:40:12 -07001457 ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value_addr, NULL);
1458 if (ix < 0)
Victor Stinnerb4efc962015-11-20 09:24:02 +01001459 return NULL;
1460 return *value_addr;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001461}
1462
Antoine Pitroue965d972012-02-27 00:45:12 +01001463/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
1464 * dictionary if it's merely replacing the value for an existing key.
1465 * This means that it's safe to loop over a dictionary with PyDict_Next()
1466 * and occasionally replace a value -- but you can't insert new keys or
1467 * remove them.
1468 */
1469int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001470PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001471{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001472 PyDictObject *mp;
1473 Py_hash_t hash;
Antoine Pitroue965d972012-02-27 00:45:12 +01001474 if (!PyDict_Check(op)) {
1475 PyErr_BadInternalCall();
1476 return -1;
1477 }
1478 assert(key);
1479 assert(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001480 mp = (PyDictObject *)op;
1481 if (!PyUnicode_CheckExact(key) ||
1482 (hash = ((PyASCIIObject *) key)->hash) == -1)
1483 {
Antoine Pitroue965d972012-02-27 00:45:12 +01001484 hash = PyObject_Hash(key);
1485 if (hash == -1)
1486 return -1;
1487 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001488
1489 /* insertdict() handles any resizing that might be necessary */
1490 return insertdict(mp, key, hash, value);
Antoine Pitroue965d972012-02-27 00:45:12 +01001491}
1492
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001493int
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001494_PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
1495 Py_hash_t hash)
1496{
1497 PyDictObject *mp;
1498
1499 if (!PyDict_Check(op)) {
1500 PyErr_BadInternalCall();
1501 return -1;
1502 }
1503 assert(key);
1504 assert(value);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001505 assert(hash != -1);
Raymond Hettinger4b74fba2014-05-03 16:32:11 -07001506 mp = (PyDictObject *)op;
1507
1508 /* insertdict() handles any resizing that might be necessary */
1509 return insertdict(mp, key, hash, value);
1510}
1511
1512int
Tim Peters1f5871e2000-07-04 17:44:48 +00001513PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001514{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001515 Py_hash_t hash;
Guido van Rossumd7047b31995-01-02 19:07:15 +00001516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 assert(key);
1518 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001519 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 hash = PyObject_Hash(key);
1521 if (hash == -1)
1522 return -1;
1523 }
Victor Stinner742da042016-09-07 17:40:12 -07001524
1525 return _PyDict_DelItem_KnownHash(op, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001526}
1527
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001528int
1529_PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
1530{
Victor Stinner742da042016-09-07 17:40:12 -07001531 Py_ssize_t hashpos, ix;
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001532 PyDictObject *mp;
1533 PyDictKeyEntry *ep;
1534 PyObject *old_key, *old_value;
1535 PyObject **value_addr;
1536
1537 if (!PyDict_Check(op)) {
1538 PyErr_BadInternalCall();
1539 return -1;
1540 }
1541 assert(key);
1542 assert(hash != -1);
1543 mp = (PyDictObject *)op;
Victor Stinner742da042016-09-07 17:40:12 -07001544 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1545 if (ix == DKIX_ERROR)
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001546 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07001547 if (ix == DKIX_EMPTY || *value_addr == NULL) {
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001548 _PyErr_SetKeyError(key);
1549 return -1;
1550 }
Victor Stinner742da042016-09-07 17:40:12 -07001551 assert(dk_get_index(mp->ma_keys, hashpos) == ix);
Victor Stinner78601a32016-09-09 19:28:36 -07001552
1553 // Split table doesn't allow deletion. Combine it.
1554 if (_PyDict_HasSplitTable(mp)) {
1555 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1556 return -1;
1557 }
1558 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1559 assert(ix >= 0);
1560 }
1561
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001562 old_value = *value_addr;
Victor Stinner78601a32016-09-09 19:28:36 -07001563 assert(old_value != NULL);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001564 *value_addr = NULL;
1565 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001566 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner78601a32016-09-09 19:28:36 -07001567 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1568 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1569 ENSURE_ALLOWS_DELETIONS(mp);
1570 old_key = ep->me_key;
1571 ep->me_key = NULL;
1572 Py_DECREF(old_key);
Serhiy Storchakab9d98d52015-10-02 12:47:11 +03001573 Py_DECREF(old_value);
1574 return 0;
1575}
1576
Guido van Rossum25831651993-05-19 14:50:45 +00001577void
Tim Peters1f5871e2000-07-04 17:44:48 +00001578PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 PyDictObject *mp;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001581 PyDictKeysObject *oldkeys;
1582 PyObject **oldvalues;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 if (!PyDict_Check(op))
1586 return;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001587 mp = ((PyDictObject *)op);
1588 oldkeys = mp->ma_keys;
1589 oldvalues = mp->ma_values;
1590 if (oldvalues == empty_values)
1591 return;
1592 /* Empty the dict... */
1593 DK_INCREF(Py_EMPTY_KEYS);
1594 mp->ma_keys = Py_EMPTY_KEYS;
1595 mp->ma_values = empty_values;
1596 mp->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001597 mp->ma_version_tag = DICT_NEXT_VERSION();
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001598 /* ...then clear the keys and values */
1599 if (oldvalues != NULL) {
Victor Stinner742da042016-09-07 17:40:12 -07001600 n = oldkeys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001601 for (i = 0; i < n; i++)
1602 Py_CLEAR(oldvalues[i]);
1603 free_values(oldvalues);
1604 DK_DECREF(oldkeys);
1605 }
1606 else {
1607 assert(oldkeys->dk_refcnt == 1);
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001608 DK_DECREF(oldkeys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001609 }
1610}
1611
1612/* Returns -1 if no more items (or op is not a dict),
1613 * index of item otherwise. Stores value in pvalue
1614 */
Benjamin Peterson73222252016-09-08 09:58:47 -07001615static inline Py_ssize_t
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001616dict_next(PyObject *op, Py_ssize_t i, PyObject **pvalue)
1617{
Victor Stinner742da042016-09-07 17:40:12 -07001618 Py_ssize_t n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001619 PyDictObject *mp;
Victor Stinner742da042016-09-07 17:40:12 -07001620 PyObject **value_ptr = NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001621
1622 if (!PyDict_Check(op))
1623 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001625 if (i < 0)
1626 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07001627
1628 n = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001629 if (mp->ma_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001630 for (; i < n; i++) {
1631 value_ptr = &mp->ma_values[i];
1632 if (*value_ptr != NULL)
1633 break;
1634 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001636 else {
Victor Stinner742da042016-09-07 17:40:12 -07001637 PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
1638 for (; i < n; i++) {
1639 value_ptr = &ep0[i].me_value;
1640 if (*value_ptr != NULL)
1641 break;
1642 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 }
Victor Stinner742da042016-09-07 17:40:12 -07001644 if (i >= n)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001645 return -1;
1646 if (pvalue)
1647 *pvalue = *value_ptr;
1648 return i;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001649}
1650
Tim Peters080c88b2003-02-15 03:01:11 +00001651/*
1652 * Iterate over a dict. Use like so:
1653 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001654 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +00001655 * PyObject *key, *value;
1656 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +00001657 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Tim Peters080c88b2003-02-15 03:01:11 +00001658 * Refer to borrowed references in key and value.
1659 * }
1660 *
1661 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +00001662 * mutates the dict. One exception: it is safe if the loop merely changes
1663 * the values associated with the keys (but doesn't insert new keys or
1664 * delete keys), via PyDict_SetItem().
1665 */
Guido van Rossum25831651993-05-19 14:50:45 +00001666int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001667PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001668{
Victor Stinner742da042016-09-07 17:40:12 -07001669 PyDictObject *mp = (PyDictObject*)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001670 Py_ssize_t i = dict_next(op, *ppos, pvalue);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 if (i < 0)
1672 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001673 mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 *ppos = i+1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 if (pkey)
Victor Stinner742da042016-09-07 17:40:12 -07001676 *pkey = DK_ENTRIES(mp->ma_keys)[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001678}
1679
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001680/* Internal version of PyDict_Next that returns a hash value in addition
1681 * to the key and value.
1682 */
Thomas Wouterscf297e42007-02-23 15:07:44 +00001683int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001684_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
1685 PyObject **pvalue, Py_hash_t *phash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001686{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001687 PyDictObject *mp;
Victor Stinner742da042016-09-07 17:40:12 -07001688 PyDictKeyEntry *ep0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001689 Py_ssize_t i = dict_next(op, *ppos, pvalue);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 if (i < 0)
1691 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001692 mp = (PyDictObject *)op;
Victor Stinner742da042016-09-07 17:40:12 -07001693 ep0 = DK_ENTRIES(mp->ma_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 *ppos = i+1;
Victor Stinner742da042016-09-07 17:40:12 -07001695 *phash = ep0[i].me_hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 if (pkey)
Victor Stinner742da042016-09-07 17:40:12 -07001697 *pkey = ep0[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 return 1;
Thomas Wouterscf297e42007-02-23 15:07:44 +00001699}
1700
Eric Snow96c6af92015-05-29 22:21:39 -06001701/* Internal version of dict.pop(). */
1702PyObject *
1703_PyDict_Pop(PyDictObject *mp, PyObject *key, PyObject *deflt)
1704{
1705 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07001706 Py_ssize_t ix, hashpos;
Eric Snow96c6af92015-05-29 22:21:39 -06001707 PyObject *old_value, *old_key;
1708 PyDictKeyEntry *ep;
1709 PyObject **value_addr;
1710
1711 if (mp->ma_used == 0) {
1712 if (deflt) {
1713 Py_INCREF(deflt);
1714 return deflt;
1715 }
1716 _PyErr_SetKeyError(key);
1717 return NULL;
1718 }
1719 if (!PyUnicode_CheckExact(key) ||
1720 (hash = ((PyASCIIObject *) key)->hash) == -1) {
1721 hash = PyObject_Hash(key);
1722 if (hash == -1)
1723 return NULL;
1724 }
Victor Stinner742da042016-09-07 17:40:12 -07001725 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1726 if (ix == DKIX_ERROR)
Eric Snow96c6af92015-05-29 22:21:39 -06001727 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001728 if (ix == DKIX_EMPTY) {
Eric Snow96c6af92015-05-29 22:21:39 -06001729 if (deflt) {
1730 Py_INCREF(deflt);
1731 return deflt;
1732 }
1733 _PyErr_SetKeyError(key);
1734 return NULL;
1735 }
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001736
Victor Stinner78601a32016-09-09 19:28:36 -07001737 // Split table doesn't allow deletion. Combine it.
1738 if (_PyDict_HasSplitTable(mp)) {
1739 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
1740 return NULL;
1741 }
1742 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
1743 assert(ix >= 0);
1744 }
1745
Victor Stinner742da042016-09-07 17:40:12 -07001746 old_value = *value_addr;
Victor Stinner78601a32016-09-09 19:28:36 -07001747 assert(old_value != NULL);
Eric Snow96c6af92015-05-29 22:21:39 -06001748 *value_addr = NULL;
1749 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07001750 mp->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner78601a32016-09-09 19:28:36 -07001751 dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
1752 ep = &DK_ENTRIES(mp->ma_keys)[ix];
1753 ENSURE_ALLOWS_DELETIONS(mp);
1754 old_key = ep->me_key;
1755 ep->me_key = NULL;
1756 Py_DECREF(old_key);
Eric Snow96c6af92015-05-29 22:21:39 -06001757 return old_value;
1758}
1759
1760/* Internal version of dict.from_keys(). It is subclass-friendly. */
1761PyObject *
1762_PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
1763{
1764 PyObject *it; /* iter(iterable) */
1765 PyObject *key;
1766 PyObject *d;
1767 int status;
1768
1769 d = PyObject_CallObject(cls, NULL);
1770 if (d == NULL)
1771 return NULL;
1772
1773 if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
1774 if (PyDict_CheckExact(iterable)) {
1775 PyDictObject *mp = (PyDictObject *)d;
1776 PyObject *oldvalue;
1777 Py_ssize_t pos = 0;
1778 PyObject *key;
1779 Py_hash_t hash;
1780
Victor Stinner742da042016-09-07 17:40:12 -07001781 if (dictresize(mp, ESTIMATE_SIZE(Py_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001782 Py_DECREF(d);
1783 return NULL;
1784 }
1785
1786 while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
1787 if (insertdict(mp, key, hash, value)) {
1788 Py_DECREF(d);
1789 return NULL;
1790 }
1791 }
1792 return d;
1793 }
1794 if (PyAnySet_CheckExact(iterable)) {
1795 PyDictObject *mp = (PyDictObject *)d;
1796 Py_ssize_t pos = 0;
1797 PyObject *key;
1798 Py_hash_t hash;
1799
Victor Stinner742da042016-09-07 17:40:12 -07001800 if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) {
Eric Snow96c6af92015-05-29 22:21:39 -06001801 Py_DECREF(d);
1802 return NULL;
1803 }
1804
1805 while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
1806 if (insertdict(mp, key, hash, value)) {
1807 Py_DECREF(d);
1808 return NULL;
1809 }
1810 }
1811 return d;
1812 }
1813 }
1814
1815 it = PyObject_GetIter(iterable);
1816 if (it == NULL){
1817 Py_DECREF(d);
1818 return NULL;
1819 }
1820
1821 if (PyDict_CheckExact(d)) {
1822 while ((key = PyIter_Next(it)) != NULL) {
1823 status = PyDict_SetItem(d, key, value);
1824 Py_DECREF(key);
1825 if (status < 0)
1826 goto Fail;
1827 }
1828 } else {
1829 while ((key = PyIter_Next(it)) != NULL) {
1830 status = PyObject_SetItem(d, key, value);
1831 Py_DECREF(key);
1832 if (status < 0)
1833 goto Fail;
1834 }
1835 }
1836
1837 if (PyErr_Occurred())
1838 goto Fail;
1839 Py_DECREF(it);
1840 return d;
1841
1842Fail:
1843 Py_DECREF(it);
1844 Py_DECREF(d);
1845 return NULL;
1846}
1847
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001848/* Methods */
1849
1850static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001851dict_dealloc(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001852{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001853 PyObject **values = mp->ma_values;
1854 PyDictKeysObject *keys = mp->ma_keys;
1855 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 PyObject_GC_UnTrack(mp);
1857 Py_TRASHCAN_SAFE_BEGIN(mp)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001858 if (values != NULL) {
1859 if (values != empty_values) {
Victor Stinner742da042016-09-07 17:40:12 -07001860 for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001861 Py_XDECREF(values[i]);
1862 }
1863 free_values(values);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001865 DK_DECREF(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 }
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02001867 else if (keys != NULL) {
Antoine Pitrou2d169b22012-05-12 23:43:44 +02001868 assert(keys->dk_refcnt == 1);
1869 DK_DECREF(keys);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001870 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
1872 free_list[numfree++] = mp;
1873 else
1874 Py_TYPE(mp)->tp_free((PyObject *)mp);
1875 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001876}
1877
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001878
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001879static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001880dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 Py_ssize_t i;
Victor Stinnerf91929b2013-11-19 13:07:38 +01001883 PyObject *key = NULL, *value = NULL;
1884 _PyUnicodeWriter writer;
1885 int first;
Guido van Rossum255443b1998-04-10 22:47:14 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 i = Py_ReprEnter((PyObject *)mp);
1888 if (i != 0) {
1889 return i > 0 ? PyUnicode_FromString("{...}") : NULL;
1890 }
Guido van Rossum255443b1998-04-10 22:47:14 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 if (mp->ma_used == 0) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01001893 Py_ReprLeave((PyObject *)mp);
1894 return PyUnicode_FromString("{}");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 }
Tim Petersa7259592001-06-16 05:11:17 +00001896
Victor Stinnerf91929b2013-11-19 13:07:38 +01001897 _PyUnicodeWriter_Init(&writer);
1898 writer.overallocate = 1;
1899 /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
1900 writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +00001901
Victor Stinnerf91929b2013-11-19 13:07:38 +01001902 if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
1903 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 /* Do repr() on each key+value pair, and insert ": " between them.
1906 Note that repr may mutate the dict. */
1907 i = 0;
Victor Stinnerf91929b2013-11-19 13:07:38 +01001908 first = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Victor Stinnerf91929b2013-11-19 13:07:38 +01001910 PyObject *s;
1911 int res;
1912
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001913 /* Prevent repr from deleting key or value during key format. */
1914 Py_INCREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 Py_INCREF(value);
Victor Stinnerf97dfd72013-07-18 01:00:45 +02001916
Victor Stinnerf91929b2013-11-19 13:07:38 +01001917 if (!first) {
1918 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
1919 goto error;
1920 }
1921 first = 0;
1922
1923 s = PyObject_Repr(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 if (s == NULL)
Victor Stinnerf91929b2013-11-19 13:07:38 +01001925 goto error;
1926 res = _PyUnicodeWriter_WriteStr(&writer, s);
1927 Py_DECREF(s);
1928 if (res < 0)
1929 goto error;
1930
1931 if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
1932 goto error;
1933
1934 s = PyObject_Repr(value);
1935 if (s == NULL)
1936 goto error;
1937 res = _PyUnicodeWriter_WriteStr(&writer, s);
1938 Py_DECREF(s);
1939 if (res < 0)
1940 goto error;
1941
1942 Py_CLEAR(key);
1943 Py_CLEAR(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 }
Tim Petersa7259592001-06-16 05:11:17 +00001945
Victor Stinnerf91929b2013-11-19 13:07:38 +01001946 writer.overallocate = 0;
1947 if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
1948 goto error;
Tim Petersa7259592001-06-16 05:11:17 +00001949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 Py_ReprLeave((PyObject *)mp);
Victor Stinnerf91929b2013-11-19 13:07:38 +01001951
1952 return _PyUnicodeWriter_Finish(&writer);
1953
1954error:
1955 Py_ReprLeave((PyObject *)mp);
1956 _PyUnicodeWriter_Dealloc(&writer);
1957 Py_XDECREF(key);
1958 Py_XDECREF(value);
1959 return NULL;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001960}
1961
Martin v. Löwis18e16552006-02-15 17:27:45 +00001962static Py_ssize_t
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001963dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 return mp->ma_used;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001966}
1967
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001968static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001969dict_subscript(PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 PyObject *v;
Victor Stinner742da042016-09-07 17:40:12 -07001972 Py_ssize_t ix;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001973 Py_hash_t hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001974 PyObject **value_addr;
1975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001977 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 hash = PyObject_Hash(key);
1979 if (hash == -1)
1980 return NULL;
1981 }
Victor Stinner742da042016-09-07 17:40:12 -07001982 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
1983 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07001985 if (ix == DKIX_EMPTY || *value_addr == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 if (!PyDict_CheckExact(mp)) {
1987 /* Look up __missing__ method if we're a subclass. */
1988 PyObject *missing, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05001989 _Py_IDENTIFIER(__missing__);
1990 missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 if (missing != NULL) {
1992 res = PyObject_CallFunctionObjArgs(missing,
1993 key, NULL);
1994 Py_DECREF(missing);
1995 return res;
1996 }
1997 else if (PyErr_Occurred())
1998 return NULL;
1999 }
Raymond Hettinger69492da2013-09-02 15:59:26 -07002000 _PyErr_SetKeyError(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 return NULL;
2002 }
Victor Stinner742da042016-09-07 17:40:12 -07002003 v = *value_addr;
2004 Py_INCREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002006}
2007
2008static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002009dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 if (w == NULL)
2012 return PyDict_DelItem((PyObject *)mp, v);
2013 else
2014 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002015}
2016
Guido van Rossuma9e7a811997-05-13 21:02:11 +00002017static PyMappingMethods dict_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 (lenfunc)dict_length, /*mp_length*/
2019 (binaryfunc)dict_subscript, /*mp_subscript*/
2020 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002021};
2022
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002023static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002024dict_keys(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002025{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002026 PyObject *v;
2027 Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002028 PyDictKeyEntry *ep;
2029 Py_ssize_t size, n, offset;
2030 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002031
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002032 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 n = mp->ma_used;
2034 v = PyList_New(n);
2035 if (v == NULL)
2036 return NULL;
2037 if (n != mp->ma_used) {
2038 /* Durnit. The allocations caused the dict to resize.
2039 * Just start over, this shouldn't normally happen.
2040 */
2041 Py_DECREF(v);
2042 goto again;
2043 }
Victor Stinner742da042016-09-07 17:40:12 -07002044 ep = DK_ENTRIES(mp->ma_keys);
2045 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002046 if (mp->ma_values) {
2047 value_ptr = mp->ma_values;
2048 offset = sizeof(PyObject *);
2049 }
2050 else {
2051 value_ptr = &ep[0].me_value;
2052 offset = sizeof(PyDictKeyEntry);
2053 }
2054 for (i = 0, j = 0; i < size; i++) {
2055 if (*value_ptr != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 PyObject *key = ep[i].me_key;
2057 Py_INCREF(key);
2058 PyList_SET_ITEM(v, j, key);
2059 j++;
2060 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002061 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 }
2063 assert(j == n);
2064 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002065}
2066
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002067static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002068dict_values(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002069{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002070 PyObject *v;
2071 Py_ssize_t i, j;
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002072 PyDictKeyEntry *ep;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002073 Py_ssize_t size, n, offset;
2074 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002075
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002076 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 n = mp->ma_used;
2078 v = PyList_New(n);
2079 if (v == NULL)
2080 return NULL;
2081 if (n != mp->ma_used) {
2082 /* Durnit. The allocations caused the dict to resize.
2083 * Just start over, this shouldn't normally happen.
2084 */
2085 Py_DECREF(v);
2086 goto again;
2087 }
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002088 ep = DK_ENTRIES(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002089 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002090 if (mp->ma_values) {
2091 value_ptr = mp->ma_values;
2092 offset = sizeof(PyObject *);
2093 }
2094 else {
Benjamin Petersonf0acae22016-09-08 09:50:08 -07002095 value_ptr = &ep[0].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002096 offset = sizeof(PyDictKeyEntry);
2097 }
2098 for (i = 0, j = 0; i < size; i++) {
2099 PyObject *value = *value_ptr;
2100 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2101 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 Py_INCREF(value);
2103 PyList_SET_ITEM(v, j, value);
2104 j++;
2105 }
2106 }
2107 assert(j == n);
2108 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002109}
2110
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002111static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002112dict_items(PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002113{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002114 PyObject *v;
2115 Py_ssize_t i, j, n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002116 Py_ssize_t size, offset;
2117 PyObject *item, *key;
2118 PyDictKeyEntry *ep;
2119 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 /* Preallocate the list of tuples, to avoid allocations during
2122 * the loop over the items, which could trigger GC, which
2123 * could resize the dict. :-(
2124 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00002125 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 n = mp->ma_used;
2127 v = PyList_New(n);
2128 if (v == NULL)
2129 return NULL;
2130 for (i = 0; i < n; i++) {
2131 item = PyTuple_New(2);
2132 if (item == NULL) {
2133 Py_DECREF(v);
2134 return NULL;
2135 }
2136 PyList_SET_ITEM(v, i, item);
2137 }
2138 if (n != mp->ma_used) {
2139 /* Durnit. The allocations caused the dict to resize.
2140 * Just start over, this shouldn't normally happen.
2141 */
2142 Py_DECREF(v);
2143 goto again;
2144 }
2145 /* Nothing we do below makes any function calls. */
Victor Stinner742da042016-09-07 17:40:12 -07002146 ep = DK_ENTRIES(mp->ma_keys);
2147 size = mp->ma_keys->dk_nentries;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002148 if (mp->ma_values) {
2149 value_ptr = mp->ma_values;
2150 offset = sizeof(PyObject *);
2151 }
2152 else {
2153 value_ptr = &ep[0].me_value;
2154 offset = sizeof(PyDictKeyEntry);
2155 }
2156 for (i = 0, j = 0; i < size; i++) {
2157 PyObject *value = *value_ptr;
2158 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
2159 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 key = ep[i].me_key;
2161 item = PyList_GET_ITEM(v, j);
2162 Py_INCREF(key);
2163 PyTuple_SET_ITEM(item, 0, key);
2164 Py_INCREF(value);
2165 PyTuple_SET_ITEM(item, 1, value);
2166 j++;
2167 }
2168 }
2169 assert(j == n);
2170 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00002171}
2172
Larry Hastings5c661892014-01-24 06:17:25 -08002173/*[clinic input]
2174@classmethod
2175dict.fromkeys
Larry Hastings5c661892014-01-24 06:17:25 -08002176 iterable: object
2177 value: object=None
2178 /
2179
2180Returns a new dict with keys from iterable and values equal to value.
2181[clinic start generated code]*/
2182
Larry Hastings5c661892014-01-24 06:17:25 -08002183static PyObject *
2184dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002185/*[clinic end generated code: output=8fb98e4b10384999 input=b85a667f9bf4669d]*/
Larry Hastings5c661892014-01-24 06:17:25 -08002186{
Eric Snow96c6af92015-05-29 22:21:39 -06002187 return _PyDict_FromKeys((PyObject *)type, iterable, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002188}
2189
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002190static int
Victor Stinner742da042016-09-07 17:40:12 -07002191dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
2192 const char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 PyObject *arg = NULL;
2195 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
2198 result = -1;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 else if (arg != NULL) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02002201 _Py_IDENTIFIER(keys);
2202 if (_PyObject_HasAttrId(arg, &PyId_keys))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 result = PyDict_Merge(self, arg, 1);
2204 else
2205 result = PyDict_MergeFromSeq2(self, arg, 1);
2206 }
2207 if (result == 0 && kwds != NULL) {
2208 if (PyArg_ValidateKeywordArguments(kwds))
2209 result = PyDict_Merge(self, kwds, 1);
2210 else
2211 result = -1;
2212 }
2213 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002214}
2215
2216static PyObject *
2217dict_update(PyObject *self, PyObject *args, PyObject *kwds)
2218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 if (dict_update_common(self, args, kwds, "update") != -1)
2220 Py_RETURN_NONE;
2221 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002222}
2223
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002224/* Update unconditionally replaces existing items.
2225 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00002226 otherwise it leaves existing items unchanged.
2227
2228 PyDict_{Update,Merge} update/merge from a mapping object.
2229
Tim Petersf582b822001-12-11 18:51:08 +00002230 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00002231 producing iterable objects of length 2.
2232*/
2233
Tim Petersf582b822001-12-11 18:51:08 +00002234int
Tim Peters1fc240e2001-10-26 05:06:50 +00002235PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
2236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 PyObject *it; /* iter(seq2) */
2238 Py_ssize_t i; /* index into seq2 of current element */
2239 PyObject *item; /* seq2[i] */
2240 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 assert(d != NULL);
2243 assert(PyDict_Check(d));
2244 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 it = PyObject_GetIter(seq2);
2247 if (it == NULL)
2248 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 for (i = 0; ; ++i) {
2251 PyObject *key, *value;
2252 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 fast = NULL;
2255 item = PyIter_Next(it);
2256 if (item == NULL) {
2257 if (PyErr_Occurred())
2258 goto Fail;
2259 break;
2260 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 /* Convert item to sequence, and verify length 2. */
2263 fast = PySequence_Fast(item, "");
2264 if (fast == NULL) {
2265 if (PyErr_ExceptionMatches(PyExc_TypeError))
2266 PyErr_Format(PyExc_TypeError,
2267 "cannot convert dictionary update "
2268 "sequence element #%zd to a sequence",
2269 i);
2270 goto Fail;
2271 }
2272 n = PySequence_Fast_GET_SIZE(fast);
2273 if (n != 2) {
2274 PyErr_Format(PyExc_ValueError,
2275 "dictionary update sequence element #%zd "
2276 "has length %zd; 2 is required",
2277 i, n);
2278 goto Fail;
2279 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 /* Update/merge with this (key, value) pair. */
2282 key = PySequence_Fast_GET_ITEM(fast, 0);
2283 value = PySequence_Fast_GET_ITEM(fast, 1);
2284 if (override || PyDict_GetItem(d, key) == NULL) {
2285 int status = PyDict_SetItem(d, key, value);
2286 if (status < 0)
2287 goto Fail;
2288 }
2289 Py_DECREF(fast);
2290 Py_DECREF(item);
2291 }
Tim Peters1fc240e2001-10-26 05:06:50 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 i = 0;
2294 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00002295Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 Py_XDECREF(item);
2297 Py_XDECREF(fast);
2298 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00002299Return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 Py_DECREF(it);
2301 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00002302}
2303
Tim Peters6d6c1a32001-08-02 04:15:00 +00002304int
2305PyDict_Update(PyObject *a, PyObject *b)
2306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 return PyDict_Merge(a, b, 1);
Guido van Rossum05ac6de2001-08-10 20:28:28 +00002308}
2309
2310int
2311PyDict_Merge(PyObject *a, PyObject *b, int override)
2312{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002313 PyDictObject *mp, *other;
2314 Py_ssize_t i, n;
Victor Stinner742da042016-09-07 17:40:12 -07002315 PyDictKeyEntry *entry, *ep0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 /* We accept for the argument either a concrete dictionary object,
2318 * or an abstract "mapping" object. For the former, we can do
2319 * things quite efficiently. For the latter, we only require that
2320 * PyMapping_Keys() and PyObject_GetItem() be supported.
2321 */
2322 if (a == NULL || !PyDict_Check(a) || b == NULL) {
2323 PyErr_BadInternalCall();
2324 return -1;
2325 }
2326 mp = (PyDictObject*)a;
2327 if (PyDict_Check(b)) {
2328 other = (PyDictObject*)b;
2329 if (other == mp || other->ma_used == 0)
2330 /* a.update(a) or a.update({}); nothing to do */
2331 return 0;
2332 if (mp->ma_used == 0)
2333 /* Since the target dict is empty, PyDict_GetItem()
2334 * always returns NULL. Setting override to 1
2335 * skips the unnecessary test.
2336 */
2337 override = 1;
2338 /* Do one big resize at the start, rather than
2339 * incrementally resizing as we insert new items. Expect
2340 * that there will be no (or few) overlapping keys.
2341 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002342 if (mp->ma_keys->dk_usable * 3 < other->ma_used * 2)
2343 if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 return -1;
Victor Stinner742da042016-09-07 17:40:12 -07002345 ep0 = DK_ENTRIES(other->ma_keys);
2346 for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002347 PyObject *key, *value;
2348 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002349 entry = &ep0[i];
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002350 key = entry->me_key;
2351 hash = entry->me_hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002352 if (other->ma_values)
2353 value = other->ma_values[i];
2354 else
2355 value = entry->me_value;
2356
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002357 if (value != NULL) {
2358 int err = 0;
2359 Py_INCREF(key);
2360 Py_INCREF(value);
2361 if (override || PyDict_GetItem(a, key) == NULL)
2362 err = insertdict(mp, key, hash, value);
2363 Py_DECREF(value);
2364 Py_DECREF(key);
2365 if (err != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 return -1;
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002367
Victor Stinner742da042016-09-07 17:40:12 -07002368 if (n != other->ma_keys->dk_nentries) {
Benjamin Petersona82f77f2015-07-04 19:55:16 -05002369 PyErr_SetString(PyExc_RuntimeError,
2370 "dict mutated during update");
2371 return -1;
2372 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 }
2374 }
2375 }
2376 else {
2377 /* Do it the generic, slower way */
2378 PyObject *keys = PyMapping_Keys(b);
2379 PyObject *iter;
2380 PyObject *key, *value;
2381 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 if (keys == NULL)
2384 /* Docstring says this is equivalent to E.keys() so
2385 * if E doesn't have a .keys() method we want
2386 * AttributeError to percolate up. Might as well
2387 * do the same for any other error.
2388 */
2389 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 iter = PyObject_GetIter(keys);
2392 Py_DECREF(keys);
2393 if (iter == NULL)
2394 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
2397 if (!override && PyDict_GetItem(a, key) != NULL) {
2398 Py_DECREF(key);
2399 continue;
2400 }
2401 value = PyObject_GetItem(b, key);
2402 if (value == NULL) {
2403 Py_DECREF(iter);
2404 Py_DECREF(key);
2405 return -1;
2406 }
2407 status = PyDict_SetItem(a, key, value);
2408 Py_DECREF(key);
2409 Py_DECREF(value);
2410 if (status < 0) {
2411 Py_DECREF(iter);
2412 return -1;
2413 }
2414 }
2415 Py_DECREF(iter);
2416 if (PyErr_Occurred())
2417 /* Iterator completed, via error */
2418 return -1;
2419 }
2420 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002421}
2422
2423static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002424dict_copy(PyDictObject *mp)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002427}
2428
2429PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002430PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 PyObject *copy;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002433 PyDictObject *mp;
2434 Py_ssize_t i, n;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 if (o == NULL || !PyDict_Check(o)) {
2437 PyErr_BadInternalCall();
2438 return NULL;
2439 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002440 mp = (PyDictObject *)o;
2441 if (_PyDict_HasSplitTable(mp)) {
2442 PyDictObject *split_copy;
Victor Stinner742da042016-09-07 17:40:12 -07002443 Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
2444 PyObject **newvalues;
2445 newvalues = new_values(size);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002446 if (newvalues == NULL)
2447 return PyErr_NoMemory();
2448 split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
2449 if (split_copy == NULL) {
2450 free_values(newvalues);
2451 return NULL;
2452 }
2453 split_copy->ma_values = newvalues;
2454 split_copy->ma_keys = mp->ma_keys;
2455 split_copy->ma_used = mp->ma_used;
2456 DK_INCREF(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002457 for (i = 0, n = size; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002458 PyObject *value = mp->ma_values[i];
2459 Py_XINCREF(value);
2460 split_copy->ma_values[i] = value;
2461 }
Benjamin Peterson7ce67e42012-04-24 10:32:57 -04002462 if (_PyObject_GC_IS_TRACKED(mp))
2463 _PyObject_GC_TRACK(split_copy);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002464 return (PyObject *)split_copy;
2465 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 copy = PyDict_New();
2467 if (copy == NULL)
2468 return NULL;
2469 if (PyDict_Merge(copy, o, 1) == 0)
2470 return copy;
2471 Py_DECREF(copy);
2472 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002473}
2474
Martin v. Löwis18e16552006-02-15 17:27:45 +00002475Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00002476PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00002477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 if (mp == NULL || !PyDict_Check(mp)) {
2479 PyErr_BadInternalCall();
2480 return -1;
2481 }
2482 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00002483}
2484
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002485PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002486PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 if (mp == NULL || !PyDict_Check(mp)) {
2489 PyErr_BadInternalCall();
2490 return NULL;
2491 }
2492 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002493}
2494
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002495PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002496PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 if (mp == NULL || !PyDict_Check(mp)) {
2499 PyErr_BadInternalCall();
2500 return NULL;
2501 }
2502 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002503}
2504
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002505PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002506PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 if (mp == NULL || !PyDict_Check(mp)) {
2509 PyErr_BadInternalCall();
2510 return NULL;
2511 }
2512 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002513}
2514
Tim Peterse63415e2001-05-08 04:38:29 +00002515/* Return 1 if dicts equal, 0 if not, -1 if error.
2516 * Gets out as soon as any difference is detected.
2517 * Uses only Py_EQ comparison.
2518 */
2519static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002520dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00002521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00002523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 if (a->ma_used != b->ma_used)
2525 /* can't be equal if # of entries differ */
2526 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Victor Stinner742da042016-09-07 17:40:12 -07002528 for (i = 0; i < a->ma_keys->dk_nentries; i++) {
2529 PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002530 PyObject *aval;
2531 if (a->ma_values)
2532 aval = a->ma_values[i];
2533 else
2534 aval = ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 if (aval != NULL) {
2536 int cmp;
2537 PyObject *bval;
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002538 PyObject **vaddr;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002539 PyObject *key = ep->me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 /* temporarily bump aval's refcount to ensure it stays
2541 alive until we're done with it */
2542 Py_INCREF(aval);
2543 /* ditto for key */
2544 Py_INCREF(key);
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002545 /* reuse the known hash value */
Victor Stinner742da042016-09-07 17:40:12 -07002546 if ((b->ma_keys->dk_lookup)(b, key, ep->me_hash, &vaddr, NULL) < 0)
Antoine Pitrou0e9958b2012-12-02 19:10:07 +01002547 bval = NULL;
2548 else
2549 bval = *vaddr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 Py_DECREF(key);
2551 if (bval == NULL) {
2552 Py_DECREF(aval);
2553 if (PyErr_Occurred())
2554 return -1;
2555 return 0;
2556 }
2557 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
2558 Py_DECREF(aval);
2559 if (cmp <= 0) /* error or not equal */
2560 return cmp;
2561 }
2562 }
2563 return 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002564}
Tim Peterse63415e2001-05-08 04:38:29 +00002565
2566static PyObject *
2567dict_richcompare(PyObject *v, PyObject *w, int op)
2568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 int cmp;
2570 PyObject *res;
Tim Peterse63415e2001-05-08 04:38:29 +00002571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 if (!PyDict_Check(v) || !PyDict_Check(w)) {
2573 res = Py_NotImplemented;
2574 }
2575 else if (op == Py_EQ || op == Py_NE) {
2576 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
2577 if (cmp < 0)
2578 return NULL;
2579 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
2580 }
2581 else
2582 res = Py_NotImplemented;
2583 Py_INCREF(res);
2584 return res;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002585}
Tim Peterse63415e2001-05-08 04:38:29 +00002586
Larry Hastings61272b72014-01-07 12:41:53 -08002587/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002588
2589@coexist
2590dict.__contains__
2591
2592 key: object
2593 /
2594
Meador Ingee02de8c2014-01-14 16:48:31 -06002595True if D has a key k, else False.
Larry Hastings61272b72014-01-07 12:41:53 -08002596[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002597
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002598static PyObject *
Larry Hastingsc2047262014-01-25 20:43:29 -08002599dict___contains__(PyDictObject *self, PyObject *key)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03002600/*[clinic end generated code: output=a3d03db709ed6e6b input=b852b2a19b51ab24]*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002601{
Larry Hastingsc2047262014-01-25 20:43:29 -08002602 register PyDictObject *mp = self;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002603 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002604 Py_ssize_t ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002605 PyObject **value_addr;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002608 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 hash = PyObject_Hash(key);
2610 if (hash == -1)
2611 return NULL;
2612 }
Victor Stinner742da042016-09-07 17:40:12 -07002613 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2614 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002616 if (ix == DKIX_EMPTY || *value_addr == NULL)
2617 Py_RETURN_FALSE;
2618 Py_RETURN_TRUE;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002619}
2620
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002621static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002622dict_get(PyDictObject *mp, PyObject *args)
Barry Warsawc38c5da1997-10-06 17:49:20 +00002623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 PyObject *key;
2625 PyObject *failobj = Py_None;
2626 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002627 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002628 Py_ssize_t ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002629 PyObject **value_addr;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
2632 return NULL;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002635 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 hash = PyObject_Hash(key);
2637 if (hash == -1)
2638 return NULL;
2639 }
Victor Stinner742da042016-09-07 17:40:12 -07002640 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2641 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002643 if (ix == DKIX_EMPTY || *value_addr == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 val = failobj;
Victor Stinner742da042016-09-07 17:40:12 -07002645 else
2646 val = *value_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 Py_INCREF(val);
2648 return val;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002649}
2650
Benjamin Peterson00e98862013-03-07 22:16:29 -05002651PyObject *
2652PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
Guido van Rossum164452c2000-08-08 16:12:54 +00002653{
Benjamin Peterson00e98862013-03-07 22:16:29 -05002654 PyDictObject *mp = (PyDictObject *)d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002656 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002657 Py_ssize_t hashpos, ix;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002658 PyDictKeyEntry *ep;
2659 PyObject **value_addr;
Guido van Rossum164452c2000-08-08 16:12:54 +00002660
Benjamin Peterson00e98862013-03-07 22:16:29 -05002661 if (!PyDict_Check(d)) {
2662 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 return NULL;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002664 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002666 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 hash = PyObject_Hash(key);
2668 if (hash == -1)
2669 return NULL;
2670 }
Victor Stinner742da042016-09-07 17:40:12 -07002671 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
2672 if (ix == DKIX_ERROR)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 return NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002674 if (ix == DKIX_EMPTY || *value_addr == NULL) {
2675 val = defaultobj;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002676 if (mp->ma_keys->dk_usable <= 0) {
2677 /* Need to resize. */
Victor Stinner3c336c52016-09-12 14:17:40 +02002678 if (insertion_resize(mp) < 0) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002679 return NULL;
Victor Stinner3c336c52016-09-12 14:17:40 +02002680 }
Victor Stinner742da042016-09-07 17:40:12 -07002681 find_empty_slot(mp, key, hash, &value_addr, &hashpos);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002682 }
Victor Stinner742da042016-09-07 17:40:12 -07002683 ix = mp->ma_keys->dk_nentries;
Benjamin Peterson00e98862013-03-07 22:16:29 -05002684 Py_INCREF(defaultobj);
Benjamin Petersonb1efa532013-03-04 09:47:50 -05002685 Py_INCREF(key);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002686 MAINTAIN_TRACKING(mp, key, defaultobj);
Victor Stinner742da042016-09-07 17:40:12 -07002687 dk_set_index(mp->ma_keys, hashpos, ix);
2688 ep = &DK_ENTRIES(mp->ma_keys)[ix];
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002689 ep->me_key = key;
2690 ep->me_hash = hash;
Victor Stinner742da042016-09-07 17:40:12 -07002691 if (mp->ma_values) {
2692 mp->ma_values[ix] = val;
2693 }
2694 else {
2695 ep->me_value = val;
2696 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002697 mp->ma_keys->dk_usable--;
Victor Stinner742da042016-09-07 17:40:12 -07002698 mp->ma_keys->dk_nentries++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002699 mp->ma_used++;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07002700 mp->ma_version_tag = DICT_NEXT_VERSION();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 }
Victor Stinner742da042016-09-07 17:40:12 -07002702 else
2703 val = *value_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 return val;
Guido van Rossum164452c2000-08-08 16:12:54 +00002705}
2706
Benjamin Peterson00e98862013-03-07 22:16:29 -05002707static PyObject *
2708dict_setdefault(PyDictObject *mp, PyObject *args)
2709{
2710 PyObject *key, *val;
2711 PyObject *defaultobj = Py_None;
2712
2713 if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &defaultobj))
2714 return NULL;
2715
Benjamin Peterson55898502013-03-08 08:36:49 -05002716 val = PyDict_SetDefault((PyObject *)mp, key, defaultobj);
Benjamin Peterson00e98862013-03-07 22:16:29 -05002717 Py_XINCREF(val);
2718 return val;
2719}
Guido van Rossum164452c2000-08-08 16:12:54 +00002720
2721static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002722dict_clear(PyDictObject *mp)
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 PyDict_Clear((PyObject *)mp);
2725 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002726}
2727
Guido van Rossumba6ab842000-12-12 22:02:18 +00002728static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002729dict_pop(PyDictObject *mp, PyObject *args)
Guido van Rossume027d982002-04-12 15:11:59 +00002730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 PyObject *key, *deflt = NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00002732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
2734 return NULL;
Eric Snow96c6af92015-05-29 22:21:39 -06002735
2736 return _PyDict_Pop(mp, key, deflt);
Guido van Rossume027d982002-04-12 15:11:59 +00002737}
2738
2739static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002740dict_popitem(PyDictObject *mp)
Guido van Rossumba6ab842000-12-12 22:02:18 +00002741{
Victor Stinner742da042016-09-07 17:40:12 -07002742 Py_ssize_t i, j;
2743 PyDictKeyEntry *ep0, *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 PyObject *res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 /* Allocate the result tuple before checking the size. Believe it
2747 * or not, this allocation could trigger a garbage collection which
2748 * could empty the dict, so if we checked the size first and that
2749 * happened, the result would be an infinite loop (searching for an
2750 * entry that no longer exists). Note that the usual popitem()
2751 * idiom is "while d: k, v = d.popitem()". so needing to throw the
2752 * tuple away if the dict *is* empty isn't a significant
2753 * inefficiency -- possible, but unlikely in practice.
2754 */
2755 res = PyTuple_New(2);
2756 if (res == NULL)
2757 return NULL;
2758 if (mp->ma_used == 0) {
2759 Py_DECREF(res);
2760 PyErr_SetString(PyExc_KeyError,
2761 "popitem(): dictionary is empty");
2762 return NULL;
2763 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002764 /* Convert split table to combined table */
2765 if (mp->ma_keys->dk_lookup == lookdict_split) {
2766 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
2767 Py_DECREF(res);
2768 return NULL;
2769 }
2770 }
2771 ENSURE_ALLOWS_DELETIONS(mp);
Victor Stinner742da042016-09-07 17:40:12 -07002772
2773 /* Pop last item */
2774 ep0 = DK_ENTRIES(mp->ma_keys);
2775 i = mp->ma_keys->dk_nentries - 1;
2776 while (i >= 0 && ep0[i].me_value == NULL) {
2777 i--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 }
Victor Stinner742da042016-09-07 17:40:12 -07002779 assert(i >= 0);
2780
2781 ep = &ep0[i];
2782 j = lookdict_index(mp->ma_keys, ep->me_hash, i);
2783 assert(j >= 0);
2784 assert(dk_get_index(mp->ma_keys, j) == i);
2785 dk_set_index(mp->ma_keys, j, DKIX_DUMMY);
2786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 PyTuple_SET_ITEM(res, 0, ep->me_key);
2788 PyTuple_SET_ITEM(res, 1, ep->me_value);
Victor Stinner742da042016-09-07 17:40:12 -07002789 ep->me_key = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 ep->me_value = NULL;
Victor Stinner742da042016-09-07 17:40:12 -07002791 /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
2792 mp->ma_keys->dk_nentries = i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 mp->ma_used--;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07002794 mp->ma_version_tag = DICT_NEXT_VERSION();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 return res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002796}
2797
Jeremy Hylton8caad492000-06-23 14:18:11 +00002798static int
2799dict_traverse(PyObject *op, visitproc visit, void *arg)
2800{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002801 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson55f44522016-09-05 12:12:59 -07002802 PyDictKeysObject *keys = mp->ma_keys;
Victor Stinner742da042016-09-07 17:40:12 -07002803 PyDictKeyEntry *entries = DK_ENTRIES(mp->ma_keys);
2804 Py_ssize_t i, n = keys->dk_nentries;
2805
Benjamin Peterson55f44522016-09-05 12:12:59 -07002806 if (keys->dk_lookup == lookdict) {
2807 for (i = 0; i < n; i++) {
2808 if (entries[i].me_value != NULL) {
2809 Py_VISIT(entries[i].me_value);
2810 Py_VISIT(entries[i].me_key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002811 }
2812 }
Victor Stinner742da042016-09-07 17:40:12 -07002813 }
2814 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002815 if (mp->ma_values != NULL) {
Benjamin Peterson55f44522016-09-05 12:12:59 -07002816 for (i = 0; i < n; i++) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002817 Py_VISIT(mp->ma_values[i]);
2818 }
2819 }
2820 else {
Benjamin Peterson55f44522016-09-05 12:12:59 -07002821 for (i = 0; i < n; i++) {
2822 Py_VISIT(entries[i].me_value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002823 }
2824 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 }
2826 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002827}
2828
2829static int
2830dict_tp_clear(PyObject *op)
2831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 PyDict_Clear(op);
2833 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002834}
2835
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002836static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00002837
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002838Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06002839_PyDict_SizeOf(PyDictObject *mp)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002840{
Victor Stinner742da042016-09-07 17:40:12 -07002841 Py_ssize_t size, usable, res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002842
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002843 size = DK_SIZE(mp->ma_keys);
Victor Stinner742da042016-09-07 17:40:12 -07002844 usable = USABLE_FRACTION(size);
2845
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002846 res = _PyObject_SIZE(Py_TYPE(mp));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002847 if (mp->ma_values)
Victor Stinner742da042016-09-07 17:40:12 -07002848 res += usable * sizeof(PyObject*);
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002849 /* If the dictionary is split, the keys portion is accounted-for
2850 in the type object. */
2851 if (mp->ma_keys->dk_refcnt == 1)
Victor Stinner98ee9d52016-09-08 09:33:56 -07002852 res += (sizeof(PyDictKeysObject)
2853 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
2854 + DK_IXSIZE(mp->ma_keys) * size
2855 + sizeof(PyDictKeyEntry) * usable);
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002856 return res;
Martin v. Loewis4f2f3b62012-04-24 19:13:57 +02002857}
2858
2859Py_ssize_t
2860_PyDict_KeysSize(PyDictKeysObject *keys)
2861{
Victor Stinner98ee9d52016-09-08 09:33:56 -07002862 return (sizeof(PyDictKeysObject)
2863 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
2864 + DK_IXSIZE(keys) * DK_SIZE(keys)
2865 + USABLE_FRACTION(DK_SIZE(keys)) * sizeof(PyDictKeyEntry));
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002866}
2867
doko@ubuntu.com17210f52016-01-14 14:04:59 +01002868static PyObject *
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002869dict_sizeof(PyDictObject *mp)
2870{
2871 return PyLong_FromSsize_t(_PyDict_SizeOf(mp));
2872}
2873
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002874PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
2875
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002876PyDoc_STRVAR(sizeof__doc__,
2877"D.__sizeof__() -> size of D in memory, in bytes");
2878
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002879PyDoc_STRVAR(get__doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00002880"D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002881
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002882PyDoc_STRVAR(setdefault_doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00002883"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 +00002884
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002885PyDoc_STRVAR(pop__doc__,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002886"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00002887If key is not found, d is returned if given, otherwise KeyError is raised");
Guido van Rossume027d982002-04-12 15:11:59 +00002888
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002889PyDoc_STRVAR(popitem__doc__,
Tim Petersf7f88b12000-12-13 23:18:45 +00002890"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000028912-tuple; but raise KeyError if D is empty.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002892
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002893PyDoc_STRVAR(update__doc__,
Brett Cannonf2754162013-05-11 14:46:48 -04002894"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n\
2895If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]\n\
2896If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n\
2897In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00002898
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002899PyDoc_STRVAR(clear__doc__,
2900"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002901
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002902PyDoc_STRVAR(copy__doc__,
2903"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00002904
Guido van Rossumb90c8482007-02-10 01:11:45 +00002905/* Forward */
2906static PyObject *dictkeys_new(PyObject *);
2907static PyObject *dictitems_new(PyObject *);
2908static PyObject *dictvalues_new(PyObject *);
2909
Guido van Rossum45c85d12007-07-27 16:31:40 +00002910PyDoc_STRVAR(keys__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 "D.keys() -> a set-like object providing a view on D's keys");
Guido van Rossum45c85d12007-07-27 16:31:40 +00002912PyDoc_STRVAR(items__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 "D.items() -> a set-like object providing a view on D's items");
Guido van Rossum45c85d12007-07-27 16:31:40 +00002914PyDoc_STRVAR(values__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 "D.values() -> an object providing a view on D's values");
Guido van Rossumb90c8482007-02-10 01:11:45 +00002916
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002917static PyMethodDef mapp_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -07002918 DICT___CONTAINS___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
2920 getitem__doc__},
Serhiy Storchaka0ce7a3a2015-12-22 08:16:18 +02002921 {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 sizeof__doc__},
2923 {"get", (PyCFunction)dict_get, METH_VARARGS,
2924 get__doc__},
2925 {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS,
2926 setdefault_doc__},
2927 {"pop", (PyCFunction)dict_pop, METH_VARARGS,
2928 pop__doc__},
2929 {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
2930 popitem__doc__},
2931 {"keys", (PyCFunction)dictkeys_new, METH_NOARGS,
2932 keys__doc__},
2933 {"items", (PyCFunction)dictitems_new, METH_NOARGS,
2934 items__doc__},
2935 {"values", (PyCFunction)dictvalues_new, METH_NOARGS,
2936 values__doc__},
2937 {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
2938 update__doc__},
Larry Hastings5c661892014-01-24 06:17:25 -08002939 DICT_FROMKEYS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
2941 clear__doc__},
2942 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
2943 copy__doc__},
2944 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002945};
2946
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002947/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00002948int
2949PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002950{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002951 Py_hash_t hash;
Victor Stinner742da042016-09-07 17:40:12 -07002952 Py_ssize_t ix;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002954 PyObject **value_addr;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002957 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 hash = PyObject_Hash(key);
2959 if (hash == -1)
2960 return -1;
2961 }
Victor Stinner742da042016-09-07 17:40:12 -07002962 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2963 if (ix == DKIX_ERROR)
2964 return -1;
2965 return (ix != DKIX_EMPTY && *value_addr != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002966}
2967
Thomas Wouterscf297e42007-02-23 15:07:44 +00002968/* Internal version of PyDict_Contains used when the hash value is already known */
2969int
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002970_PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00002971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002973 PyObject **value_addr;
Victor Stinner742da042016-09-07 17:40:12 -07002974 Py_ssize_t ix;
Thomas Wouterscf297e42007-02-23 15:07:44 +00002975
Victor Stinner742da042016-09-07 17:40:12 -07002976 ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
2977 if (ix == DKIX_ERROR)
2978 return -1;
2979 return (ix != DKIX_EMPTY && *value_addr != NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00002980}
2981
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002982/* Hack to implement "key in dict" */
2983static PySequenceMethods dict_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 0, /* sq_length */
2985 0, /* sq_concat */
2986 0, /* sq_repeat */
2987 0, /* sq_item */
2988 0, /* sq_slice */
2989 0, /* sq_ass_item */
2990 0, /* sq_ass_slice */
2991 PyDict_Contains, /* sq_contains */
2992 0, /* sq_inplace_concat */
2993 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002994};
2995
Guido van Rossum09e563a2001-05-01 12:10:21 +00002996static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002997dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 PyObject *self;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003000 PyDictObject *d;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 assert(type != NULL && type->tp_alloc != NULL);
3003 self = type->tp_alloc(type, 0);
Victor Stinnera9f61a52013-07-16 22:17:26 +02003004 if (self == NULL)
3005 return NULL;
Victor Stinnera9f61a52013-07-16 22:17:26 +02003006 d = (PyDictObject *)self;
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003007
Victor Stinnera9f61a52013-07-16 22:17:26 +02003008 /* The object has been implicitly tracked by tp_alloc */
3009 if (type == &PyDict_Type)
3010 _PyObject_GC_UNTRACK(d);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003011
3012 d->ma_used = 0;
Victor Stinner3b6a6b42016-09-08 12:51:24 -07003013 d->ma_version_tag = DICT_NEXT_VERSION();
Victor Stinner742da042016-09-07 17:40:12 -07003014 d->ma_keys = new_keys_object(PyDict_MINSIZE);
Victor Stinnerac2a4fe2013-07-16 22:19:00 +02003015 if (d->ma_keys == NULL) {
3016 Py_DECREF(self);
3017 return NULL;
3018 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 return self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003020}
3021
Tim Peters25786c02001-09-02 08:22:48 +00003022static int
3023dict_init(PyObject *self, PyObject *args, PyObject *kwds)
3024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00003026}
3027
Tim Peters6d6c1a32001-08-02 04:15:00 +00003028static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003029dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00003030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00003032}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003033
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003034PyDoc_STRVAR(dictionary_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00003035"dict() -> new empty dictionary\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00003036"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003037" (key, value) pairs\n"
3038"dict(iterable) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00003039" d = {}\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00003040" for k, v in iterable:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00003041" d[k] = v\n"
3042"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
3043" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00003044
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003045PyTypeObject PyDict_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3047 "dict",
3048 sizeof(PyDictObject),
3049 0,
3050 (destructor)dict_dealloc, /* tp_dealloc */
3051 0, /* tp_print */
3052 0, /* tp_getattr */
3053 0, /* tp_setattr */
3054 0, /* tp_reserved */
3055 (reprfunc)dict_repr, /* tp_repr */
3056 0, /* tp_as_number */
3057 &dict_as_sequence, /* tp_as_sequence */
3058 &dict_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003059 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 0, /* tp_call */
3061 0, /* tp_str */
3062 PyObject_GenericGetAttr, /* tp_getattro */
3063 0, /* tp_setattro */
3064 0, /* tp_as_buffer */
3065 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3066 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
3067 dictionary_doc, /* tp_doc */
3068 dict_traverse, /* tp_traverse */
3069 dict_tp_clear, /* tp_clear */
3070 dict_richcompare, /* tp_richcompare */
3071 0, /* tp_weaklistoffset */
3072 (getiterfunc)dict_iter, /* tp_iter */
3073 0, /* tp_iternext */
3074 mapp_methods, /* tp_methods */
3075 0, /* tp_members */
3076 0, /* tp_getset */
3077 0, /* tp_base */
3078 0, /* tp_dict */
3079 0, /* tp_descr_get */
3080 0, /* tp_descr_set */
3081 0, /* tp_dictoffset */
3082 dict_init, /* tp_init */
3083 PyType_GenericAlloc, /* tp_alloc */
3084 dict_new, /* tp_new */
3085 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003086};
3087
Victor Stinner3c1e4812012-03-26 22:10:51 +02003088PyObject *
3089_PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
3090{
3091 PyObject *kv;
3092 kv = _PyUnicode_FromId(key); /* borrowed */
Victor Stinner5b3b1002013-07-22 23:50:57 +02003093 if (kv == NULL) {
3094 PyErr_Clear();
Victor Stinner3c1e4812012-03-26 22:10:51 +02003095 return NULL;
Victor Stinner5b3b1002013-07-22 23:50:57 +02003096 }
Victor Stinner3c1e4812012-03-26 22:10:51 +02003097 return PyDict_GetItem(dp, kv);
3098}
3099
Guido van Rossum3cca2451997-05-16 14:23:33 +00003100/* For backward compatibility with old dictionary interface */
3101
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003102PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003103PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 PyObject *kv, *rv;
3106 kv = PyUnicode_FromString(key);
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003107 if (kv == NULL) {
3108 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 return NULL;
Victor Stinnerfdcbab92013-07-16 22:16:05 +02003110 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 rv = PyDict_GetItem(v, kv);
3112 Py_DECREF(kv);
3113 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003114}
3115
3116int
Victor Stinner3c1e4812012-03-26 22:10:51 +02003117_PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
3118{
3119 PyObject *kv;
3120 kv = _PyUnicode_FromId(key); /* borrowed */
3121 if (kv == NULL)
3122 return -1;
3123 return PyDict_SetItem(v, kv, item);
3124}
3125
3126int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003127PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 PyObject *kv;
3130 int err;
3131 kv = PyUnicode_FromString(key);
3132 if (kv == NULL)
3133 return -1;
3134 PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
3135 err = PyDict_SetItem(v, kv, item);
3136 Py_DECREF(kv);
3137 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003138}
3139
3140int
Victor Stinner5fd2e5a2013-11-06 18:58:22 +01003141_PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
3142{
3143 PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
3144 if (kv == NULL)
3145 return -1;
3146 return PyDict_DelItem(v, kv);
3147}
3148
3149int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00003150PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 PyObject *kv;
3153 int err;
3154 kv = PyUnicode_FromString(key);
3155 if (kv == NULL)
3156 return -1;
3157 err = PyDict_DelItem(v, kv);
3158 Py_DECREF(kv);
3159 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00003160}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003161
Raymond Hettinger019a1482004-03-18 02:41:19 +00003162/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003163
3164typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 PyObject_HEAD
3166 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
3167 Py_ssize_t di_used;
3168 Py_ssize_t di_pos;
3169 PyObject* di_result; /* reusable result tuple for iteritems */
3170 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003171} dictiterobject;
3172
3173static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003174dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 dictiterobject *di;
3177 di = PyObject_GC_New(dictiterobject, itertype);
3178 if (di == NULL)
3179 return NULL;
3180 Py_INCREF(dict);
3181 di->di_dict = dict;
3182 di->di_used = dict->ma_used;
3183 di->di_pos = 0;
3184 di->len = dict->ma_used;
3185 if (itertype == &PyDictIterItem_Type) {
3186 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
3187 if (di->di_result == NULL) {
3188 Py_DECREF(di);
3189 return NULL;
3190 }
3191 }
3192 else
3193 di->di_result = NULL;
3194 _PyObject_GC_TRACK(di);
3195 return (PyObject *)di;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003196}
3197
3198static void
3199dictiter_dealloc(dictiterobject *di)
3200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 Py_XDECREF(di->di_dict);
3202 Py_XDECREF(di->di_result);
3203 PyObject_GC_Del(di);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003204}
3205
3206static int
3207dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
3208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 Py_VISIT(di->di_dict);
3210 Py_VISIT(di->di_result);
3211 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003212}
3213
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003214static PyObject *
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003215dictiter_len(dictiterobject *di)
3216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 Py_ssize_t len = 0;
3218 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
3219 len = di->len;
3220 return PyLong_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003221}
3222
Guido van Rossumb90c8482007-02-10 01:11:45 +00003223PyDoc_STRVAR(length_hint_doc,
3224 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003225
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003226static PyObject *
3227dictiter_reduce(dictiterobject *di);
3228
3229PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3230
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003231static PyMethodDef dictiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS,
3233 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003234 {"__reduce__", (PyCFunction)dictiter_reduce, METH_NOARGS,
3235 reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003236 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00003237};
3238
Raymond Hettinger019a1482004-03-18 02:41:19 +00003239static PyObject *dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00003240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003241 PyObject *key;
Victor Stinner742da042016-09-07 17:40:12 -07003242 Py_ssize_t i, n, offset;
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003243 PyDictKeysObject *k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003244 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003245 PyObject **value_ptr;
Guido van Rossum213c7a62001-04-23 14:08:49 +00003246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 if (d == NULL)
3248 return NULL;
3249 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00003250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 if (di->di_used != d->ma_used) {
3252 PyErr_SetString(PyExc_RuntimeError,
3253 "dictionary changed size during iteration");
3254 di->di_used = -1; /* Make this state sticky */
3255 return NULL;
3256 }
Guido van Rossum2147df72002-07-16 20:30:22 +00003257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 i = di->di_pos;
3259 if (i < 0)
3260 goto fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003261 k = d->ma_keys;
3262 if (d->ma_values) {
3263 value_ptr = &d->ma_values[i];
3264 offset = sizeof(PyObject *);
3265 }
3266 else {
Victor Stinner742da042016-09-07 17:40:12 -07003267 value_ptr = &DK_ENTRIES(k)[i].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003268 offset = sizeof(PyDictKeyEntry);
3269 }
Victor Stinner742da042016-09-07 17:40:12 -07003270 n = k->dk_nentries - 1;
3271 while (i <= n && *value_ptr == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003272 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 i++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003274 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 di->di_pos = i+1;
Victor Stinner742da042016-09-07 17:40:12 -07003276 if (i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 goto fail;
3278 di->len--;
Victor Stinner742da042016-09-07 17:40:12 -07003279 key = DK_ENTRIES(k)[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 Py_INCREF(key);
3281 return key;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003282
3283fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003285 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003287}
3288
Raymond Hettinger019a1482004-03-18 02:41:19 +00003289PyTypeObject PyDictIterKey_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3291 "dict_keyiterator", /* tp_name */
3292 sizeof(dictiterobject), /* tp_basicsize */
3293 0, /* tp_itemsize */
3294 /* methods */
3295 (destructor)dictiter_dealloc, /* tp_dealloc */
3296 0, /* tp_print */
3297 0, /* tp_getattr */
3298 0, /* tp_setattr */
3299 0, /* tp_reserved */
3300 0, /* tp_repr */
3301 0, /* tp_as_number */
3302 0, /* tp_as_sequence */
3303 0, /* tp_as_mapping */
3304 0, /* tp_hash */
3305 0, /* tp_call */
3306 0, /* tp_str */
3307 PyObject_GenericGetAttr, /* tp_getattro */
3308 0, /* tp_setattro */
3309 0, /* tp_as_buffer */
3310 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3311 0, /* tp_doc */
3312 (traverseproc)dictiter_traverse, /* tp_traverse */
3313 0, /* tp_clear */
3314 0, /* tp_richcompare */
3315 0, /* tp_weaklistoffset */
3316 PyObject_SelfIter, /* tp_iter */
3317 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
3318 dictiter_methods, /* tp_methods */
3319 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003320};
3321
3322static PyObject *dictiter_iternextvalue(dictiterobject *di)
3323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 PyObject *value;
Victor Stinner742da042016-09-07 17:40:12 -07003325 Py_ssize_t i, n, offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003327 PyObject **value_ptr;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 if (d == NULL)
3330 return NULL;
3331 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 if (di->di_used != d->ma_used) {
3334 PyErr_SetString(PyExc_RuntimeError,
3335 "dictionary changed size during iteration");
3336 di->di_used = -1; /* Make this state sticky */
3337 return NULL;
3338 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 i = di->di_pos;
Victor Stinner742da042016-09-07 17:40:12 -07003341 n = d->ma_keys->dk_nentries - 1;
3342 if (i < 0 || i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 goto fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003344 if (d->ma_values) {
3345 value_ptr = &d->ma_values[i];
3346 offset = sizeof(PyObject *);
3347 }
3348 else {
Victor Stinner742da042016-09-07 17:40:12 -07003349 value_ptr = &DK_ENTRIES(d->ma_keys)[i].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003350 offset = sizeof(PyDictKeyEntry);
3351 }
Victor Stinner742da042016-09-07 17:40:12 -07003352 while (i <= n && *value_ptr == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003353 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 i++;
Victor Stinner742da042016-09-07 17:40:12 -07003355 if (i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 goto fail;
3357 }
3358 di->di_pos = i+1;
3359 di->len--;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003360 value = *value_ptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003361 Py_INCREF(value);
3362 return value;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003363
3364fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003366 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003368}
3369
3370PyTypeObject PyDictIterValue_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3372 "dict_valueiterator", /* tp_name */
3373 sizeof(dictiterobject), /* tp_basicsize */
3374 0, /* tp_itemsize */
3375 /* methods */
3376 (destructor)dictiter_dealloc, /* tp_dealloc */
3377 0, /* tp_print */
3378 0, /* tp_getattr */
3379 0, /* tp_setattr */
3380 0, /* tp_reserved */
3381 0, /* tp_repr */
3382 0, /* tp_as_number */
3383 0, /* tp_as_sequence */
3384 0, /* tp_as_mapping */
3385 0, /* tp_hash */
3386 0, /* tp_call */
3387 0, /* tp_str */
3388 PyObject_GenericGetAttr, /* tp_getattro */
3389 0, /* tp_setattro */
3390 0, /* tp_as_buffer */
3391 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3392 0, /* tp_doc */
3393 (traverseproc)dictiter_traverse, /* tp_traverse */
3394 0, /* tp_clear */
3395 0, /* tp_richcompare */
3396 0, /* tp_weaklistoffset */
3397 PyObject_SelfIter, /* tp_iter */
3398 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
3399 dictiter_methods, /* tp_methods */
3400 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00003401};
3402
3403static PyObject *dictiter_iternextitem(dictiterobject *di)
3404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 PyObject *key, *value, *result = di->di_result;
Victor Stinner742da042016-09-07 17:40:12 -07003406 Py_ssize_t i, n, offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003408 PyObject **value_ptr;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 if (d == NULL)
3411 return NULL;
3412 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00003413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 if (di->di_used != d->ma_used) {
3415 PyErr_SetString(PyExc_RuntimeError,
3416 "dictionary changed size during iteration");
3417 di->di_used = -1; /* Make this state sticky */
3418 return NULL;
3419 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00003420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 i = di->di_pos;
3422 if (i < 0)
3423 goto fail;
Victor Stinner742da042016-09-07 17:40:12 -07003424 n = d->ma_keys->dk_nentries - 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003425 if (d->ma_values) {
3426 value_ptr = &d->ma_values[i];
3427 offset = sizeof(PyObject *);
3428 }
3429 else {
Victor Stinner742da042016-09-07 17:40:12 -07003430 value_ptr = &DK_ENTRIES(d->ma_keys)[i].me_value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003431 offset = sizeof(PyDictKeyEntry);
3432 }
Victor Stinner742da042016-09-07 17:40:12 -07003433 while (i <= n && *value_ptr == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003434 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 i++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003436 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 di->di_pos = i+1;
Victor Stinner742da042016-09-07 17:40:12 -07003438 if (i > n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 goto fail;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 if (result->ob_refcnt == 1) {
3442 Py_INCREF(result);
3443 Py_DECREF(PyTuple_GET_ITEM(result, 0));
3444 Py_DECREF(PyTuple_GET_ITEM(result, 1));
3445 } else {
3446 result = PyTuple_New(2);
3447 if (result == NULL)
3448 return NULL;
3449 }
3450 di->len--;
Victor Stinner742da042016-09-07 17:40:12 -07003451 key = DK_ENTRIES(d->ma_keys)[i].me_key;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003452 value = *value_ptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 Py_INCREF(key);
3454 Py_INCREF(value);
Eric Snow96c6af92015-05-29 22:21:39 -06003455 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
3456 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003458
3459fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 di->di_dict = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003461 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00003463}
3464
3465PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3467 "dict_itemiterator", /* tp_name */
3468 sizeof(dictiterobject), /* tp_basicsize */
3469 0, /* tp_itemsize */
3470 /* methods */
3471 (destructor)dictiter_dealloc, /* tp_dealloc */
3472 0, /* tp_print */
3473 0, /* tp_getattr */
3474 0, /* tp_setattr */
3475 0, /* tp_reserved */
3476 0, /* tp_repr */
3477 0, /* tp_as_number */
3478 0, /* tp_as_sequence */
3479 0, /* tp_as_mapping */
3480 0, /* tp_hash */
3481 0, /* tp_call */
3482 0, /* tp_str */
3483 PyObject_GenericGetAttr, /* tp_getattro */
3484 0, /* tp_setattro */
3485 0, /* tp_as_buffer */
3486 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3487 0, /* tp_doc */
3488 (traverseproc)dictiter_traverse, /* tp_traverse */
3489 0, /* tp_clear */
3490 0, /* tp_richcompare */
3491 0, /* tp_weaklistoffset */
3492 PyObject_SelfIter, /* tp_iter */
3493 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
3494 dictiter_methods, /* tp_methods */
3495 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003496};
Guido van Rossumb90c8482007-02-10 01:11:45 +00003497
3498
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003499static PyObject *
3500dictiter_reduce(dictiterobject *di)
3501{
3502 PyObject *list;
3503 dictiterobject tmp;
3504
3505 list = PyList_New(0);
3506 if (!list)
3507 return NULL;
3508
3509 /* copy the itertor state */
3510 tmp = *di;
3511 Py_XINCREF(tmp.di_dict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003512
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003513 /* iterate the temporary into a list */
3514 for(;;) {
3515 PyObject *element = 0;
3516 if (Py_TYPE(di) == &PyDictIterItem_Type)
3517 element = dictiter_iternextitem(&tmp);
3518 else if (Py_TYPE(di) == &PyDictIterKey_Type)
3519 element = dictiter_iternextkey(&tmp);
3520 else if (Py_TYPE(di) == &PyDictIterValue_Type)
3521 element = dictiter_iternextvalue(&tmp);
3522 else
3523 assert(0);
3524 if (element) {
3525 if (PyList_Append(list, element)) {
3526 Py_DECREF(element);
3527 Py_DECREF(list);
3528 Py_XDECREF(tmp.di_dict);
3529 return NULL;
3530 }
3531 Py_DECREF(element);
3532 } else
3533 break;
3534 }
3535 Py_XDECREF(tmp.di_dict);
3536 /* check for error */
3537 if (tmp.di_dict != NULL) {
3538 /* we have an error */
3539 Py_DECREF(list);
3540 return NULL;
3541 }
Antoine Pitroua7013882012-04-05 00:04:20 +02003542 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003543}
3544
Guido van Rossum3ac67412007-02-10 18:55:06 +00003545/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003546/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00003547/***********************************************/
3548
Guido van Rossumb90c8482007-02-10 01:11:45 +00003549/* The instance lay-out is the same for all three; but the type differs. */
3550
Guido van Rossumb90c8482007-02-10 01:11:45 +00003551static void
Eric Snow96c6af92015-05-29 22:21:39 -06003552dictview_dealloc(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 Py_XDECREF(dv->dv_dict);
3555 PyObject_GC_Del(dv);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003556}
3557
3558static int
Eric Snow96c6af92015-05-29 22:21:39 -06003559dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 Py_VISIT(dv->dv_dict);
3562 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003563}
3564
Guido van Rossum83825ac2007-02-10 04:54:19 +00003565static Py_ssize_t
Eric Snow96c6af92015-05-29 22:21:39 -06003566dictview_len(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 Py_ssize_t len = 0;
3569 if (dv->dv_dict != NULL)
3570 len = dv->dv_dict->ma_used;
3571 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003572}
3573
Eric Snow96c6af92015-05-29 22:21:39 -06003574PyObject *
3575_PyDictView_New(PyObject *dict, PyTypeObject *type)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003576{
Eric Snow96c6af92015-05-29 22:21:39 -06003577 _PyDictViewObject *dv;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 if (dict == NULL) {
3579 PyErr_BadInternalCall();
3580 return NULL;
3581 }
3582 if (!PyDict_Check(dict)) {
3583 /* XXX Get rid of this restriction later */
3584 PyErr_Format(PyExc_TypeError,
3585 "%s() requires a dict argument, not '%s'",
3586 type->tp_name, dict->ob_type->tp_name);
3587 return NULL;
3588 }
Eric Snow96c6af92015-05-29 22:21:39 -06003589 dv = PyObject_GC_New(_PyDictViewObject, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003590 if (dv == NULL)
3591 return NULL;
3592 Py_INCREF(dict);
3593 dv->dv_dict = (PyDictObject *)dict;
3594 _PyObject_GC_TRACK(dv);
3595 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003596}
3597
Neal Norwitze36f2ba2007-02-26 23:12:28 +00003598/* TODO(guido): The views objects are not complete:
3599
3600 * support more set operations
3601 * support arbitrary mappings?
3602 - either these should be static or exported in dictobject.h
3603 - if public then they should probably be in builtins
3604*/
3605
Guido van Rossumaac530c2007-08-24 22:33:45 +00003606/* Return 1 if self is a subset of other, iterating over self;
3607 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00003608static int
3609all_contained_in(PyObject *self, PyObject *other)
3610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 PyObject *iter = PyObject_GetIter(self);
3612 int ok = 1;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 if (iter == NULL)
3615 return -1;
3616 for (;;) {
3617 PyObject *next = PyIter_Next(iter);
3618 if (next == NULL) {
3619 if (PyErr_Occurred())
3620 ok = -1;
3621 break;
3622 }
3623 ok = PySequence_Contains(other, next);
3624 Py_DECREF(next);
3625 if (ok <= 0)
3626 break;
3627 }
3628 Py_DECREF(iter);
3629 return ok;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003630}
3631
3632static PyObject *
3633dictview_richcompare(PyObject *self, PyObject *other, int op)
3634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 Py_ssize_t len_self, len_other;
3636 int ok;
3637 PyObject *result;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003639 assert(self != NULL);
3640 assert(PyDictViewSet_Check(self));
3641 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00003642
Brian Curtindfc80e32011-08-10 20:28:54 -05003643 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
3644 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003646 len_self = PyObject_Size(self);
3647 if (len_self < 0)
3648 return NULL;
3649 len_other = PyObject_Size(other);
3650 if (len_other < 0)
3651 return NULL;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 ok = 0;
3654 switch(op) {
Guido van Rossumaac530c2007-08-24 22:33:45 +00003655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 case Py_NE:
3657 case Py_EQ:
3658 if (len_self == len_other)
3659 ok = all_contained_in(self, other);
3660 if (op == Py_NE && ok >= 0)
3661 ok = !ok;
3662 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 case Py_LT:
3665 if (len_self < len_other)
3666 ok = all_contained_in(self, other);
3667 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 case Py_LE:
3670 if (len_self <= len_other)
3671 ok = all_contained_in(self, other);
3672 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 case Py_GT:
3675 if (len_self > len_other)
3676 ok = all_contained_in(other, self);
3677 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003679 case Py_GE:
3680 if (len_self >= len_other)
3681 ok = all_contained_in(other, self);
3682 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003684 }
3685 if (ok < 0)
3686 return NULL;
3687 result = ok ? Py_True : Py_False;
3688 Py_INCREF(result);
3689 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003690}
3691
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003692static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003693dictview_repr(_PyDictViewObject *dv)
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 PyObject *seq;
3696 PyObject *result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003698 seq = PySequence_List((PyObject *)dv);
3699 if (seq == NULL)
3700 return NULL;
3701
3702 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
3703 Py_DECREF(seq);
3704 return result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003705}
3706
Guido van Rossum3ac67412007-02-10 18:55:06 +00003707/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003708
3709static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003710dictkeys_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003712 if (dv->dv_dict == NULL) {
3713 Py_RETURN_NONE;
3714 }
3715 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003716}
3717
3718static int
Eric Snow96c6af92015-05-29 22:21:39 -06003719dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00003720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003721 if (dv->dv_dict == NULL)
3722 return 0;
3723 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003724}
3725
Guido van Rossum83825ac2007-02-10 04:54:19 +00003726static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 (lenfunc)dictview_len, /* sq_length */
3728 0, /* sq_concat */
3729 0, /* sq_repeat */
3730 0, /* sq_item */
3731 0, /* sq_slice */
3732 0, /* sq_ass_item */
3733 0, /* sq_ass_slice */
3734 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003735};
3736
Guido van Rossum523259b2007-08-24 23:41:22 +00003737static PyObject*
3738dictviews_sub(PyObject* self, PyObject *other)
3739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 PyObject *result = PySet_New(self);
3741 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003742 _Py_IDENTIFIER(difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003744 if (result == NULL)
3745 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003746
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003747 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 if (tmp == NULL) {
3749 Py_DECREF(result);
3750 return NULL;
3751 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003753 Py_DECREF(tmp);
3754 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003755}
3756
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003757PyObject*
3758_PyDictView_Intersect(PyObject* self, PyObject *other)
Guido van Rossum523259b2007-08-24 23:41:22 +00003759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 PyObject *result = PySet_New(self);
3761 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003762 _Py_IDENTIFIER(intersection_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 if (result == NULL)
3765 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003766
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003767 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_intersection_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 if (tmp == NULL) {
3769 Py_DECREF(result);
3770 return NULL;
3771 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 Py_DECREF(tmp);
3774 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003775}
3776
3777static PyObject*
3778dictviews_or(PyObject* self, PyObject *other)
3779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 PyObject *result = PySet_New(self);
3781 PyObject *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02003782 _Py_IDENTIFIER(update);
Victor Stinnerd1a9cc22011-10-13 22:51:17 +02003783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003784 if (result == NULL)
3785 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003786
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003787 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 if (tmp == NULL) {
3789 Py_DECREF(result);
3790 return NULL;
3791 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003793 Py_DECREF(tmp);
3794 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003795}
3796
3797static PyObject*
3798dictviews_xor(PyObject* self, PyObject *other)
3799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 PyObject *result = PySet_New(self);
3801 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003802 _Py_IDENTIFIER(symmetric_difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 if (result == NULL)
3805 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003806
Benjamin Petersonf11b25b2016-03-03 22:05:36 -08003807 tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_symmetric_difference_update, other, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 if (tmp == NULL) {
3809 Py_DECREF(result);
3810 return NULL;
3811 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003813 Py_DECREF(tmp);
3814 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003815}
3816
3817static PyNumberMethods dictviews_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 0, /*nb_add*/
3819 (binaryfunc)dictviews_sub, /*nb_subtract*/
3820 0, /*nb_multiply*/
3821 0, /*nb_remainder*/
3822 0, /*nb_divmod*/
3823 0, /*nb_power*/
3824 0, /*nb_negative*/
3825 0, /*nb_positive*/
3826 0, /*nb_absolute*/
3827 0, /*nb_bool*/
3828 0, /*nb_invert*/
3829 0, /*nb_lshift*/
3830 0, /*nb_rshift*/
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003831 (binaryfunc)_PyDictView_Intersect, /*nb_and*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 (binaryfunc)dictviews_xor, /*nb_xor*/
3833 (binaryfunc)dictviews_or, /*nb_or*/
Guido van Rossum523259b2007-08-24 23:41:22 +00003834};
3835
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003836static PyObject*
3837dictviews_isdisjoint(PyObject *self, PyObject *other)
3838{
3839 PyObject *it;
3840 PyObject *item = NULL;
3841
3842 if (self == other) {
Eric Snow96c6af92015-05-29 22:21:39 -06003843 if (dictview_len((_PyDictViewObject *)self) == 0)
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003844 Py_RETURN_TRUE;
3845 else
3846 Py_RETURN_FALSE;
3847 }
3848
3849 /* Iterate over the shorter object (only if other is a set,
3850 * because PySequence_Contains may be expensive otherwise): */
3851 if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
Eric Snow96c6af92015-05-29 22:21:39 -06003852 Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003853 Py_ssize_t len_other = PyObject_Size(other);
3854 if (len_other == -1)
3855 return NULL;
3856
3857 if ((len_other > len_self)) {
3858 PyObject *tmp = other;
3859 other = self;
3860 self = tmp;
3861 }
3862 }
3863
3864 it = PyObject_GetIter(other);
3865 if (it == NULL)
3866 return NULL;
3867
3868 while ((item = PyIter_Next(it)) != NULL) {
3869 int contains = PySequence_Contains(self, item);
3870 Py_DECREF(item);
3871 if (contains == -1) {
3872 Py_DECREF(it);
3873 return NULL;
3874 }
3875
3876 if (contains) {
3877 Py_DECREF(it);
3878 Py_RETURN_FALSE;
3879 }
3880 }
3881 Py_DECREF(it);
3882 if (PyErr_Occurred())
3883 return NULL; /* PyIter_Next raised an exception. */
3884 Py_RETURN_TRUE;
3885}
3886
3887PyDoc_STRVAR(isdisjoint_doc,
3888"Return True if the view and the given iterable have a null intersection.");
3889
Guido van Rossumb90c8482007-02-10 01:11:45 +00003890static PyMethodDef dictkeys_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003891 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
3892 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00003894};
3895
3896PyTypeObject PyDictKeys_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3898 "dict_keys", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06003899 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 0, /* tp_itemsize */
3901 /* methods */
3902 (destructor)dictview_dealloc, /* tp_dealloc */
3903 0, /* tp_print */
3904 0, /* tp_getattr */
3905 0, /* tp_setattr */
3906 0, /* tp_reserved */
3907 (reprfunc)dictview_repr, /* tp_repr */
3908 &dictviews_as_number, /* tp_as_number */
3909 &dictkeys_as_sequence, /* tp_as_sequence */
3910 0, /* tp_as_mapping */
3911 0, /* tp_hash */
3912 0, /* tp_call */
3913 0, /* tp_str */
3914 PyObject_GenericGetAttr, /* tp_getattro */
3915 0, /* tp_setattro */
3916 0, /* tp_as_buffer */
3917 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3918 0, /* tp_doc */
3919 (traverseproc)dictview_traverse, /* tp_traverse */
3920 0, /* tp_clear */
3921 dictview_richcompare, /* tp_richcompare */
3922 0, /* tp_weaklistoffset */
3923 (getiterfunc)dictkeys_iter, /* tp_iter */
3924 0, /* tp_iternext */
3925 dictkeys_methods, /* tp_methods */
3926 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00003927};
3928
3929static PyObject *
3930dictkeys_new(PyObject *dict)
3931{
Eric Snow96c6af92015-05-29 22:21:39 -06003932 return _PyDictView_New(dict, &PyDictKeys_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003933}
3934
Guido van Rossum3ac67412007-02-10 18:55:06 +00003935/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003936
3937static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06003938dictitems_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003940 if (dv->dv_dict == NULL) {
3941 Py_RETURN_NONE;
3942 }
3943 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003944}
3945
3946static int
Eric Snow96c6af92015-05-29 22:21:39 -06003947dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
Guido van Rossum3ac67412007-02-10 18:55:06 +00003948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 PyObject *key, *value, *found;
3950 if (dv->dv_dict == NULL)
3951 return 0;
3952 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
3953 return 0;
3954 key = PyTuple_GET_ITEM(obj, 0);
3955 value = PyTuple_GET_ITEM(obj, 1);
3956 found = PyDict_GetItem((PyObject *)dv->dv_dict, key);
3957 if (found == NULL) {
3958 if (PyErr_Occurred())
3959 return -1;
3960 return 0;
3961 }
3962 return PyObject_RichCompareBool(value, found, Py_EQ);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003963}
3964
Guido van Rossum83825ac2007-02-10 04:54:19 +00003965static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003966 (lenfunc)dictview_len, /* sq_length */
3967 0, /* sq_concat */
3968 0, /* sq_repeat */
3969 0, /* sq_item */
3970 0, /* sq_slice */
3971 0, /* sq_ass_item */
3972 0, /* sq_ass_slice */
3973 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003974};
3975
Guido van Rossumb90c8482007-02-10 01:11:45 +00003976static PyMethodDef dictitems_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003977 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
3978 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003979 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00003980};
3981
3982PyTypeObject PyDictItems_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003983 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3984 "dict_items", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06003985 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 0, /* tp_itemsize */
3987 /* methods */
3988 (destructor)dictview_dealloc, /* tp_dealloc */
3989 0, /* tp_print */
3990 0, /* tp_getattr */
3991 0, /* tp_setattr */
3992 0, /* tp_reserved */
3993 (reprfunc)dictview_repr, /* tp_repr */
3994 &dictviews_as_number, /* tp_as_number */
3995 &dictitems_as_sequence, /* tp_as_sequence */
3996 0, /* tp_as_mapping */
3997 0, /* tp_hash */
3998 0, /* tp_call */
3999 0, /* tp_str */
4000 PyObject_GenericGetAttr, /* tp_getattro */
4001 0, /* tp_setattro */
4002 0, /* tp_as_buffer */
4003 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4004 0, /* tp_doc */
4005 (traverseproc)dictview_traverse, /* tp_traverse */
4006 0, /* tp_clear */
4007 dictview_richcompare, /* tp_richcompare */
4008 0, /* tp_weaklistoffset */
4009 (getiterfunc)dictitems_iter, /* tp_iter */
4010 0, /* tp_iternext */
4011 dictitems_methods, /* tp_methods */
4012 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004013};
4014
4015static PyObject *
4016dictitems_new(PyObject *dict)
4017{
Eric Snow96c6af92015-05-29 22:21:39 -06004018 return _PyDictView_New(dict, &PyDictItems_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004019}
4020
Guido van Rossum3ac67412007-02-10 18:55:06 +00004021/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00004022
4023static PyObject *
Eric Snow96c6af92015-05-29 22:21:39 -06004024dictvalues_iter(_PyDictViewObject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00004025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004026 if (dv->dv_dict == NULL) {
4027 Py_RETURN_NONE;
4028 }
4029 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004030}
4031
Guido van Rossum83825ac2007-02-10 04:54:19 +00004032static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004033 (lenfunc)dictview_len, /* sq_length */
4034 0, /* sq_concat */
4035 0, /* sq_repeat */
4036 0, /* sq_item */
4037 0, /* sq_slice */
4038 0, /* sq_ass_item */
4039 0, /* sq_ass_slice */
4040 (objobjproc)0, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00004041};
4042
Guido van Rossumb90c8482007-02-10 01:11:45 +00004043static PyMethodDef dictvalues_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00004045};
4046
4047PyTypeObject PyDictValues_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4049 "dict_values", /* tp_name */
Eric Snow96c6af92015-05-29 22:21:39 -06004050 sizeof(_PyDictViewObject), /* tp_basicsize */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 0, /* tp_itemsize */
4052 /* methods */
4053 (destructor)dictview_dealloc, /* tp_dealloc */
4054 0, /* tp_print */
4055 0, /* tp_getattr */
4056 0, /* tp_setattr */
4057 0, /* tp_reserved */
4058 (reprfunc)dictview_repr, /* tp_repr */
4059 0, /* tp_as_number */
4060 &dictvalues_as_sequence, /* tp_as_sequence */
4061 0, /* tp_as_mapping */
4062 0, /* tp_hash */
4063 0, /* tp_call */
4064 0, /* tp_str */
4065 PyObject_GenericGetAttr, /* tp_getattro */
4066 0, /* tp_setattro */
4067 0, /* tp_as_buffer */
4068 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4069 0, /* tp_doc */
4070 (traverseproc)dictview_traverse, /* tp_traverse */
4071 0, /* tp_clear */
4072 0, /* tp_richcompare */
4073 0, /* tp_weaklistoffset */
4074 (getiterfunc)dictvalues_iter, /* tp_iter */
4075 0, /* tp_iternext */
4076 dictvalues_methods, /* tp_methods */
4077 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00004078};
4079
4080static PyObject *
4081dictvalues_new(PyObject *dict)
4082{
Eric Snow96c6af92015-05-29 22:21:39 -06004083 return _PyDictView_New(dict, &PyDictValues_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00004084}
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004085
4086/* Returns NULL if cannot allocate a new PyDictKeysObject,
4087 but does not set an error */
4088PyDictKeysObject *
4089_PyDict_NewKeysForClass(void)
4090{
Victor Stinner742da042016-09-07 17:40:12 -07004091 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004092 if (keys == NULL)
4093 PyErr_Clear();
4094 else
4095 keys->dk_lookup = lookdict_split;
4096 return keys;
4097}
4098
4099#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
4100
4101PyObject *
4102PyObject_GenericGetDict(PyObject *obj, void *context)
4103{
4104 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
4105 if (dictptr == NULL) {
4106 PyErr_SetString(PyExc_AttributeError,
4107 "This object has no __dict__");
4108 return NULL;
4109 }
4110 dict = *dictptr;
4111 if (dict == NULL) {
4112 PyTypeObject *tp = Py_TYPE(obj);
4113 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
4114 DK_INCREF(CACHED_KEYS(tp));
4115 *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
4116 }
4117 else {
4118 *dictptr = dict = PyDict_New();
4119 }
4120 }
4121 Py_XINCREF(dict);
4122 return dict;
4123}
4124
4125int
4126_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
Victor Stinner742da042016-09-07 17:40:12 -07004127 PyObject *key, PyObject *value)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004128{
4129 PyObject *dict;
4130 int res;
4131 PyDictKeysObject *cached;
4132
4133 assert(dictptr != NULL);
4134 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
4135 assert(dictptr != NULL);
4136 dict = *dictptr;
4137 if (dict == NULL) {
4138 DK_INCREF(cached);
4139 dict = new_dict_with_shared_keys(cached);
4140 if (dict == NULL)
4141 return -1;
4142 *dictptr = dict;
4143 }
4144 if (value == NULL) {
4145 res = PyDict_DelItem(dict, key);
4146 if (cached != ((PyDictObject *)dict)->ma_keys) {
4147 CACHED_KEYS(tp) = NULL;
4148 DK_DECREF(cached);
4149 }
4150 } else {
4151 res = PyDict_SetItem(dict, key, value);
4152 if (cached != ((PyDictObject *)dict)->ma_keys) {
4153 /* Either update tp->ht_cached_keys or delete it */
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004154 if (cached->dk_refcnt == 1) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004155 CACHED_KEYS(tp) = make_keys_shared(dict);
Victor Stinner742da042016-09-07 17:40:12 -07004156 }
4157 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004158 CACHED_KEYS(tp) = NULL;
4159 }
4160 DK_DECREF(cached);
Benjamin Peterson15ee8212012-04-24 14:44:18 -04004161 if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
4162 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04004163 }
4164 }
4165 } else {
4166 dict = *dictptr;
4167 if (dict == NULL) {
4168 dict = PyDict_New();
4169 if (dict == NULL)
4170 return -1;
4171 *dictptr = dict;
4172 }
4173 if (value == NULL) {
4174 res = PyDict_DelItem(dict, key);
4175 } else {
4176 res = PyDict_SetItem(dict, key, value);
4177 }
4178 }
4179 return res;
4180}
4181
4182void
4183_PyDictKeys_DecRef(PyDictKeysObject *keys)
4184{
4185 DK_DECREF(keys);
4186}