blob: 2e45c8d8fdd4d1157bb6b3313b596f53ce574489 [file] [log] [blame]
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001
Guido van Rossum2bc13791999-03-24 19:06:42 +00002/* Dictionary object implementation using a hash table */
Guido van Rossum9bfef441993-03-29 10:43:31 +00003
Raymond Hettinger930427b2003-05-03 06:51:59 +00004/* The distribution includes a separate file, Objects/dictnotes.txt,
Tim Peters60b29962006-01-01 01:19:23 +00005 describing explorations into dictionary design and optimization.
Raymond Hettinger930427b2003-05-03 06:51:59 +00006 It covers typical dictionary use patterns, the parameters for
7 tuning dictionaries, and several ideas for possible optimizations.
8*/
9
Benjamin Peterson7d95e402012-04-23 11:24:50 -040010
11/*
12There are four kinds of slots in the table:
13
141. Unused. me_key == me_value == NULL
15 Does not hold an active (key, value) pair now and never did. Unused can
16 transition to Active upon key insertion. This is the only case in which
17 me_key is NULL, and is each slot's initial state.
18
192. Active. me_key != NULL and me_key != dummy and me_value != NULL
20 Holds an active (key, value) pair. Active can transition to Dummy or
21 Pending upon key deletion (for combined and split tables respectively).
22 This is the only case in which me_value != NULL.
23
243. Dummy. me_key == dummy and me_value == NULL
25 Previously held an active (key, value) pair, but that was deleted and an
26 active pair has not yet overwritten the slot. Dummy can transition to
27 Active upon key insertion. Dummy slots cannot be made Unused again
28 (cannot have me_key set to NULL), else the probe sequence in case of
29 collision would have no way to know they were once active.
30
314. Pending. Not yet inserted or deleted from a split-table.
32 key != NULL, key != dummy and value == NULL
33
34The DictObject can be in one of two forms.
35Either:
36 A combined table:
37 ma_values == NULL, dk_refcnt == 1.
38 Values are stored in the me_value field of the PyDictKeysObject.
39 Slot kind 4 is not allowed i.e.
40 key != NULL, key != dummy and value == NULL is illegal.
41Or:
42 A split table:
43 ma_values != NULL, dk_refcnt >= 1
44 Values are stored in the ma_values array.
45 Only string (unicode) keys are allowed, no <dummy> keys are present.
46
47Note: .popitem() abuses the me_hash field of an Unused or Dummy slot to
48hold a search finger. The me_hash field of Unused or Dummy slots has no
49meaning otherwise. As a consequence of this popitem always converts the dict
50to the combined-table form.
51*/
52
53/* PyDict_MINSIZE_SPLIT is the minimum size of a split dictionary.
54 * It must be a power of 2, and at least 4.
55 * Resizing of split dictionaries is very rare, so the saving memory is more
56 * important than the cost of resizing.
57 */
58#define PyDict_MINSIZE_SPLIT 4
59
60/* PyDict_MINSIZE_COMBINED is the starting size for any new, non-split dict.
61 * 8 allows dicts with no more than 5 active entries; experiments suggested
62 * this suffices for the majority of dicts (consisting mostly of usually-small
63 * dicts created to pass keyword arguments).
64 * Making this 8, rather than 4 reduces the number of resizes for most
65 * dictionaries, without any significant extra memory use.
66 */
67#define PyDict_MINSIZE_COMBINED 8
68
Guido van Rossumc0b618a1997-05-02 03:12:38 +000069#include "Python.h"
Christian Heimes0ded5b52007-12-10 15:50:56 +000070#include "stringlib/eq.h"
Guido van Rossum4b1302b1993-03-27 18:11:32 +000071
Benjamin Peterson7d95e402012-04-23 11:24:50 -040072typedef struct {
73 /* Cached hash code of me_key. */
74 Py_hash_t me_hash;
75 PyObject *me_key;
76 PyObject *me_value; /* This field is only meaningful for combined tables */
77} PyDictKeyEntry;
78
79typedef PyDictKeyEntry *(*dict_lookup_func)
80(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject ***value_addr);
81
82struct _dictkeysobject {
83 Py_ssize_t dk_refcnt;
84 Py_ssize_t dk_size;
85 dict_lookup_func dk_lookup;
86 Py_ssize_t dk_usable;
87 PyDictKeyEntry dk_entries[1];
88};
89
90
91/*
92To ensure the lookup algorithm terminates, there must be at least one Unused
93slot (NULL key) in the table.
94To avoid slowing down lookups on a near-full table, we resize the table when
95it's USABLE_FRACTION (currently two-thirds) full.
96*/
Guido van Rossum16e93a81997-01-28 00:00:11 +000097
Thomas Wouters89f507f2006-12-13 04:49:30 +000098/* Set a key error with the specified argument, wrapping it in a
99 * tuple automatically so that tuple keys are not unpacked as the
100 * exception arguments. */
101static void
102set_key_error(PyObject *arg)
103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 PyObject *tup;
105 tup = PyTuple_Pack(1, arg);
106 if (!tup)
107 return; /* caller will expect error to be set anyway */
108 PyErr_SetObject(PyExc_KeyError, tup);
109 Py_DECREF(tup);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000110}
111
Tim Peterseb28ef22001-06-02 05:27:19 +0000112#define PERTURB_SHIFT 5
113
Guido van Rossum16e93a81997-01-28 00:00:11 +0000114/*
Tim Peterseb28ef22001-06-02 05:27:19 +0000115Major subtleties ahead: Most hash schemes depend on having a "good" hash
116function, in the sense of simulating randomness. Python doesn't: its most
117important hash functions (for strings and ints) are very regular in common
118cases:
Tim Peters15d49292001-05-27 07:39:22 +0000119
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000120 >>> map(hash, (0, 1, 2, 3))
121 [0, 1, 2, 3]
122 >>> map(hash, ("namea", "nameb", "namec", "named"))
123 [-1658398457, -1658398460, -1658398459, -1658398462]
124 >>>
Tim Peters15d49292001-05-27 07:39:22 +0000125
Tim Peterseb28ef22001-06-02 05:27:19 +0000126This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
127the low-order i bits as the initial table index is extremely fast, and there
128are no collisions at all for dicts indexed by a contiguous range of ints.
129The same is approximately true when keys are "consecutive" strings. So this
130gives better-than-random behavior in common cases, and that's very desirable.
Tim Peters15d49292001-05-27 07:39:22 +0000131
Tim Peterseb28ef22001-06-02 05:27:19 +0000132OTOH, when collisions occur, the tendency to fill contiguous slices of the
133hash table makes a good collision resolution strategy crucial. Taking only
134the last i bits of the hash code is also vulnerable: for example, consider
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135the list [i << 16 for i in range(20000)] as a set of keys. Since ints are
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000136their own hash codes, and this fits in a dict of size 2**15, the last 15 bits
137 of every hash code are all 0: they *all* map to the same table index.
Tim Peters15d49292001-05-27 07:39:22 +0000138
Tim Peterseb28ef22001-06-02 05:27:19 +0000139But catering to unusual cases should not slow the usual ones, so we just take
140the last i bits anyway. It's up to collision resolution to do the rest. If
141we *usually* find the key we're looking for on the first try (and, it turns
142out, we usually do -- the table load factor is kept under 2/3, so the odds
143are solidly in our favor), then it makes best sense to keep the initial index
144computation dirt cheap.
Tim Peters15d49292001-05-27 07:39:22 +0000145
Tim Peterseb28ef22001-06-02 05:27:19 +0000146The first half of collision resolution is to visit table indices via this
147recurrence:
Tim Peters15d49292001-05-27 07:39:22 +0000148
Tim Peterseb28ef22001-06-02 05:27:19 +0000149 j = ((5*j) + 1) mod 2**i
Tim Peters15d49292001-05-27 07:39:22 +0000150
Tim Peterseb28ef22001-06-02 05:27:19 +0000151For any initial j in range(2**i), repeating that 2**i times generates each
152int in range(2**i) exactly once (see any text on random-number generation for
153proof). By itself, this doesn't help much: like linear probing (setting
154j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
155order. This would be bad, except that's not the only thing we do, and it's
156actually *good* in the common cases where hash keys are consecutive. In an
157example that's really too small to make this entirely clear, for a table of
158size 2**3 the order of indices is:
Tim Peters15d49292001-05-27 07:39:22 +0000159
Tim Peterseb28ef22001-06-02 05:27:19 +0000160 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
161
162If two things come in at index 5, the first place we look after is index 2,
163not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
164Linear probing is deadly in this case because there the fixed probe order
165is the *same* as the order consecutive keys are likely to arrive. But it's
166extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
167and certain that consecutive hash codes do not.
168
169The other half of the strategy is to get the other bits of the hash code
170into play. This is done by initializing a (unsigned) vrbl "perturb" to the
171full hash code, and changing the recurrence to:
172
173 j = (5*j) + 1 + perturb;
174 perturb >>= PERTURB_SHIFT;
175 use j % 2**i as the next table index;
176
177Now the probe sequence depends (eventually) on every bit in the hash code,
178and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
179because it quickly magnifies small differences in the bits that didn't affect
180the initial index. Note that because perturb is unsigned, if the recurrence
181is executed often enough perturb eventually becomes and remains 0. At that
182point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
183that's certain to find an empty slot eventually (since it generates every int
184in range(2**i), and we make sure there's always at least one empty slot).
185
186Selecting a good value for PERTURB_SHIFT is a balancing act. You want it
187small so that the high bits of the hash code continue to affect the probe
188sequence across iterations; but you want it large so that in really bad cases
189the high-order hash bits have an effect on early iterations. 5 was "the
190best" in minimizing total collisions across experiments Tim Peters ran (on
191both normal and pathological cases), but 4 and 6 weren't significantly worse.
192
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000193Historical: Reimer Behrends contributed the idea of using a polynomial-based
Tim Peterseb28ef22001-06-02 05:27:19 +0000194approach, using repeated multiplication by x in GF(2**n) where an irreducible
195polynomial for each table size was chosen such that x was a primitive root.
196Christian Tismer later extended that to use division by x instead, as an
197efficient way to get the high bits of the hash code into play. This scheme
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000198also gave excellent collision statistics, but was more expensive: two
199if-tests were required inside the loop; computing "the next" index took about
200the same number of operations but without as much potential parallelism
201(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
202above, and then shifting perturb can be done while the table index is being
203masked); and the PyDictObject struct required a member to hold the table's
204polynomial. In Tim's experiments the current scheme ran faster, produced
205equally good collision statistics, needed less code & used less memory.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000206
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000207*/
Tim Petersdea48ec2001-05-22 20:40:22 +0000208
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400209/* Object used as dummy key to fill deleted entries
210 * This could be any unique object,
211 * use a custom type in order to minimise coupling.
212*/
213static PyObject _dummy_struct;
214
215#define dummy (&_dummy_struct)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000216
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000217#ifdef Py_REF_DEBUG
218PyObject *
219_PyDict_Dummy(void)
220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 return dummy;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000222}
223#endif
224
Fred Drake1bff34a2000-08-31 19:31:38 +0000225/* forward declarations */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400226static PyDictKeyEntry *lookdict(PyDictObject *mp, PyObject *key,
227 Py_hash_t hash, PyObject ***value_addr);
228static PyDictKeyEntry *lookdict_unicode(PyDictObject *mp, PyObject *key,
229 Py_hash_t hash, PyObject ***value_addr);
230static PyDictKeyEntry *
231lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
232 Py_hash_t hash, PyObject ***value_addr);
233static PyDictKeyEntry *lookdict_split(PyDictObject *mp, PyObject *key,
234 Py_hash_t hash, PyObject ***value_addr);
Fred Drake1bff34a2000-08-31 19:31:38 +0000235
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400236static int dictresize(PyDictObject *mp, Py_ssize_t minused);
Tim Petersdea48ec2001-05-22 20:40:22 +0000237
Raymond Hettinger43442782004-03-17 21:55:03 +0000238/* Dictionary reuse scheme to save calls to malloc, free, and memset */
Christian Heimes2202f872008-02-06 14:31:34 +0000239#ifndef PyDict_MAXFREELIST
240#define PyDict_MAXFREELIST 80
241#endif
242static PyDictObject *free_list[PyDict_MAXFREELIST];
243static int numfree = 0;
Raymond Hettinger43442782004-03-17 21:55:03 +0000244
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100245int
246PyDict_ClearFreeList(void)
Christian Heimes77c02eb2008-02-09 02:18:51 +0000247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 PyDictObject *op;
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100249 int ret = numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 while (numfree) {
251 op = free_list[--numfree];
252 assert(PyDict_CheckExact(op));
253 PyObject_GC_Del(op);
254 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100255 return ret;
256}
257
258void
259PyDict_Fini(void)
260{
261 PyDict_ClearFreeList();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000262}
263
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400264#define DK_INCREF(dk) (++(dk)->dk_refcnt)
265#define DK_DECREF(dk) if ((--(dk)->dk_refcnt) == 0) free_keys_object(dk)
266#define DK_SIZE(dk) ((dk)->dk_size)
267#define DK_MASK(dk) (((dk)->dk_size)-1)
268#define IS_POWER_OF_2(x) (((x) & (x-1)) == 0)
269
270/* USABLE_FRACTION must obey the following:
271 * (0 < USABLE_FRACTION(n) < n) for all n >= 2
272 *
273 * USABLE_FRACTION should be very quick to calculate.
274 * Fractions around 5/8 to 2/3 seem to work well in practice.
275 */
276
277/* Use (2n+1)/3 rather than 2n+3 because: it makes no difference for
278 * combined tables (the two fractions round to the same number n < ),
279 * but 2*4/3 is 2 whereas (2*4+1)/3 is 3 which potentially saves quite
280 * a lot of space for small, split tables */
281#define USABLE_FRACTION(n) ((((n) << 1)+1)/3)
282
283/* Alternative fraction that is otherwise close enough to (2n+1)/3 to make
284 * little difference. 8 * 2/3 == 8 * 5/8 == 5. 16 * 2/3 == 16 * 5/8 == 10.
285 * 32 * 2/3 = 21, 32 * 5/8 = 20.
286 * Its advantage is that it is faster to compute on machines with slow division.
287 * #define USABLE_FRACTION(n) (((n) >> 1) + ((n) >> 2) - ((n) >> 3))
288*/
289
290
291#define ENSURE_ALLOWS_DELETIONS(d) \
292 if ((d)->ma_keys->dk_lookup == lookdict_unicode_nodummy) { \
293 (d)->ma_keys->dk_lookup = lookdict_unicode; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400295
296/* This immutable, empty PyDictKeysObject is used for PyDict_Clear()
297 * (which cannot fail and thus can do no allocation).
298 */
299static PyDictKeysObject empty_keys_struct = {
300 2, /* dk_refcnt 1 for this struct, 1 for dummy_struct */
301 1, /* dk_size */
302 lookdict_split, /* dk_lookup */
303 0, /* dk_usable (immutable) */
304 {
305 { 0, 0, 0 } /* dk_entries (empty) */
306 }
307};
308
309static PyObject *empty_values[1] = { NULL };
310
311#define Py_EMPTY_KEYS &empty_keys_struct
312
313static PyDictKeysObject *new_keys_object(Py_ssize_t size)
314{
315 PyDictKeysObject *dk;
316 Py_ssize_t i;
317 PyDictKeyEntry *ep0;
318
319 assert(size >= PyDict_MINSIZE_SPLIT);
320 assert(IS_POWER_OF_2(size));
321 dk = PyMem_MALLOC(sizeof(PyDictKeysObject) +
322 sizeof(PyDictKeyEntry) * (size-1));
323 if (dk == NULL) {
324 PyErr_NoMemory();
325 return NULL;
326 }
327 dk->dk_refcnt = 1;
328 dk->dk_size = size;
329 dk->dk_usable = USABLE_FRACTION(size);
330 ep0 = &dk->dk_entries[0];
331 /* Hash value of slot 0 is used by popitem, so it must be initialized */
332 ep0->me_hash = 0;
333 for (i = 0; i < size; i++) {
334 ep0[i].me_key = NULL;
335 ep0[i].me_value = NULL;
336 }
337 dk->dk_lookup = lookdict_unicode_nodummy;
338 return dk;
339}
340
341static void
342free_keys_object(PyDictKeysObject *keys)
343{
344 PyDictKeyEntry *entries = &keys->dk_entries[0];
345 Py_ssize_t i, n;
346 for (i = 0, n = DK_SIZE(keys); i < n; i++) {
347 Py_XDECREF(entries[i].me_key);
348 Py_XDECREF(entries[i].me_value);
349 }
350 PyMem_FREE(keys);
351}
352
353#define new_values(size) PyMem_NEW(PyObject *, size)
354
355#define free_values(values) PyMem_FREE(values)
356
357/* Consumes a reference to the keys object */
358static PyObject *
359new_dict(PyDictKeysObject *keys, PyObject **values)
360{
361 PyDictObject *mp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 if (numfree) {
363 mp = free_list[--numfree];
364 assert (mp != NULL);
365 assert (Py_TYPE(mp) == &PyDict_Type);
366 _Py_NewReference((PyObject *)mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400368 else {
369 mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
370 if (mp == NULL) {
371 DK_DECREF(keys);
372 free_values(values);
373 return NULL;
374 }
375 }
376 mp->ma_keys = keys;
377 mp->ma_values = values;
378 mp->ma_used = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000380}
381
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400382/* Consumes a reference to the keys object */
383static PyObject *
384new_dict_with_shared_keys(PyDictKeysObject *keys)
385{
386 PyObject **values;
387 Py_ssize_t i, size;
388
389 size = DK_SIZE(keys);
390 values = new_values(size);
391 if (values == NULL) {
392 DK_DECREF(keys);
393 return PyErr_NoMemory();
394 }
395 for (i = 0; i < size; i++) {
396 values[i] = NULL;
397 }
398 return new_dict(keys, values);
399}
400
401PyObject *
402PyDict_New(void)
403{
404 return new_dict(new_keys_object(PyDict_MINSIZE_COMBINED), NULL);
405}
406
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000407/*
408The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000409This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000410Open addressing is preferred over chaining since the link overhead for
411chaining would be substantial (100% with typical malloc overhead).
412
Tim Peterseb28ef22001-06-02 05:27:19 +0000413The initial probe index is computed as hash mod the table size. Subsequent
414probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000415
416All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000417
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000418The details in this version are due to Tim Peters, building on many past
Tim Peterseb28ef22001-06-02 05:27:19 +0000419contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000420Christian Tismer.
Fred Drake1bff34a2000-08-31 19:31:38 +0000421
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000422lookdict() is general-purpose, and may return NULL if (and only if) a
423comparison raises an exception (this was new in Python 2.5).
Guido van Rossum89d8c602007-09-18 17:26:56 +0000424lookdict_unicode() below is specialized to string keys, comparison of which can
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400425never raise an exception; that function can never return NULL.
426lookdict_unicode_nodummy is further specialized for string keys that cannot be
427the <dummy> value.
428For both, when the key isn't found a PyDictEntry* is returned
429where the key would have been found, *value_addr points to the matching value
430slot.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000431*/
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400432static PyDictKeyEntry *
433lookdict(PyDictObject *mp, PyObject *key,
434 Py_hash_t hash, PyObject ***value_addr)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 register size_t i;
437 register size_t perturb;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400438 register PyDictKeyEntry *freeslot;
439 register size_t mask = DK_MASK(mp->ma_keys);
440 PyDictKeyEntry *ep0 = &mp->ma_keys->dk_entries[0];
441 register PyDictKeyEntry *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 register int cmp;
443 PyObject *startkey;
Tim Peterseb28ef22001-06-02 05:27:19 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 i = (size_t)hash & mask;
446 ep = &ep0[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400447 if (ep->me_key == NULL || ep->me_key == key) {
448 *value_addr = &ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 return ep;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400450 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 if (ep->me_key == dummy)
452 freeslot = ep;
453 else {
454 if (ep->me_hash == hash) {
455 startkey = ep->me_key;
456 Py_INCREF(startkey);
457 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
458 Py_DECREF(startkey);
459 if (cmp < 0)
460 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400461 if (ep0 == mp->ma_keys->dk_entries && ep->me_key == startkey) {
462 if (cmp > 0) {
463 *value_addr = &ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 return ep;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400465 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 }
467 else {
Victor Stinner198b2912012-03-06 01:03:13 +0100468 PyErr_SetString(PyExc_RuntimeError,
469 "dictionary changed size during lookup");
470 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 }
472 }
473 freeslot = NULL;
474 }
Tim Peters15d49292001-05-27 07:39:22 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 /* In the loop, me_key == dummy is by far (factor of 100s) the
477 least likely outcome, so test for that last. */
478 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
479 i = (i << 2) + i + perturb + 1;
480 ep = &ep0[i & mask];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400481 if (ep->me_key == NULL) {
482 if (freeslot == NULL) {
483 *value_addr = &ep->me_value;
484 return ep;
485 } else {
486 *value_addr = &freeslot->me_value;
487 return freeslot;
488 }
489 }
490 if (ep->me_key == key) {
491 *value_addr = &ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 return ep;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400493 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 if (ep->me_hash == hash && ep->me_key != dummy) {
495 startkey = ep->me_key;
496 Py_INCREF(startkey);
497 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
498 Py_DECREF(startkey);
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400499 if (cmp < 0) {
500 *value_addr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400502 }
503 if (ep0 == mp->ma_keys->dk_entries && ep->me_key == startkey) {
504 if (cmp > 0) {
505 *value_addr = &ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 return ep;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400507 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 }
509 else {
Victor Stinner198b2912012-03-06 01:03:13 +0100510 PyErr_SetString(PyExc_RuntimeError,
511 "dictionary changed size during lookup");
512 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 }
514 }
515 else if (ep->me_key == dummy && freeslot == NULL)
516 freeslot = ep;
517 }
518 assert(0); /* NOT REACHED */
519 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000520}
521
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400522/* Specialized version for string-only keys */
523static PyDictKeyEntry *
524lookdict_unicode(PyDictObject *mp, PyObject *key,
525 Py_hash_t hash, PyObject ***value_addr)
Fred Drake1bff34a2000-08-31 19:31:38 +0000526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 register size_t i;
528 register size_t perturb;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400529 register PyDictKeyEntry *freeslot;
530 register size_t mask = DK_MASK(mp->ma_keys);
531 PyDictKeyEntry *ep0 = &mp->ma_keys->dk_entries[0];
532 register PyDictKeyEntry *ep;
Fred Drake1bff34a2000-08-31 19:31:38 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 /* Make sure this function doesn't have to handle non-unicode keys,
535 including subclasses of str; e.g., one reason to subclass
536 unicodes is to override __eq__, and for speed we don't cater to
537 that here. */
538 if (!PyUnicode_CheckExact(key)) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400539 mp->ma_keys->dk_lookup = lookdict;
540 return lookdict(mp, key, hash, value_addr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 }
Mark Dickinson57e683e2011-09-24 18:18:40 +0100542 i = (size_t)hash & mask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 ep = &ep0[i];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400544 if (ep->me_key == NULL || ep->me_key == key) {
545 *value_addr = &ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 return ep;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400547 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 if (ep->me_key == dummy)
549 freeslot = ep;
550 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400551 if (ep->me_hash == hash && unicode_eq(ep->me_key, key)) {
552 *value_addr = &ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 return ep;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400554 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 freeslot = NULL;
556 }
Tim Peters15d49292001-05-27 07:39:22 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 /* In the loop, me_key == dummy is by far (factor of 100s) the
559 least likely outcome, so test for that last. */
560 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
561 i = (i << 2) + i + perturb + 1;
562 ep = &ep0[i & mask];
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400563 if (ep->me_key == NULL) {
564 if (freeslot == NULL) {
565 *value_addr = &ep->me_value;
566 return ep;
567 } else {
568 *value_addr = &freeslot->me_value;
569 return freeslot;
570 }
571 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 if (ep->me_key == key
573 || (ep->me_hash == hash
574 && ep->me_key != dummy
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400575 && unicode_eq(ep->me_key, key))) {
576 *value_addr = &ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 return ep;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400578 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 if (ep->me_key == dummy && freeslot == NULL)
580 freeslot = ep;
581 }
582 assert(0); /* NOT REACHED */
583 return 0;
Fred Drake1bff34a2000-08-31 19:31:38 +0000584}
585
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400586/* Faster version of lookdict_unicode when it is known that no <dummy> keys
587 * will be present. */
588static PyDictKeyEntry *
589lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
590 Py_hash_t hash, PyObject ***value_addr)
591{
592 register size_t i;
593 register size_t perturb;
594 register size_t mask = DK_MASK(mp->ma_keys);
595 PyDictKeyEntry *ep0 = &mp->ma_keys->dk_entries[0];
596 register PyDictKeyEntry *ep;
597
598 /* Make sure this function doesn't have to handle non-unicode keys,
599 including subclasses of str; e.g., one reason to subclass
600 unicodes is to override __eq__, and for speed we don't cater to
601 that here. */
602 if (!PyUnicode_CheckExact(key)) {
603 mp->ma_keys->dk_lookup = lookdict;
604 return lookdict(mp, key, hash, value_addr);
605 }
606 i = (size_t)hash & mask;
607 ep = &ep0[i];
608 assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
609 if (ep->me_key == NULL || ep->me_key == key ||
610 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
611 *value_addr = &ep->me_value;
612 return ep;
613 }
614 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
615 i = (i << 2) + i + perturb + 1;
616 ep = &ep0[i & mask];
617 assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
618 if (ep->me_key == NULL || ep->me_key == key ||
619 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
620 *value_addr = &ep->me_value;
621 return ep;
622 }
623 }
624 assert(0); /* NOT REACHED */
625 return 0;
626}
627
628/* Version of lookdict for split tables.
629 * All split tables and only split tables use this lookup function.
630 * Split tables only contain unicode keys and no dummy keys,
631 * so algorithm is the same as lookdict_unicode_nodummy.
632 */
633static PyDictKeyEntry *
634lookdict_split(PyDictObject *mp, PyObject *key,
635 Py_hash_t hash, PyObject ***value_addr)
636{
637 register size_t i;
638 register size_t perturb;
639 register size_t mask = DK_MASK(mp->ma_keys);
640 PyDictKeyEntry *ep0 = &mp->ma_keys->dk_entries[0];
641 register PyDictKeyEntry *ep;
642
643 if (!PyUnicode_CheckExact(key)) {
644 return lookdict(mp, key, hash, value_addr);
645 }
646 i = (size_t)hash & mask;
647 ep = &ep0[i];
648 assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
649 if (ep->me_key == NULL || ep->me_key == key ||
650 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
651 *value_addr = &mp->ma_values[i];
652 return ep;
653 }
654 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
655 i = (i << 2) + i + perturb + 1;
656 ep = &ep0[i & mask];
657 assert(ep->me_key == NULL || PyUnicode_CheckExact(ep->me_key));
658 if (ep->me_key == NULL || ep->me_key == key ||
659 (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
660 *value_addr = &mp->ma_values[i & mask];
661 return ep;
662 }
663 }
664 assert(0); /* NOT REACHED */
665 return 0;
666}
667
Benjamin Petersonfb886362010-04-24 18:21:17 +0000668int
669_PyDict_HasOnlyStringKeys(PyObject *dict)
670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 Py_ssize_t pos = 0;
672 PyObject *key, *value;
Benjamin Petersonf6096542010-11-17 22:33:12 +0000673 assert(PyDict_Check(dict));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 /* Shortcut */
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400675 if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 return 1;
677 while (PyDict_Next(dict, &pos, &key, &value))
678 if (!PyUnicode_Check(key))
679 return 0;
680 return 1;
Benjamin Petersonfb886362010-04-24 18:21:17 +0000681}
682
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000683#define MAINTAIN_TRACKING(mp, key, value) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 do { \
685 if (!_PyObject_GC_IS_TRACKED(mp)) { \
686 if (_PyObject_GC_MAY_BE_TRACKED(key) || \
687 _PyObject_GC_MAY_BE_TRACKED(value)) { \
688 _PyObject_GC_TRACK(mp); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 } \
690 } \
691 } while(0)
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000692
693void
694_PyDict_MaybeUntrack(PyObject *op)
695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 PyDictObject *mp;
697 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400698 Py_ssize_t i, size;
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
701 return;
702
703 mp = (PyDictObject *) op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400704 size = DK_SIZE(mp->ma_keys);
705 if (_PyDict_HasSplitTable(mp)) {
706 for (i = 0; i < size; i++) {
707 if ((value = mp->ma_values[i]) == NULL)
708 continue;
709 if (_PyObject_GC_MAY_BE_TRACKED(value)) {
710 assert(!_PyObject_GC_MAY_BE_TRACKED(
711 mp->ma_keys->dk_entries[i].me_key));
712 return;
713 }
714 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400716 else {
717 PyDictKeyEntry *ep0 = &mp->ma_keys->dk_entries[0];
718 for (i = 0; i < size; i++) {
719 if ((value = ep0[i].me_value) == NULL)
720 continue;
721 if (_PyObject_GC_MAY_BE_TRACKED(value) ||
722 _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
723 return;
724 }
725 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 _PyObject_GC_UNTRACK(op);
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000727}
728
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400729/* Internal function to find slot for an item from its hash
730 * when it is known that the key is not present in the dict.
731 */
732static PyDictKeyEntry *
733find_empty_slot(PyDictObject *mp, PyObject *key, Py_hash_t hash,
734 PyObject ***value_addr)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000735{
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400736 size_t i;
737 size_t perturb;
738 size_t mask = DK_MASK(mp->ma_keys);
739 PyDictKeyEntry *ep0 = &mp->ma_keys->dk_entries[0];
740 PyDictKeyEntry *ep;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000741
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400742 assert(key != NULL);
743 if (!PyUnicode_CheckExact(key))
744 mp->ma_keys->dk_lookup = lookdict;
745 i = hash & mask;
746 ep = &ep0[i];
747 for (perturb = hash; ep->me_key != NULL; perturb >>= PERTURB_SHIFT) {
748 i = (i << 2) + i + perturb + 1;
749 ep = &ep0[i & mask];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400751 assert(ep->me_value == NULL);
752 if (mp->ma_values)
753 *value_addr = &mp->ma_values[i & mask];
754 else
755 *value_addr = &ep->me_value;
756 return ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000757}
758
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400759static int
760insertion_resize(PyDictObject *mp)
761{
762 /*
763 * Double the size of the dict,
764 * Previous versions quadrupled size, but doing so may result in excessive
765 * memory use. Doubling keeps the number of resizes low without wasting
766 * too much memory.
767 */
768 return dictresize(mp, 2 * mp->ma_used);
769}
Antoine Pitroue965d972012-02-27 00:45:12 +0100770
771/*
772Internal routine to insert a new item into the table.
773Used both by the internal resize routine and by the public insert routine.
774Eats a reference to key and one to value.
775Returns -1 if an error occurred, or 0 on success.
776*/
777static int
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400778insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +0100779{
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400780 PyObject *old_value;
781 PyObject **value_addr;
782 PyDictKeyEntry *ep;
783 assert(key != dummy);
Antoine Pitroue965d972012-02-27 00:45:12 +0100784
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400785 if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
786 if (insertion_resize(mp) < 0)
787 return -1;
788 }
789
790 ep = mp->ma_keys->dk_lookup(mp, key, hash, &value_addr);
Antoine Pitroue965d972012-02-27 00:45:12 +0100791 if (ep == NULL) {
792 Py_DECREF(key);
793 Py_DECREF(value);
794 return -1;
795 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400796 MAINTAIN_TRACKING(mp, key, value);
797 old_value = *value_addr;
798 if (old_value != NULL) {
799 assert(ep->me_key != NULL && ep->me_key != dummy);
800 *value_addr = value;
801 Py_DECREF(old_value); /* which **CAN** re-enter */
802 Py_DECREF(key);
803 }
804 else {
805 if (ep->me_key == NULL) {
806 if (mp->ma_keys->dk_usable <= 0) {
807 /* Need to resize. */
808 if (insertion_resize(mp) < 0) {
809 Py_DECREF(key);
810 Py_DECREF(value);
811 return -1;
812 }
813 ep = find_empty_slot(mp, key, hash, &value_addr);
814 }
815 mp->ma_keys->dk_usable--;
816 assert(mp->ma_keys->dk_usable >= 0);
817 ep->me_key = key;
818 ep->me_hash = hash;
819 }
820 else {
821 if (ep->me_key == dummy) {
822 ep->me_key = key;
823 ep->me_hash = hash;
824 Py_DECREF(dummy);
825 } else {
826 Py_DECREF(key);
827 assert(_PyDict_HasSplitTable(mp));
828 }
829 }
830 mp->ma_used++;
831 *value_addr = value;
832 }
833 assert(ep->me_key != NULL && ep->me_key != dummy);
834 assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
835 return 0;
Antoine Pitroue965d972012-02-27 00:45:12 +0100836}
837
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000838/*
839Internal routine used by dictresize() to insert an item which is
840known to be absent from the dict. This routine also assumes that
841the dict contains no deleted entries. Besides the performance benefit,
842using insertdict() in dictresize() is dangerous (SF bug #1456209).
843Note that no refcounts are changed by this routine; if needed, the caller
844is responsible for incref'ing `key` and `value`.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400845Neither mp->ma_used nor k->dk_usable are modified by this routine; the caller
846must set them correctly
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000847*/
848static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400849insertdict_clean(PyDictObject *mp, PyObject *key, Py_hash_t hash,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 PyObject *value)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000851{
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400852 size_t i;
853 size_t perturb;
854 PyDictKeysObject *k = mp->ma_keys;
855 size_t mask = (size_t)DK_SIZE(k)-1;
856 PyDictKeyEntry *ep0 = &k->dk_entries[0];
857 PyDictKeyEntry *ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000858
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400859 assert(k->dk_lookup != NULL);
860 assert(value != NULL);
861 assert(key != NULL);
862 assert(key != dummy);
863 assert(PyUnicode_CheckExact(key) || k->dk_lookup == lookdict);
864 i = hash & mask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 ep = &ep0[i];
866 for (perturb = hash; ep->me_key != NULL; perturb >>= PERTURB_SHIFT) {
867 i = (i << 2) + i + perturb + 1;
868 ep = &ep0[i & mask];
869 }
870 assert(ep->me_value == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 ep->me_key = key;
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000872 ep->me_hash = hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 ep->me_value = value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000874}
875
876/*
877Restructure the table by allocating a new table and reinserting all
878items again. When entries have been deleted, the new table may
879actually be smaller than the old one.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400880If a table is split (its keys and hashes are shared, its values are not),
881then the values are temporarily copied into the table, it is resized as
882a combined table, then the me_value slots in the old table are NULLed out.
883After resizing a table is always combined,
884but can be resplit by make_keys_shared().
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000885*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000886static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000887dictresize(PyDictObject *mp, Py_ssize_t minused)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 Py_ssize_t newsize;
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400890 PyDictKeysObject *oldkeys;
891 PyObject **oldvalues;
892 Py_ssize_t i, oldsize;
Tim Peters91a364d2001-05-19 07:04:38 +0000893
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400894/* Find the smallest table size > minused. */
895 for (newsize = PyDict_MINSIZE_COMBINED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 newsize <= minused && newsize > 0;
897 newsize <<= 1)
898 ;
899 if (newsize <= 0) {
900 PyErr_NoMemory();
901 return -1;
902 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400903 oldkeys = mp->ma_keys;
904 oldvalues = mp->ma_values;
905 /* Allocate a new table. */
906 mp->ma_keys = new_keys_object(newsize);
907 if (mp->ma_keys == NULL) {
908 mp->ma_keys = oldkeys;
909 return -1;
910 }
911 if (oldkeys->dk_lookup == lookdict)
912 mp->ma_keys->dk_lookup = lookdict;
913 oldsize = DK_SIZE(oldkeys);
914 mp->ma_values = NULL;
915 /* If empty then nothing to copy so just return */
916 if (oldsize == 1) {
917 assert(oldkeys == Py_EMPTY_KEYS);
918 DK_DECREF(oldkeys);
919 return 0;
920 }
921 /* Main loop below assumes we can transfer refcount to new keys
922 * and that value is stored in me_value.
923 * Increment ref-counts and copy values here to compensate
924 * This (resizing a split table) should be relatively rare */
925 if (oldvalues != NULL) {
926 for (i = 0; i < oldsize; i++) {
927 if (oldvalues[i] != NULL) {
928 Py_INCREF(oldkeys->dk_entries[i].me_key);
929 oldkeys->dk_entries[i].me_value = oldvalues[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 }
932 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400933 /* Main loop */
934 for (i = 0; i < oldsize; i++) {
935 PyDictKeyEntry *ep = &oldkeys->dk_entries[i];
936 if (ep->me_value != NULL) {
937 assert(ep->me_key != dummy);
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000938 insertdict_clean(mp, ep->me_key, ep->me_hash, ep->me_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400941 mp->ma_keys->dk_usable -= mp->ma_used;
942 if (oldvalues != NULL) {
943 /* NULL out me_value slot in oldkeys, in case it was shared */
944 for (i = 0; i < oldsize; i++)
945 oldkeys->dk_entries[i].me_value = NULL;
946 assert(oldvalues != empty_values);
947 free_values(oldvalues);
948 DK_DECREF(oldkeys);
949 }
950 else {
951 assert(oldkeys->dk_lookup != lookdict_split);
952 if (oldkeys->dk_lookup != lookdict_unicode_nodummy) {
953 PyDictKeyEntry *ep0 = &oldkeys->dk_entries[0];
954 for (i = 0; i < oldsize; i++) {
955 if (ep0[i].me_key == dummy)
956 Py_DECREF(dummy);
957 }
958 }
959 assert(oldkeys->dk_refcnt == 1);
960 PyMem_FREE(oldkeys);
961 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000963}
964
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400965static PyDictKeysObject *
966make_keys_shared(PyObject *op)
967{
968 Py_ssize_t i;
969 Py_ssize_t size;
970 PyDictObject *mp = (PyDictObject *)op;
971
972 assert(PyDict_CheckExact(op));
973 if (!_PyDict_HasSplitTable(mp)) {
974 PyDictKeyEntry *ep0;
975 PyObject **values;
976 assert(mp->ma_keys->dk_refcnt == 1);
977 if (mp->ma_keys->dk_lookup == lookdict) {
978 return NULL;
979 }
980 else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
981 /* Remove dummy keys */
982 if (dictresize(mp, DK_SIZE(mp->ma_keys)))
983 return NULL;
984 }
985 assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
986 /* Copy values into a new array */
987 ep0 = &mp->ma_keys->dk_entries[0];
988 size = DK_SIZE(mp->ma_keys);
989 values = new_values(size);
990 if (values == NULL) {
991 PyErr_SetString(PyExc_MemoryError,
992 "Not enough memory to allocate new values array");
993 return NULL;
994 }
995 for (i = 0; i < size; i++) {
996 values[i] = ep0[i].me_value;
997 ep0[i].me_value = NULL;
998 }
999 mp->ma_keys->dk_lookup = lookdict_split;
1000 mp->ma_values = values;
1001 }
1002 DK_INCREF(mp->ma_keys);
1003 return mp->ma_keys;
1004}
Christian Heimes99170a52007-12-19 02:07:34 +00001005
1006PyObject *
1007_PyDict_NewPresized(Py_ssize_t minused)
1008{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001009 Py_ssize_t newsize;
1010 PyDictKeysObject *new_keys;
1011 for (newsize = PyDict_MINSIZE_COMBINED;
1012 newsize <= minused && newsize > 0;
1013 newsize <<= 1)
1014 ;
1015 new_keys = new_keys_object(newsize);
1016 if (new_keys == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001018 return new_dict(new_keys, NULL);
Christian Heimes99170a52007-12-19 02:07:34 +00001019}
1020
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001021/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
1022 * that may occur (originally dicts supported only string keys, and exceptions
1023 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001024 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001025 * (suppressed) occurred while computing the key's hash, or that some error
1026 * (suppressed) occurred when comparing keys in the dict's internal probe
1027 * sequence. A nasty example of the latter is when a Python-coded comparison
1028 * function hits a stack-depth error, which can cause this to return NULL
1029 * even if the key is present.
1030 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001031PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001032PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001033{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001034 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001036 PyDictKeyEntry *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 PyThreadState *tstate;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001038 PyObject **value_addr;
1039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 if (!PyDict_Check(op))
1041 return NULL;
1042 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001043 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 {
1045 hash = PyObject_Hash(key);
1046 if (hash == -1) {
1047 PyErr_Clear();
1048 return NULL;
1049 }
1050 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 /* We can arrive here with a NULL tstate during initialization: try
1053 running "python -Wi" for an example related to string interning.
1054 Let's just hope that no exception occurs then... This must be
1055 _PyThreadState_Current and not PyThreadState_GET() because in debug
1056 mode, the latter complains if tstate is NULL. */
1057 tstate = (PyThreadState*)_Py_atomic_load_relaxed(
1058 &_PyThreadState_Current);
1059 if (tstate != NULL && tstate->curexc_type != NULL) {
1060 /* preserve the existing exception */
1061 PyObject *err_type, *err_value, *err_tb;
1062 PyErr_Fetch(&err_type, &err_value, &err_tb);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001063 ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 /* ignore errors */
1065 PyErr_Restore(err_type, err_value, err_tb);
1066 if (ep == NULL)
1067 return NULL;
1068 }
1069 else {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001070 ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 if (ep == NULL) {
1072 PyErr_Clear();
1073 return NULL;
1074 }
1075 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001076 return *value_addr;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001077}
1078
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001079/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
1080 This returns NULL *with* an exception set if an exception occurred.
1081 It returns NULL *without* an exception set if the key wasn't present.
1082*/
1083PyObject *
1084PyDict_GetItemWithError(PyObject *op, PyObject *key)
1085{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001086 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 PyDictObject*mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001088 PyDictKeyEntry *ep;
1089 PyObject **value_addr;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 if (!PyDict_Check(op)) {
1092 PyErr_BadInternalCall();
1093 return NULL;
1094 }
1095 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001096 (hash = ((PyASCIIObject *) key)->hash) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 {
1098 hash = PyObject_Hash(key);
1099 if (hash == -1) {
1100 return NULL;
1101 }
1102 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001103
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001104 ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 if (ep == NULL)
1106 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001107 return *value_addr;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001108}
1109
Brett Cannonfd074152012-04-14 14:10:13 -04001110PyObject *
1111_PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
1112{
1113 PyObject *kv;
1114 kv = _PyUnicode_FromId(key); /* borrowed */
1115 if (kv == NULL)
1116 return NULL;
1117 return PyDict_GetItemWithError(dp, kv);
1118}
1119
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001120/* Fast version of global value lookup.
1121 * Lookup in globals, then builtins.
1122 */
1123PyObject *
1124_PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001125{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001126 PyObject *x;
1127 if (PyUnicode_CheckExact(key)) {
1128 PyObject **value_addr;
1129 Py_hash_t hash = ((PyASCIIObject *)key)->hash;
1130 if (hash != -1) {
1131 PyDictKeyEntry *e;
1132 e = globals->ma_keys->dk_lookup(globals, key, hash, &value_addr);
1133 if (e == NULL) {
1134 return NULL;
1135 }
1136 x = *value_addr;
1137 if (x != NULL)
1138 return x;
1139 e = builtins->ma_keys->dk_lookup(builtins, key, hash, &value_addr);
1140 if (e == NULL) {
1141 return NULL;
1142 }
1143 x = *value_addr;
1144 return x;
1145 }
Antoine Pitroue965d972012-02-27 00:45:12 +01001146 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001147 x = PyDict_GetItemWithError((PyObject *)globals, key);
1148 if (x != NULL)
1149 return x;
1150 if (PyErr_Occurred())
1151 return NULL;
1152 return PyDict_GetItemWithError((PyObject *)builtins, key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001153}
1154
Antoine Pitroue965d972012-02-27 00:45:12 +01001155/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
1156 * dictionary if it's merely replacing the value for an existing key.
1157 * This means that it's safe to loop over a dictionary with PyDict_Next()
1158 * and occasionally replace a value -- but you can't insert new keys or
1159 * remove them.
1160 */
1161int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001162PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
Antoine Pitroue965d972012-02-27 00:45:12 +01001163{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001164 PyDictObject *mp;
1165 Py_hash_t hash;
Antoine Pitroue965d972012-02-27 00:45:12 +01001166 if (!PyDict_Check(op)) {
1167 PyErr_BadInternalCall();
1168 return -1;
1169 }
1170 assert(key);
1171 assert(value);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001172 mp = (PyDictObject *)op;
1173 if (!PyUnicode_CheckExact(key) ||
1174 (hash = ((PyASCIIObject *) key)->hash) == -1)
1175 {
Antoine Pitroue965d972012-02-27 00:45:12 +01001176 hash = PyObject_Hash(key);
1177 if (hash == -1)
1178 return -1;
1179 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001180 Py_INCREF(value);
1181 Py_INCREF(key);
1182
1183 /* insertdict() handles any resizing that might be necessary */
1184 return insertdict(mp, key, hash, value);
Antoine Pitroue965d972012-02-27 00:45:12 +01001185}
1186
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001187int
Tim Peters1f5871e2000-07-04 17:44:48 +00001188PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001189{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001190 PyDictObject *mp;
1191 Py_hash_t hash;
1192 PyDictKeyEntry *ep;
1193 PyObject *old_key, *old_value;
1194 PyObject **value_addr;
Guido van Rossumd7047b31995-01-02 19:07:15 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 if (!PyDict_Check(op)) {
1197 PyErr_BadInternalCall();
1198 return -1;
1199 }
1200 assert(key);
1201 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001202 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 hash = PyObject_Hash(key);
1204 if (hash == -1)
1205 return -1;
1206 }
1207 mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001208 ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 if (ep == NULL)
1210 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001211 if (*value_addr == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 set_key_error(key);
1213 return -1;
1214 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001215 old_value = *value_addr;
1216 *value_addr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 mp->ma_used--;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001218 if (!_PyDict_HasSplitTable(mp)) {
1219 ENSURE_ALLOWS_DELETIONS(mp);
1220 old_key = ep->me_key;
1221 Py_INCREF(dummy);
1222 ep->me_key = dummy;
1223 Py_DECREF(old_key);
1224 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 Py_DECREF(old_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001227}
1228
Guido van Rossum25831651993-05-19 14:50:45 +00001229void
Tim Peters1f5871e2000-07-04 17:44:48 +00001230PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 PyDictObject *mp;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001233 PyDictKeysObject *oldkeys;
1234 PyObject **oldvalues;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (!PyDict_Check(op))
1238 return;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001239 mp = ((PyDictObject *)op);
1240 oldkeys = mp->ma_keys;
1241 oldvalues = mp->ma_values;
1242 if (oldvalues == empty_values)
1243 return;
1244 /* Empty the dict... */
1245 DK_INCREF(Py_EMPTY_KEYS);
1246 mp->ma_keys = Py_EMPTY_KEYS;
1247 mp->ma_values = empty_values;
1248 mp->ma_used = 0;
1249 /* ...then clear the keys and values */
1250 if (oldvalues != NULL) {
1251 n = DK_SIZE(oldkeys);
1252 for (i = 0; i < n; i++)
1253 Py_CLEAR(oldvalues[i]);
1254 free_values(oldvalues);
1255 DK_DECREF(oldkeys);
1256 }
1257 else {
1258 assert(oldkeys->dk_refcnt == 1);
1259 free_keys_object(oldkeys);
1260 }
1261}
1262
1263/* Returns -1 if no more items (or op is not a dict),
1264 * index of item otherwise. Stores value in pvalue
1265 */
1266Py_LOCAL_INLINE(Py_ssize_t)
1267dict_next(PyObject *op, Py_ssize_t i, PyObject **pvalue)
1268{
1269 Py_ssize_t mask, offset;
1270 PyDictObject *mp;
1271 PyObject **value_ptr;
1272
1273
1274 if (!PyDict_Check(op))
1275 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001277 if (i < 0)
1278 return -1;
1279 if (mp->ma_values) {
1280 value_ptr = &mp->ma_values[i];
1281 offset = sizeof(PyObject *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001283 else {
1284 value_ptr = &mp->ma_keys->dk_entries[i].me_value;
1285 offset = sizeof(PyDictKeyEntry);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001287 mask = DK_MASK(mp->ma_keys);
1288 while (i <= mask && *value_ptr == NULL) {
1289 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
1290 i++;
1291 }
1292 if (i > mask)
1293 return -1;
1294 if (pvalue)
1295 *pvalue = *value_ptr;
1296 return i;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001297}
1298
Tim Peters080c88b2003-02-15 03:01:11 +00001299/*
1300 * Iterate over a dict. Use like so:
1301 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001302 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +00001303 * PyObject *key, *value;
1304 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +00001305 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Tim Peters080c88b2003-02-15 03:01:11 +00001306 * Refer to borrowed references in key and value.
1307 * }
1308 *
1309 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +00001310 * mutates the dict. One exception: it is safe if the loop merely changes
1311 * the values associated with the keys (but doesn't insert new keys or
1312 * delete keys), via PyDict_SetItem().
1313 */
Guido van Rossum25831651993-05-19 14:50:45 +00001314int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001315PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001316{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001317 PyDictObject *mp;
1318 Py_ssize_t i = dict_next(op, *ppos, pvalue);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 if (i < 0)
1320 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001321 mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 *ppos = i+1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 if (pkey)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001324 *pkey = mp->ma_keys->dk_entries[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001326}
1327
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001328/* Internal version of PyDict_Next that returns a hash value in addition
1329 * to the key and value.
1330 */
Thomas Wouterscf297e42007-02-23 15:07:44 +00001331int
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001332_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
1333 PyObject **pvalue, Py_hash_t *phash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001334{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001335 PyDictObject *mp;
1336 Py_ssize_t i = dict_next(op, *ppos, pvalue);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 if (i < 0)
1338 return 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001339 mp = (PyDictObject *)op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 *ppos = i+1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001341 *phash = mp->ma_keys->dk_entries[i].me_hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 if (pkey)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001343 *pkey = mp->ma_keys->dk_entries[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 return 1;
Thomas Wouterscf297e42007-02-23 15:07:44 +00001345}
1346
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001347/* Methods */
1348
1349static void
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001350dict_dealloc(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001351{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001352 PyObject **values = mp->ma_values;
1353 PyDictKeysObject *keys = mp->ma_keys;
1354 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 PyObject_GC_UnTrack(mp);
1356 Py_TRASHCAN_SAFE_BEGIN(mp)
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001357 if (values != NULL) {
1358 if (values != empty_values) {
1359 for (i = 0, n = DK_SIZE(mp->ma_keys); i < n; i++) {
1360 Py_XDECREF(values[i]);
1361 }
1362 free_values(values);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001364 DK_DECREF(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001366 else {
1367 free_keys_object(keys);
1368 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
1370 free_list[numfree++] = mp;
1371 else
1372 Py_TYPE(mp)->tp_free((PyObject *)mp);
1373 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001374}
1375
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001376
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001377static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001378dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 Py_ssize_t i;
1381 PyObject *s, *temp, *colon = NULL;
1382 PyObject *pieces = NULL, *result = NULL;
1383 PyObject *key, *value;
Guido van Rossum255443b1998-04-10 22:47:14 +00001384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 i = Py_ReprEnter((PyObject *)mp);
1386 if (i != 0) {
1387 return i > 0 ? PyUnicode_FromString("{...}") : NULL;
1388 }
Guido van Rossum255443b1998-04-10 22:47:14 +00001389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 if (mp->ma_used == 0) {
1391 result = PyUnicode_FromString("{}");
1392 goto Done;
1393 }
Tim Petersa7259592001-06-16 05:11:17 +00001394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 pieces = PyList_New(0);
1396 if (pieces == NULL)
1397 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +00001398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 colon = PyUnicode_FromString(": ");
1400 if (colon == NULL)
1401 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 /* Do repr() on each key+value pair, and insert ": " between them.
1404 Note that repr may mutate the dict. */
1405 i = 0;
1406 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
1407 int status;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001408 /* Prevent repr from deleting key or value during key format. */
1409 Py_INCREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 Py_INCREF(value);
1411 s = PyObject_Repr(key);
1412 PyUnicode_Append(&s, colon);
1413 PyUnicode_AppendAndDel(&s, PyObject_Repr(value));
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001414 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 Py_DECREF(value);
1416 if (s == NULL)
1417 goto Done;
1418 status = PyList_Append(pieces, s);
1419 Py_DECREF(s); /* append created a new ref */
1420 if (status < 0)
1421 goto Done;
1422 }
Tim Petersa7259592001-06-16 05:11:17 +00001423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 /* Add "{}" decorations to the first and last items. */
1425 assert(PyList_GET_SIZE(pieces) > 0);
1426 s = PyUnicode_FromString("{");
1427 if (s == NULL)
1428 goto Done;
1429 temp = PyList_GET_ITEM(pieces, 0);
1430 PyUnicode_AppendAndDel(&s, temp);
1431 PyList_SET_ITEM(pieces, 0, s);
1432 if (s == NULL)
1433 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +00001434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 s = PyUnicode_FromString("}");
1436 if (s == NULL)
1437 goto Done;
1438 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
1439 PyUnicode_AppendAndDel(&temp, s);
1440 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
1441 if (temp == NULL)
1442 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 /* Paste them all together with ", " between. */
1445 s = PyUnicode_FromString(", ");
1446 if (s == NULL)
1447 goto Done;
1448 result = PyUnicode_Join(s, pieces);
1449 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +00001450
1451Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 Py_XDECREF(pieces);
1453 Py_XDECREF(colon);
1454 Py_ReprLeave((PyObject *)mp);
1455 return result;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001456}
1457
Martin v. Löwis18e16552006-02-15 17:27:45 +00001458static Py_ssize_t
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001459dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 return mp->ma_used;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001462}
1463
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001464static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001465dict_subscript(PyDictObject *mp, register PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 PyObject *v;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001468 Py_hash_t hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001469 PyDictKeyEntry *ep;
1470 PyObject **value_addr;
1471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001473 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 hash = PyObject_Hash(key);
1475 if (hash == -1)
1476 return NULL;
1477 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001478 ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 if (ep == NULL)
1480 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001481 v = *value_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 if (v == NULL) {
1483 if (!PyDict_CheckExact(mp)) {
1484 /* Look up __missing__ method if we're a subclass. */
1485 PyObject *missing, *res;
Benjamin Petersonce798522012-01-22 11:24:29 -05001486 _Py_IDENTIFIER(__missing__);
1487 missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 if (missing != NULL) {
1489 res = PyObject_CallFunctionObjArgs(missing,
1490 key, NULL);
1491 Py_DECREF(missing);
1492 return res;
1493 }
1494 else if (PyErr_Occurred())
1495 return NULL;
1496 }
1497 set_key_error(key);
1498 return NULL;
1499 }
1500 else
1501 Py_INCREF(v);
1502 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001503}
1504
1505static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001506dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 if (w == NULL)
1509 return PyDict_DelItem((PyObject *)mp, v);
1510 else
1511 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001512}
1513
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001514static PyMappingMethods dict_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 (lenfunc)dict_length, /*mp_length*/
1516 (binaryfunc)dict_subscript, /*mp_subscript*/
1517 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001518};
1519
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001520static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001521dict_keys(register PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 register PyObject *v;
1524 register Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001525 PyDictKeyEntry *ep;
1526 Py_ssize_t size, n, offset;
1527 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001528
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001529 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 n = mp->ma_used;
1531 v = PyList_New(n);
1532 if (v == NULL)
1533 return NULL;
1534 if (n != mp->ma_used) {
1535 /* Durnit. The allocations caused the dict to resize.
1536 * Just start over, this shouldn't normally happen.
1537 */
1538 Py_DECREF(v);
1539 goto again;
1540 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001541 ep = &mp->ma_keys->dk_entries[0];
1542 size = DK_SIZE(mp->ma_keys);
1543 if (mp->ma_values) {
1544 value_ptr = mp->ma_values;
1545 offset = sizeof(PyObject *);
1546 }
1547 else {
1548 value_ptr = &ep[0].me_value;
1549 offset = sizeof(PyDictKeyEntry);
1550 }
1551 for (i = 0, j = 0; i < size; i++) {
1552 if (*value_ptr != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 PyObject *key = ep[i].me_key;
1554 Py_INCREF(key);
1555 PyList_SET_ITEM(v, j, key);
1556 j++;
1557 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001558 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 }
1560 assert(j == n);
1561 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001562}
1563
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001564static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001565dict_values(register PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 register PyObject *v;
1568 register Py_ssize_t i, j;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001569 Py_ssize_t size, n, offset;
1570 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001571
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001572 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 n = mp->ma_used;
1574 v = PyList_New(n);
1575 if (v == NULL)
1576 return NULL;
1577 if (n != mp->ma_used) {
1578 /* Durnit. The allocations caused the dict to resize.
1579 * Just start over, this shouldn't normally happen.
1580 */
1581 Py_DECREF(v);
1582 goto again;
1583 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001584 size = DK_SIZE(mp->ma_keys);
1585 if (mp->ma_values) {
1586 value_ptr = mp->ma_values;
1587 offset = sizeof(PyObject *);
1588 }
1589 else {
1590 value_ptr = &mp->ma_keys->dk_entries[0].me_value;
1591 offset = sizeof(PyDictKeyEntry);
1592 }
1593 for (i = 0, j = 0; i < size; i++) {
1594 PyObject *value = *value_ptr;
1595 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
1596 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 Py_INCREF(value);
1598 PyList_SET_ITEM(v, j, value);
1599 j++;
1600 }
1601 }
1602 assert(j == n);
1603 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00001604}
1605
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001606static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001607dict_items(register PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 register PyObject *v;
1610 register Py_ssize_t i, j, n;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001611 Py_ssize_t size, offset;
1612 PyObject *item, *key;
1613 PyDictKeyEntry *ep;
1614 PyObject **value_ptr;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 /* Preallocate the list of tuples, to avoid allocations during
1617 * the loop over the items, which could trigger GC, which
1618 * could resize the dict. :-(
1619 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001620 again:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 n = mp->ma_used;
1622 v = PyList_New(n);
1623 if (v == NULL)
1624 return NULL;
1625 for (i = 0; i < n; i++) {
1626 item = PyTuple_New(2);
1627 if (item == NULL) {
1628 Py_DECREF(v);
1629 return NULL;
1630 }
1631 PyList_SET_ITEM(v, i, item);
1632 }
1633 if (n != mp->ma_used) {
1634 /* Durnit. The allocations caused the dict to resize.
1635 * Just start over, this shouldn't normally happen.
1636 */
1637 Py_DECREF(v);
1638 goto again;
1639 }
1640 /* Nothing we do below makes any function calls. */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001641 ep = mp->ma_keys->dk_entries;
1642 size = DK_SIZE(mp->ma_keys);
1643 if (mp->ma_values) {
1644 value_ptr = mp->ma_values;
1645 offset = sizeof(PyObject *);
1646 }
1647 else {
1648 value_ptr = &ep[0].me_value;
1649 offset = sizeof(PyDictKeyEntry);
1650 }
1651 for (i = 0, j = 0; i < size; i++) {
1652 PyObject *value = *value_ptr;
1653 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
1654 if (value != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 key = ep[i].me_key;
1656 item = PyList_GET_ITEM(v, j);
1657 Py_INCREF(key);
1658 PyTuple_SET_ITEM(item, 0, key);
1659 Py_INCREF(value);
1660 PyTuple_SET_ITEM(item, 1, value);
1661 j++;
1662 }
1663 }
1664 assert(j == n);
1665 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00001666}
1667
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001668static PyObject *
Tim Petersbca1cbc2002-12-09 22:56:13 +00001669dict_fromkeys(PyObject *cls, PyObject *args)
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 PyObject *seq;
1672 PyObject *value = Py_None;
1673 PyObject *it; /* iter(seq) */
1674 PyObject *key;
1675 PyObject *d;
1676 int status;
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 if (!PyArg_UnpackTuple(args, "fromkeys", 1, 2, &seq, &value))
1679 return NULL;
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 d = PyObject_CallObject(cls, NULL);
1682 if (d == NULL)
1683 return NULL;
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 if (PyDict_CheckExact(d) && PyDict_CheckExact(seq)) {
1686 PyDictObject *mp = (PyDictObject *)d;
1687 PyObject *oldvalue;
1688 Py_ssize_t pos = 0;
1689 PyObject *key;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001690 Py_hash_t hash;
Guido van Rossum58da9312007-11-10 23:39:45 +00001691
Petri Lehtinena94200e2011-10-24 21:12:58 +03001692 if (dictresize(mp, Py_SIZE(seq))) {
1693 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 return NULL;
Petri Lehtinena94200e2011-10-24 21:12:58 +03001695 }
Guido van Rossum58da9312007-11-10 23:39:45 +00001696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 while (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash)) {
1698 Py_INCREF(key);
1699 Py_INCREF(value);
Petri Lehtinena94200e2011-10-24 21:12:58 +03001700 if (insertdict(mp, key, hash, value)) {
1701 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 return NULL;
Petri Lehtinena94200e2011-10-24 21:12:58 +03001703 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 }
1705 return d;
1706 }
Guido van Rossum58da9312007-11-10 23:39:45 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 if (PyDict_CheckExact(d) && PyAnySet_CheckExact(seq)) {
1709 PyDictObject *mp = (PyDictObject *)d;
1710 Py_ssize_t pos = 0;
1711 PyObject *key;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001712 Py_hash_t hash;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001713
Petri Lehtinena94200e2011-10-24 21:12:58 +03001714 if (dictresize(mp, PySet_GET_SIZE(seq))) {
1715 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 return NULL;
Petri Lehtinena94200e2011-10-24 21:12:58 +03001717 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 while (_PySet_NextEntry(seq, &pos, &key, &hash)) {
1720 Py_INCREF(key);
1721 Py_INCREF(value);
Petri Lehtinena94200e2011-10-24 21:12:58 +03001722 if (insertdict(mp, key, hash, value)) {
1723 Py_DECREF(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 return NULL;
Petri Lehtinena94200e2011-10-24 21:12:58 +03001725 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 }
1727 return d;
1728 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 it = PyObject_GetIter(seq);
1731 if (it == NULL){
1732 Py_DECREF(d);
1733 return NULL;
1734 }
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 if (PyDict_CheckExact(d)) {
1737 while ((key = PyIter_Next(it)) != NULL) {
1738 status = PyDict_SetItem(d, key, value);
1739 Py_DECREF(key);
1740 if (status < 0)
1741 goto Fail;
1742 }
1743 } else {
1744 while ((key = PyIter_Next(it)) != NULL) {
1745 status = PyObject_SetItem(d, key, value);
1746 Py_DECREF(key);
1747 if (status < 0)
1748 goto Fail;
1749 }
1750 }
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 if (PyErr_Occurred())
1753 goto Fail;
1754 Py_DECREF(it);
1755 return d;
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001756
1757Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 Py_DECREF(it);
1759 Py_DECREF(d);
1760 return NULL;
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001761}
1762
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001763static int
1764dict_update_common(PyObject *self, PyObject *args, PyObject *kwds, char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 PyObject *arg = NULL;
1767 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
1770 result = -1;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 else if (arg != NULL) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001773 _Py_IDENTIFIER(keys);
1774 if (_PyObject_HasAttrId(arg, &PyId_keys))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 result = PyDict_Merge(self, arg, 1);
1776 else
1777 result = PyDict_MergeFromSeq2(self, arg, 1);
1778 }
1779 if (result == 0 && kwds != NULL) {
1780 if (PyArg_ValidateKeywordArguments(kwds))
1781 result = PyDict_Merge(self, kwds, 1);
1782 else
1783 result = -1;
1784 }
1785 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001786}
1787
1788static PyObject *
1789dict_update(PyObject *self, PyObject *args, PyObject *kwds)
1790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 if (dict_update_common(self, args, kwds, "update") != -1)
1792 Py_RETURN_NONE;
1793 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001794}
1795
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001796/* Update unconditionally replaces existing items.
1797 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00001798 otherwise it leaves existing items unchanged.
1799
1800 PyDict_{Update,Merge} update/merge from a mapping object.
1801
Tim Petersf582b822001-12-11 18:51:08 +00001802 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00001803 producing iterable objects of length 2.
1804*/
1805
Tim Petersf582b822001-12-11 18:51:08 +00001806int
Tim Peters1fc240e2001-10-26 05:06:50 +00001807PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
1808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 PyObject *it; /* iter(seq2) */
1810 Py_ssize_t i; /* index into seq2 of current element */
1811 PyObject *item; /* seq2[i] */
1812 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00001813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 assert(d != NULL);
1815 assert(PyDict_Check(d));
1816 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00001817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 it = PyObject_GetIter(seq2);
1819 if (it == NULL)
1820 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00001821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 for (i = 0; ; ++i) {
1823 PyObject *key, *value;
1824 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00001825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 fast = NULL;
1827 item = PyIter_Next(it);
1828 if (item == NULL) {
1829 if (PyErr_Occurred())
1830 goto Fail;
1831 break;
1832 }
Tim Peters1fc240e2001-10-26 05:06:50 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 /* Convert item to sequence, and verify length 2. */
1835 fast = PySequence_Fast(item, "");
1836 if (fast == NULL) {
1837 if (PyErr_ExceptionMatches(PyExc_TypeError))
1838 PyErr_Format(PyExc_TypeError,
1839 "cannot convert dictionary update "
1840 "sequence element #%zd to a sequence",
1841 i);
1842 goto Fail;
1843 }
1844 n = PySequence_Fast_GET_SIZE(fast);
1845 if (n != 2) {
1846 PyErr_Format(PyExc_ValueError,
1847 "dictionary update sequence element #%zd "
1848 "has length %zd; 2 is required",
1849 i, n);
1850 goto Fail;
1851 }
Tim Peters1fc240e2001-10-26 05:06:50 +00001852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 /* Update/merge with this (key, value) pair. */
1854 key = PySequence_Fast_GET_ITEM(fast, 0);
1855 value = PySequence_Fast_GET_ITEM(fast, 1);
1856 if (override || PyDict_GetItem(d, key) == NULL) {
1857 int status = PyDict_SetItem(d, key, value);
1858 if (status < 0)
1859 goto Fail;
1860 }
1861 Py_DECREF(fast);
1862 Py_DECREF(item);
1863 }
Tim Peters1fc240e2001-10-26 05:06:50 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 i = 0;
1866 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00001867Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 Py_XDECREF(item);
1869 Py_XDECREF(fast);
1870 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00001871Return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 Py_DECREF(it);
1873 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00001874}
1875
Tim Peters6d6c1a32001-08-02 04:15:00 +00001876int
1877PyDict_Update(PyObject *a, PyObject *b)
1878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 return PyDict_Merge(a, b, 1);
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001880}
1881
1882int
1883PyDict_Merge(PyObject *a, PyObject *b, int override)
1884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 register PyDictObject *mp, *other;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001886 register Py_ssize_t i, n;
1887 PyDictKeyEntry *entry;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 /* We accept for the argument either a concrete dictionary object,
1890 * or an abstract "mapping" object. For the former, we can do
1891 * things quite efficiently. For the latter, we only require that
1892 * PyMapping_Keys() and PyObject_GetItem() be supported.
1893 */
1894 if (a == NULL || !PyDict_Check(a) || b == NULL) {
1895 PyErr_BadInternalCall();
1896 return -1;
1897 }
1898 mp = (PyDictObject*)a;
1899 if (PyDict_Check(b)) {
1900 other = (PyDictObject*)b;
1901 if (other == mp || other->ma_used == 0)
1902 /* a.update(a) or a.update({}); nothing to do */
1903 return 0;
1904 if (mp->ma_used == 0)
1905 /* Since the target dict is empty, PyDict_GetItem()
1906 * always returns NULL. Setting override to 1
1907 * skips the unnecessary test.
1908 */
1909 override = 1;
1910 /* Do one big resize at the start, rather than
1911 * incrementally resizing as we insert new items. Expect
1912 * that there will be no (or few) overlapping keys.
1913 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001914 if (mp->ma_keys->dk_usable * 3 < other->ma_used * 2)
1915 if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 return -1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001917 for (i = 0, n = DK_SIZE(other->ma_keys); i < n; i++) {
1918 PyObject *value;
1919 entry = &other->ma_keys->dk_entries[i];
1920 if (other->ma_values)
1921 value = other->ma_values[i];
1922 else
1923 value = entry->me_value;
1924
1925 if (value != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 (override ||
1927 PyDict_GetItem(a, entry->me_key) == NULL)) {
1928 Py_INCREF(entry->me_key);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001929 Py_INCREF(value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 if (insertdict(mp, entry->me_key,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001931 entry->me_hash,
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001932 value) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 return -1;
1934 }
1935 }
1936 }
1937 else {
1938 /* Do it the generic, slower way */
1939 PyObject *keys = PyMapping_Keys(b);
1940 PyObject *iter;
1941 PyObject *key, *value;
1942 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 if (keys == NULL)
1945 /* Docstring says this is equivalent to E.keys() so
1946 * if E doesn't have a .keys() method we want
1947 * AttributeError to percolate up. Might as well
1948 * do the same for any other error.
1949 */
1950 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 iter = PyObject_GetIter(keys);
1953 Py_DECREF(keys);
1954 if (iter == NULL)
1955 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
1958 if (!override && PyDict_GetItem(a, key) != NULL) {
1959 Py_DECREF(key);
1960 continue;
1961 }
1962 value = PyObject_GetItem(b, key);
1963 if (value == NULL) {
1964 Py_DECREF(iter);
1965 Py_DECREF(key);
1966 return -1;
1967 }
1968 status = PyDict_SetItem(a, key, value);
1969 Py_DECREF(key);
1970 Py_DECREF(value);
1971 if (status < 0) {
1972 Py_DECREF(iter);
1973 return -1;
1974 }
1975 }
1976 Py_DECREF(iter);
1977 if (PyErr_Occurred())
1978 /* Iterator completed, via error */
1979 return -1;
1980 }
1981 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001982}
1983
1984static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001985dict_copy(register PyDictObject *mp)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001988}
1989
1990PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001991PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 PyObject *copy;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001994 PyDictObject *mp;
1995 Py_ssize_t i, n;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 if (o == NULL || !PyDict_Check(o)) {
1998 PyErr_BadInternalCall();
1999 return NULL;
2000 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002001 mp = (PyDictObject *)o;
2002 if (_PyDict_HasSplitTable(mp)) {
2003 PyDictObject *split_copy;
2004 PyObject **newvalues = new_values(DK_SIZE(mp->ma_keys));
2005 if (newvalues == NULL)
2006 return PyErr_NoMemory();
2007 split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
2008 if (split_copy == NULL) {
2009 free_values(newvalues);
2010 return NULL;
2011 }
2012 split_copy->ma_values = newvalues;
2013 split_copy->ma_keys = mp->ma_keys;
2014 split_copy->ma_used = mp->ma_used;
2015 DK_INCREF(mp->ma_keys);
2016 for (i = 0, n = DK_SIZE(mp->ma_keys); i < n; i++) {
2017 PyObject *value = mp->ma_values[i];
2018 Py_XINCREF(value);
2019 split_copy->ma_values[i] = value;
2020 }
2021 return (PyObject *)split_copy;
2022 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 copy = PyDict_New();
2024 if (copy == NULL)
2025 return NULL;
2026 if (PyDict_Merge(copy, o, 1) == 0)
2027 return copy;
2028 Py_DECREF(copy);
2029 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00002030}
2031
Martin v. Löwis18e16552006-02-15 17:27:45 +00002032Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00002033PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00002034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 if (mp == NULL || !PyDict_Check(mp)) {
2036 PyErr_BadInternalCall();
2037 return -1;
2038 }
2039 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00002040}
2041
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002042PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002043PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 if (mp == NULL || !PyDict_Check(mp)) {
2046 PyErr_BadInternalCall();
2047 return NULL;
2048 }
2049 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002050}
2051
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002052PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002053PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 if (mp == NULL || !PyDict_Check(mp)) {
2056 PyErr_BadInternalCall();
2057 return NULL;
2058 }
2059 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002060}
2061
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002062PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00002063PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00002064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 if (mp == NULL || !PyDict_Check(mp)) {
2066 PyErr_BadInternalCall();
2067 return NULL;
2068 }
2069 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00002070}
2071
Tim Peterse63415e2001-05-08 04:38:29 +00002072/* Return 1 if dicts equal, 0 if not, -1 if error.
2073 * Gets out as soon as any difference is detected.
2074 * Uses only Py_EQ comparison.
2075 */
2076static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002077dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00002078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00002080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 if (a->ma_used != b->ma_used)
2082 /* can't be equal if # of entries differ */
2083 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002085 for (i = 0; i < DK_SIZE(a->ma_keys); i++) {
2086 PyDictKeyEntry *ep = &a->ma_keys->dk_entries[i];
2087 PyObject *aval;
2088 if (a->ma_values)
2089 aval = a->ma_values[i];
2090 else
2091 aval = ep->me_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 if (aval != NULL) {
2093 int cmp;
2094 PyObject *bval;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002095 PyObject *key = ep->me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 /* temporarily bump aval's refcount to ensure it stays
2097 alive until we're done with it */
2098 Py_INCREF(aval);
2099 /* ditto for key */
2100 Py_INCREF(key);
2101 bval = PyDict_GetItemWithError((PyObject *)b, key);
2102 Py_DECREF(key);
2103 if (bval == NULL) {
2104 Py_DECREF(aval);
2105 if (PyErr_Occurred())
2106 return -1;
2107 return 0;
2108 }
2109 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
2110 Py_DECREF(aval);
2111 if (cmp <= 0) /* error or not equal */
2112 return cmp;
2113 }
2114 }
2115 return 1;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002116}
Tim Peterse63415e2001-05-08 04:38:29 +00002117
2118static PyObject *
2119dict_richcompare(PyObject *v, PyObject *w, int op)
2120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 int cmp;
2122 PyObject *res;
Tim Peterse63415e2001-05-08 04:38:29 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 if (!PyDict_Check(v) || !PyDict_Check(w)) {
2125 res = Py_NotImplemented;
2126 }
2127 else if (op == Py_EQ || op == Py_NE) {
2128 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
2129 if (cmp < 0)
2130 return NULL;
2131 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
2132 }
2133 else
2134 res = Py_NotImplemented;
2135 Py_INCREF(res);
2136 return res;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002137}
Tim Peterse63415e2001-05-08 04:38:29 +00002138
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002139static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002140dict_contains(register PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002141{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002142 Py_hash_t hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002143 PyDictKeyEntry *ep;
2144 PyObject **value_addr;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002147 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 hash = PyObject_Hash(key);
2149 if (hash == -1)
2150 return NULL;
2151 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002152 ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 if (ep == NULL)
2154 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002155 return PyBool_FromLong(*value_addr != NULL);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002156}
2157
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002158static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002159dict_get(register PyDictObject *mp, PyObject *args)
Barry Warsawc38c5da1997-10-06 17:49:20 +00002160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 PyObject *key;
2162 PyObject *failobj = Py_None;
2163 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002164 Py_hash_t hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002165 PyDictKeyEntry *ep;
2166 PyObject **value_addr;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
2169 return NULL;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002172 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 hash = PyObject_Hash(key);
2174 if (hash == -1)
2175 return NULL;
2176 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002177 ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 if (ep == NULL)
2179 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002180 val = *value_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 if (val == NULL)
2182 val = failobj;
2183 Py_INCREF(val);
2184 return val;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002185}
2186
Barry Warsawc38c5da1997-10-06 17:49:20 +00002187static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002188dict_setdefault(register PyDictObject *mp, PyObject *args)
Guido van Rossum164452c2000-08-08 16:12:54 +00002189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 PyObject *key;
2191 PyObject *failobj = Py_None;
2192 PyObject *val = NULL;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002193 Py_hash_t hash;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002194 PyDictKeyEntry *ep;
2195 PyObject **value_addr;
Guido van Rossum164452c2000-08-08 16:12:54 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &failobj))
2198 return NULL;
Guido van Rossum164452c2000-08-08 16:12:54 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002201 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 hash = PyObject_Hash(key);
2203 if (hash == -1)
2204 return NULL;
2205 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002206 ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 if (ep == NULL)
2208 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002209 val = *value_addr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 if (val == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002211 Py_INCREF(failobj);
2212 Py_INCREF(key);
2213 if (mp->ma_keys->dk_usable <= 0) {
2214 /* Need to resize. */
2215 if (insertion_resize(mp) < 0)
2216 return NULL;
2217 ep = find_empty_slot(mp, key, hash, &value_addr);
2218 }
2219 ep->me_key = key;
2220 ep->me_hash = hash;
2221 *value_addr = failobj;
2222 val = failobj;
2223 mp->ma_keys->dk_usable--;
2224 mp->ma_used++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002226 Py_INCREF(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 return val;
Guido van Rossum164452c2000-08-08 16:12:54 +00002228}
2229
2230
2231static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002232dict_clear(register PyDictObject *mp)
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 PyDict_Clear((PyObject *)mp);
2235 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002236}
2237
Guido van Rossumba6ab842000-12-12 22:02:18 +00002238static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002239dict_pop(PyDictObject *mp, PyObject *args)
Guido van Rossume027d982002-04-12 15:11:59 +00002240{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002241 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 PyObject *old_value, *old_key;
2243 PyObject *key, *deflt = NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002244 PyDictKeyEntry *ep;
2245 PyObject **value_addr;
Guido van Rossume027d982002-04-12 15:11:59 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
2248 return NULL;
2249 if (mp->ma_used == 0) {
2250 if (deflt) {
2251 Py_INCREF(deflt);
2252 return deflt;
2253 }
Raymond Hettingerdd421542010-10-30 08:10:29 +00002254 set_key_error(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 return NULL;
2256 }
2257 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002258 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 hash = PyObject_Hash(key);
2260 if (hash == -1)
2261 return NULL;
2262 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002263 ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 if (ep == NULL)
2265 return NULL;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002266 old_value = *value_addr;
2267 if (old_value == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 if (deflt) {
2269 Py_INCREF(deflt);
2270 return deflt;
2271 }
2272 set_key_error(key);
2273 return NULL;
2274 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002275 *value_addr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 mp->ma_used--;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002277 if (!_PyDict_HasSplitTable(mp)) {
2278 ENSURE_ALLOWS_DELETIONS(mp);
2279 old_key = ep->me_key;
2280 Py_INCREF(dummy);
2281 ep->me_key = dummy;
2282 Py_DECREF(old_key);
2283 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 return old_value;
Guido van Rossume027d982002-04-12 15:11:59 +00002285}
2286
2287static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002288dict_popitem(PyDictObject *mp)
Guido van Rossumba6ab842000-12-12 22:02:18 +00002289{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002290 Py_hash_t i = 0;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002291 PyDictKeyEntry *ep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 PyObject *res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002293
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 /* Allocate the result tuple before checking the size. Believe it
2296 * or not, this allocation could trigger a garbage collection which
2297 * could empty the dict, so if we checked the size first and that
2298 * happened, the result would be an infinite loop (searching for an
2299 * entry that no longer exists). Note that the usual popitem()
2300 * idiom is "while d: k, v = d.popitem()". so needing to throw the
2301 * tuple away if the dict *is* empty isn't a significant
2302 * inefficiency -- possible, but unlikely in practice.
2303 */
2304 res = PyTuple_New(2);
2305 if (res == NULL)
2306 return NULL;
2307 if (mp->ma_used == 0) {
2308 Py_DECREF(res);
2309 PyErr_SetString(PyExc_KeyError,
2310 "popitem(): dictionary is empty");
2311 return NULL;
2312 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002313 /* Convert split table to combined table */
2314 if (mp->ma_keys->dk_lookup == lookdict_split) {
2315 if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
2316 Py_DECREF(res);
2317 return NULL;
2318 }
2319 }
2320 ENSURE_ALLOWS_DELETIONS(mp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 /* Set ep to "the first" dict entry with a value. We abuse the hash
2322 * field of slot 0 to hold a search finger:
2323 * If slot 0 has a value, use slot 0.
2324 * Else slot 0 is being used to hold a search finger,
2325 * and we use its hash value as the first index to look.
2326 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002327 ep = &mp->ma_keys->dk_entries[0];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 if (ep->me_value == NULL) {
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002329 Py_ssize_t mask = DK_MASK(mp->ma_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 i = ep->me_hash;
2331 /* The hash field may be a real hash value, or it may be a
2332 * legit search finger, or it may be a once-legit search
2333 * finger that's out of bounds now because it wrapped around
2334 * or the table shrunk -- simply make sure it's in bounds now.
2335 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002336 if (i > mask || i < 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 i = 1; /* skip slot 0 */
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002338 while ((ep = &mp->ma_keys->dk_entries[i])->me_value == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 i++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002340 if (i > mask)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 i = 1;
2342 }
2343 }
2344 PyTuple_SET_ITEM(res, 0, ep->me_key);
2345 PyTuple_SET_ITEM(res, 1, ep->me_value);
2346 Py_INCREF(dummy);
2347 ep->me_key = dummy;
2348 ep->me_value = NULL;
2349 mp->ma_used--;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002350 assert(mp->ma_keys->dk_entries[0].me_value == NULL);
2351 mp->ma_keys->dk_entries[0].me_hash = i + 1; /* next place to start */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 return res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002353}
2354
Jeremy Hylton8caad492000-06-23 14:18:11 +00002355static int
2356dict_traverse(PyObject *op, visitproc visit, void *arg)
2357{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002358 Py_ssize_t i, n;
2359 PyDictObject *mp = (PyDictObject *)op;
2360 if (mp->ma_keys->dk_lookup == lookdict) {
2361 for (i = 0; i < DK_SIZE(mp->ma_keys); i++) {
2362 if (mp->ma_keys->dk_entries[i].me_value != NULL) {
2363 Py_VISIT(mp->ma_keys->dk_entries[i].me_value);
2364 Py_VISIT(mp->ma_keys->dk_entries[i].me_key);
2365 }
2366 }
2367 } else {
2368 if (mp->ma_values != NULL) {
2369 for (i = 0, n = DK_SIZE(mp->ma_keys); i < n; i++) {
2370 Py_VISIT(mp->ma_values[i]);
2371 }
2372 }
2373 else {
2374 for (i = 0, n = DK_SIZE(mp->ma_keys); i < n; i++) {
2375 Py_VISIT(mp->ma_keys->dk_entries[i].me_value);
2376 }
2377 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 }
2379 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002380}
2381
2382static int
2383dict_tp_clear(PyObject *op)
2384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 PyDict_Clear(op);
2386 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002387}
2388
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002389static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00002390
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002391static PyObject *
2392dict_sizeof(PyDictObject *mp)
2393{
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002394 Py_ssize_t size;
2395 double res, keys_size;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002396
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002397 size = DK_SIZE(mp->ma_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 res = sizeof(PyDictObject);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002399 if (mp->ma_values)
2400 res += size * sizeof(PyObject*);
2401 /* Count our share of the keys object -- with rounding errors. */
2402 keys_size = sizeof(PyDictKeysObject) + (size-1) * sizeof(PyDictKeyEntry);
2403 /* If refcnt > 1, then one count is (probably) held by a type */
2404 /* XXX This is somewhat approximate :) */
2405 if (mp->ma_keys->dk_refcnt < 3)
2406 res += keys_size;
2407 else
2408 res += keys_size / (mp->ma_keys->dk_refcnt - 1);
2409 return PyFloat_FromDouble(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002410}
2411
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002412PyDoc_STRVAR(contains__doc__,
2413"D.__contains__(k) -> True if D has a key k, else False");
2414
2415PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
2416
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002417PyDoc_STRVAR(sizeof__doc__,
2418"D.__sizeof__() -> size of D in memory, in bytes");
2419
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002420PyDoc_STRVAR(get__doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00002421"D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002422
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002423PyDoc_STRVAR(setdefault_doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00002424"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 +00002425
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002426PyDoc_STRVAR(pop__doc__,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002427"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00002428If key is not found, d is returned if given, otherwise KeyError is raised");
Guido van Rossume027d982002-04-12 15:11:59 +00002429
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002430PyDoc_STRVAR(popitem__doc__,
Tim Petersf7f88b12000-12-13 23:18:45 +00002431"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000024322-tuple; but raise KeyError if D is empty.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002433
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002434PyDoc_STRVAR(update__doc__,
Georg Brandlac0675c2011-12-18 19:30:55 +01002435"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n"
2436"If E present and has a .keys() method, does: for k in E: D[k] = E[k]\n\
2437If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002438In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00002439
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002440PyDoc_STRVAR(fromkeys__doc__,
2441"dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.\n\
2442v defaults to None.");
2443
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002444PyDoc_STRVAR(clear__doc__,
2445"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002446
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002447PyDoc_STRVAR(copy__doc__,
2448"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00002449
Guido van Rossumb90c8482007-02-10 01:11:45 +00002450/* Forward */
2451static PyObject *dictkeys_new(PyObject *);
2452static PyObject *dictitems_new(PyObject *);
2453static PyObject *dictvalues_new(PyObject *);
2454
Guido van Rossum45c85d12007-07-27 16:31:40 +00002455PyDoc_STRVAR(keys__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 "D.keys() -> a set-like object providing a view on D's keys");
Guido van Rossum45c85d12007-07-27 16:31:40 +00002457PyDoc_STRVAR(items__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 "D.items() -> a set-like object providing a view on D's items");
Guido van Rossum45c85d12007-07-27 16:31:40 +00002459PyDoc_STRVAR(values__doc__,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 "D.values() -> an object providing a view on D's values");
Guido van Rossumb90c8482007-02-10 01:11:45 +00002461
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002462static PyMethodDef mapp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 {"__contains__",(PyCFunction)dict_contains, METH_O | METH_COEXIST,
2464 contains__doc__},
2465 {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
2466 getitem__doc__},
2467 {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS,
2468 sizeof__doc__},
2469 {"get", (PyCFunction)dict_get, METH_VARARGS,
2470 get__doc__},
2471 {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS,
2472 setdefault_doc__},
2473 {"pop", (PyCFunction)dict_pop, METH_VARARGS,
2474 pop__doc__},
2475 {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
2476 popitem__doc__},
2477 {"keys", (PyCFunction)dictkeys_new, METH_NOARGS,
2478 keys__doc__},
2479 {"items", (PyCFunction)dictitems_new, METH_NOARGS,
2480 items__doc__},
2481 {"values", (PyCFunction)dictvalues_new, METH_NOARGS,
2482 values__doc__},
2483 {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
2484 update__doc__},
2485 {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS,
2486 fromkeys__doc__},
2487 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
2488 clear__doc__},
2489 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
2490 copy__doc__},
2491 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002492};
2493
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002494/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00002495int
2496PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002497{
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002498 Py_hash_t hash;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002500 PyDictKeyEntry *ep;
2501 PyObject **value_addr;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 if (!PyUnicode_CheckExact(key) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002504 (hash = ((PyASCIIObject *) key)->hash) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 hash = PyObject_Hash(key);
2506 if (hash == -1)
2507 return -1;
2508 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002509 ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
2510 return (ep == NULL) ? -1 : (*value_addr != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002511}
2512
Thomas Wouterscf297e42007-02-23 15:07:44 +00002513/* Internal version of PyDict_Contains used when the hash value is already known */
2514int
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002515_PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
Thomas Wouterscf297e42007-02-23 15:07:44 +00002516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 PyDictObject *mp = (PyDictObject *)op;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002518 PyDictKeyEntry *ep;
2519 PyObject **value_addr;
Thomas Wouterscf297e42007-02-23 15:07:44 +00002520
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002521 ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
2522 return (ep == NULL) ? -1 : (*value_addr != NULL);
Thomas Wouterscf297e42007-02-23 15:07:44 +00002523}
2524
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002525/* Hack to implement "key in dict" */
2526static PySequenceMethods dict_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 0, /* sq_length */
2528 0, /* sq_concat */
2529 0, /* sq_repeat */
2530 0, /* sq_item */
2531 0, /* sq_slice */
2532 0, /* sq_ass_item */
2533 0, /* sq_ass_slice */
2534 PyDict_Contains, /* sq_contains */
2535 0, /* sq_inplace_concat */
2536 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002537};
2538
Guido van Rossum09e563a2001-05-01 12:10:21 +00002539static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002540dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 PyObject *self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 assert(type != NULL && type->tp_alloc != NULL);
2545 self = type->tp_alloc(type, 0);
2546 if (self != NULL) {
2547 PyDictObject *d = (PyDictObject *)self;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002548 d->ma_keys = new_keys_object(PyDict_MINSIZE_COMBINED);
2549 /* XXX - Should we raise a no-memory error? */
2550 if (d->ma_keys == NULL) {
2551 DK_INCREF(Py_EMPTY_KEYS);
2552 d->ma_keys = Py_EMPTY_KEYS;
2553 d->ma_values = empty_values;
2554 }
2555 d->ma_used = 0;
Ezio Melotti13925002011-03-16 11:05:33 +02002556 /* The object has been implicitly tracked by tp_alloc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 if (type == &PyDict_Type)
2558 _PyObject_GC_UNTRACK(d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 }
2560 return self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002561}
2562
Tim Peters25786c02001-09-02 08:22:48 +00002563static int
2564dict_init(PyObject *self, PyObject *args, PyObject *kwds)
2565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00002567}
2568
Tim Peters6d6c1a32001-08-02 04:15:00 +00002569static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002570dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00002571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00002573}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002574
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002575PyDoc_STRVAR(dictionary_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00002576"dict() -> new empty dictionary\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00002577"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00002578" (key, value) pairs\n"
2579"dict(iterable) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00002580" d = {}\n"
Ezio Melotti7f807b72010-03-01 04:08:34 +00002581" for k, v in iterable:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00002582" d[k] = v\n"
2583"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
2584" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00002585
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002586PyTypeObject PyDict_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2588 "dict",
2589 sizeof(PyDictObject),
2590 0,
2591 (destructor)dict_dealloc, /* tp_dealloc */
2592 0, /* tp_print */
2593 0, /* tp_getattr */
2594 0, /* tp_setattr */
2595 0, /* tp_reserved */
2596 (reprfunc)dict_repr, /* tp_repr */
2597 0, /* tp_as_number */
2598 &dict_as_sequence, /* tp_as_sequence */
2599 &dict_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00002600 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 0, /* tp_call */
2602 0, /* tp_str */
2603 PyObject_GenericGetAttr, /* tp_getattro */
2604 0, /* tp_setattro */
2605 0, /* tp_as_buffer */
2606 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2607 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
2608 dictionary_doc, /* tp_doc */
2609 dict_traverse, /* tp_traverse */
2610 dict_tp_clear, /* tp_clear */
2611 dict_richcompare, /* tp_richcompare */
2612 0, /* tp_weaklistoffset */
2613 (getiterfunc)dict_iter, /* tp_iter */
2614 0, /* tp_iternext */
2615 mapp_methods, /* tp_methods */
2616 0, /* tp_members */
2617 0, /* tp_getset */
2618 0, /* tp_base */
2619 0, /* tp_dict */
2620 0, /* tp_descr_get */
2621 0, /* tp_descr_set */
2622 0, /* tp_dictoffset */
2623 dict_init, /* tp_init */
2624 PyType_GenericAlloc, /* tp_alloc */
2625 dict_new, /* tp_new */
2626 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002627};
2628
Victor Stinner3c1e4812012-03-26 22:10:51 +02002629PyObject *
2630_PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
2631{
2632 PyObject *kv;
2633 kv = _PyUnicode_FromId(key); /* borrowed */
2634 if (kv == NULL)
2635 return NULL;
2636 return PyDict_GetItem(dp, kv);
2637}
2638
Guido van Rossum3cca2451997-05-16 14:23:33 +00002639/* For backward compatibility with old dictionary interface */
2640
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002641PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00002642PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 PyObject *kv, *rv;
2645 kv = PyUnicode_FromString(key);
2646 if (kv == NULL)
2647 return NULL;
2648 rv = PyDict_GetItem(v, kv);
2649 Py_DECREF(kv);
2650 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002651}
2652
2653int
Victor Stinner3c1e4812012-03-26 22:10:51 +02002654_PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
2655{
2656 PyObject *kv;
2657 kv = _PyUnicode_FromId(key); /* borrowed */
2658 if (kv == NULL)
2659 return -1;
2660 return PyDict_SetItem(v, kv, item);
2661}
2662
2663int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00002664PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 PyObject *kv;
2667 int err;
2668 kv = PyUnicode_FromString(key);
2669 if (kv == NULL)
2670 return -1;
2671 PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
2672 err = PyDict_SetItem(v, kv, item);
2673 Py_DECREF(kv);
2674 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002675}
2676
2677int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00002678PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 PyObject *kv;
2681 int err;
2682 kv = PyUnicode_FromString(key);
2683 if (kv == NULL)
2684 return -1;
2685 err = PyDict_DelItem(v, kv);
2686 Py_DECREF(kv);
2687 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002688}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002689
Raymond Hettinger019a1482004-03-18 02:41:19 +00002690/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002691
2692typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 PyObject_HEAD
2694 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
2695 Py_ssize_t di_used;
2696 Py_ssize_t di_pos;
2697 PyObject* di_result; /* reusable result tuple for iteritems */
2698 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002699} dictiterobject;
2700
2701static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002702dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 dictiterobject *di;
2705 di = PyObject_GC_New(dictiterobject, itertype);
2706 if (di == NULL)
2707 return NULL;
2708 Py_INCREF(dict);
2709 di->di_dict = dict;
2710 di->di_used = dict->ma_used;
2711 di->di_pos = 0;
2712 di->len = dict->ma_used;
2713 if (itertype == &PyDictIterItem_Type) {
2714 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
2715 if (di->di_result == NULL) {
2716 Py_DECREF(di);
2717 return NULL;
2718 }
2719 }
2720 else
2721 di->di_result = NULL;
2722 _PyObject_GC_TRACK(di);
2723 return (PyObject *)di;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002724}
2725
2726static void
2727dictiter_dealloc(dictiterobject *di)
2728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 Py_XDECREF(di->di_dict);
2730 Py_XDECREF(di->di_result);
2731 PyObject_GC_Del(di);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002732}
2733
2734static int
2735dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
2736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 Py_VISIT(di->di_dict);
2738 Py_VISIT(di->di_result);
2739 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002740}
2741
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002742static PyObject *
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002743dictiter_len(dictiterobject *di)
2744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 Py_ssize_t len = 0;
2746 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
2747 len = di->len;
2748 return PyLong_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002749}
2750
Guido van Rossumb90c8482007-02-10 01:11:45 +00002751PyDoc_STRVAR(length_hint_doc,
2752 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002753
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002754static PyObject *
2755dictiter_reduce(dictiterobject *di);
2756
2757PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
2758
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002759static PyMethodDef dictiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS,
2761 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002762 {"__reduce__", (PyCFunction)dictiter_reduce, METH_NOARGS,
2763 reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002765};
2766
Raymond Hettinger019a1482004-03-18 02:41:19 +00002767static PyObject *dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00002768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 PyObject *key;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002770 register Py_ssize_t i, mask, offset;
2771 register PyDictKeysObject *k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002773 PyObject **value_ptr;
Guido van Rossum213c7a62001-04-23 14:08:49 +00002774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 if (d == NULL)
2776 return NULL;
2777 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00002778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 if (di->di_used != d->ma_used) {
2780 PyErr_SetString(PyExc_RuntimeError,
2781 "dictionary changed size during iteration");
2782 di->di_used = -1; /* Make this state sticky */
2783 return NULL;
2784 }
Guido van Rossum2147df72002-07-16 20:30:22 +00002785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 i = di->di_pos;
2787 if (i < 0)
2788 goto fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002789 k = d->ma_keys;
2790 if (d->ma_values) {
2791 value_ptr = &d->ma_values[i];
2792 offset = sizeof(PyObject *);
2793 }
2794 else {
2795 value_ptr = &k->dk_entries[i].me_value;
2796 offset = sizeof(PyDictKeyEntry);
2797 }
2798 mask = DK_SIZE(k)-1;
2799 while (i <= mask && *value_ptr == NULL) {
2800 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 i++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002802 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 di->di_pos = i+1;
2804 if (i > mask)
2805 goto fail;
2806 di->len--;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002807 key = k->dk_entries[i].me_key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 Py_INCREF(key);
2809 return key;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002810
2811fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 Py_DECREF(d);
2813 di->di_dict = NULL;
2814 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002815}
2816
Raymond Hettinger019a1482004-03-18 02:41:19 +00002817PyTypeObject PyDictIterKey_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2819 "dict_keyiterator", /* tp_name */
2820 sizeof(dictiterobject), /* tp_basicsize */
2821 0, /* tp_itemsize */
2822 /* methods */
2823 (destructor)dictiter_dealloc, /* tp_dealloc */
2824 0, /* tp_print */
2825 0, /* tp_getattr */
2826 0, /* tp_setattr */
2827 0, /* tp_reserved */
2828 0, /* tp_repr */
2829 0, /* tp_as_number */
2830 0, /* tp_as_sequence */
2831 0, /* tp_as_mapping */
2832 0, /* tp_hash */
2833 0, /* tp_call */
2834 0, /* tp_str */
2835 PyObject_GenericGetAttr, /* tp_getattro */
2836 0, /* tp_setattro */
2837 0, /* tp_as_buffer */
2838 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2839 0, /* tp_doc */
2840 (traverseproc)dictiter_traverse, /* tp_traverse */
2841 0, /* tp_clear */
2842 0, /* tp_richcompare */
2843 0, /* tp_weaklistoffset */
2844 PyObject_SelfIter, /* tp_iter */
2845 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
2846 dictiter_methods, /* tp_methods */
2847 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00002848};
2849
2850static PyObject *dictiter_iternextvalue(dictiterobject *di)
2851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 PyObject *value;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002853 register Py_ssize_t i, mask, offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002855 PyObject **value_ptr;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 if (d == NULL)
2858 return NULL;
2859 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00002860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 if (di->di_used != d->ma_used) {
2862 PyErr_SetString(PyExc_RuntimeError,
2863 "dictionary changed size during iteration");
2864 di->di_used = -1; /* Make this state sticky */
2865 return NULL;
2866 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00002867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 i = di->di_pos;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002869 mask = DK_SIZE(d->ma_keys)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 if (i < 0 || i > mask)
2871 goto fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002872 if (d->ma_values) {
2873 value_ptr = &d->ma_values[i];
2874 offset = sizeof(PyObject *);
2875 }
2876 else {
2877 value_ptr = &d->ma_keys->dk_entries[i].me_value;
2878 offset = sizeof(PyDictKeyEntry);
2879 }
2880 while (i <= mask && *value_ptr == NULL) {
2881 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 i++;
2883 if (i > mask)
2884 goto fail;
2885 }
2886 di->di_pos = i+1;
2887 di->len--;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002888 value = *value_ptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 Py_INCREF(value);
2890 return value;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002891
2892fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 Py_DECREF(d);
2894 di->di_dict = NULL;
2895 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002896}
2897
2898PyTypeObject PyDictIterValue_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2900 "dict_valueiterator", /* tp_name */
2901 sizeof(dictiterobject), /* tp_basicsize */
2902 0, /* tp_itemsize */
2903 /* methods */
2904 (destructor)dictiter_dealloc, /* tp_dealloc */
2905 0, /* tp_print */
2906 0, /* tp_getattr */
2907 0, /* tp_setattr */
2908 0, /* tp_reserved */
2909 0, /* tp_repr */
2910 0, /* tp_as_number */
2911 0, /* tp_as_sequence */
2912 0, /* tp_as_mapping */
2913 0, /* tp_hash */
2914 0, /* tp_call */
2915 0, /* tp_str */
2916 PyObject_GenericGetAttr, /* tp_getattro */
2917 0, /* tp_setattro */
2918 0, /* tp_as_buffer */
2919 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2920 0, /* tp_doc */
2921 (traverseproc)dictiter_traverse, /* tp_traverse */
2922 0, /* tp_clear */
2923 0, /* tp_richcompare */
2924 0, /* tp_weaklistoffset */
2925 PyObject_SelfIter, /* tp_iter */
2926 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
2927 dictiter_methods, /* tp_methods */
2928 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00002929};
2930
2931static PyObject *dictiter_iternextitem(dictiterobject *di)
2932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 PyObject *key, *value, *result = di->di_result;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002934 register Py_ssize_t i, mask, offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 PyDictObject *d = di->di_dict;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002936 PyObject **value_ptr;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 if (d == NULL)
2939 return NULL;
2940 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00002941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 if (di->di_used != d->ma_used) {
2943 PyErr_SetString(PyExc_RuntimeError,
2944 "dictionary changed size during iteration");
2945 di->di_used = -1; /* Make this state sticky */
2946 return NULL;
2947 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00002948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 i = di->di_pos;
2950 if (i < 0)
2951 goto fail;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002952 mask = DK_SIZE(d->ma_keys)-1;
2953 if (d->ma_values) {
2954 value_ptr = &d->ma_values[i];
2955 offset = sizeof(PyObject *);
2956 }
2957 else {
2958 value_ptr = &d->ma_keys->dk_entries[i].me_value;
2959 offset = sizeof(PyDictKeyEntry);
2960 }
2961 while (i <= mask && *value_ptr == NULL) {
2962 value_ptr = (PyObject **)(((char *)value_ptr) + offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 i++;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002964 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 di->di_pos = i+1;
2966 if (i > mask)
2967 goto fail;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 if (result->ob_refcnt == 1) {
2970 Py_INCREF(result);
2971 Py_DECREF(PyTuple_GET_ITEM(result, 0));
2972 Py_DECREF(PyTuple_GET_ITEM(result, 1));
2973 } else {
2974 result = PyTuple_New(2);
2975 if (result == NULL)
2976 return NULL;
2977 }
2978 di->len--;
Benjamin Peterson7d95e402012-04-23 11:24:50 -04002979 key = d->ma_keys->dk_entries[i].me_key;
2980 value = *value_ptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 Py_INCREF(key);
2982 Py_INCREF(value);
2983 PyTuple_SET_ITEM(result, 0, key);
2984 PyTuple_SET_ITEM(result, 1, value);
2985 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002986
2987fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 Py_DECREF(d);
2989 di->di_dict = NULL;
2990 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002991}
2992
2993PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2995 "dict_itemiterator", /* tp_name */
2996 sizeof(dictiterobject), /* tp_basicsize */
2997 0, /* tp_itemsize */
2998 /* methods */
2999 (destructor)dictiter_dealloc, /* tp_dealloc */
3000 0, /* tp_print */
3001 0, /* tp_getattr */
3002 0, /* tp_setattr */
3003 0, /* tp_reserved */
3004 0, /* tp_repr */
3005 0, /* tp_as_number */
3006 0, /* tp_as_sequence */
3007 0, /* tp_as_mapping */
3008 0, /* tp_hash */
3009 0, /* tp_call */
3010 0, /* tp_str */
3011 PyObject_GenericGetAttr, /* tp_getattro */
3012 0, /* tp_setattro */
3013 0, /* tp_as_buffer */
3014 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3015 0, /* tp_doc */
3016 (traverseproc)dictiter_traverse, /* tp_traverse */
3017 0, /* tp_clear */
3018 0, /* tp_richcompare */
3019 0, /* tp_weaklistoffset */
3020 PyObject_SelfIter, /* tp_iter */
3021 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
3022 dictiter_methods, /* tp_methods */
3023 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00003024};
Guido van Rossumb90c8482007-02-10 01:11:45 +00003025
3026
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003027static PyObject *
3028dictiter_reduce(dictiterobject *di)
3029{
3030 PyObject *list;
3031 dictiterobject tmp;
3032
3033 list = PyList_New(0);
3034 if (!list)
3035 return NULL;
3036
3037 /* copy the itertor state */
3038 tmp = *di;
3039 Py_XINCREF(tmp.di_dict);
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003040
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003041 /* iterate the temporary into a list */
3042 for(;;) {
3043 PyObject *element = 0;
3044 if (Py_TYPE(di) == &PyDictIterItem_Type)
3045 element = dictiter_iternextitem(&tmp);
3046 else if (Py_TYPE(di) == &PyDictIterKey_Type)
3047 element = dictiter_iternextkey(&tmp);
3048 else if (Py_TYPE(di) == &PyDictIterValue_Type)
3049 element = dictiter_iternextvalue(&tmp);
3050 else
3051 assert(0);
3052 if (element) {
3053 if (PyList_Append(list, element)) {
3054 Py_DECREF(element);
3055 Py_DECREF(list);
3056 Py_XDECREF(tmp.di_dict);
3057 return NULL;
3058 }
3059 Py_DECREF(element);
3060 } else
3061 break;
3062 }
3063 Py_XDECREF(tmp.di_dict);
3064 /* check for error */
3065 if (tmp.di_dict != NULL) {
3066 /* we have an error */
3067 Py_DECREF(list);
3068 return NULL;
3069 }
Antoine Pitroua7013882012-04-05 00:04:20 +02003070 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003071}
3072
Guido van Rossum3ac67412007-02-10 18:55:06 +00003073/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003074/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00003075/***********************************************/
3076
Guido van Rossumb90c8482007-02-10 01:11:45 +00003077/* The instance lay-out is the same for all three; but the type differs. */
3078
3079typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 PyObject_HEAD
3081 PyDictObject *dv_dict;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003082} dictviewobject;
3083
3084
3085static void
Guido van Rossum3ac67412007-02-10 18:55:06 +00003086dictview_dealloc(dictviewobject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 Py_XDECREF(dv->dv_dict);
3089 PyObject_GC_Del(dv);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00003090}
3091
3092static int
3093dictview_traverse(dictviewobject *dv, visitproc visit, void *arg)
3094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 Py_VISIT(dv->dv_dict);
3096 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003097}
3098
Guido van Rossum83825ac2007-02-10 04:54:19 +00003099static Py_ssize_t
Guido van Rossum3ac67412007-02-10 18:55:06 +00003100dictview_len(dictviewobject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 Py_ssize_t len = 0;
3103 if (dv->dv_dict != NULL)
3104 len = dv->dv_dict->ma_used;
3105 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003106}
3107
3108static PyObject *
3109dictview_new(PyObject *dict, PyTypeObject *type)
3110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 dictviewobject *dv;
3112 if (dict == NULL) {
3113 PyErr_BadInternalCall();
3114 return NULL;
3115 }
3116 if (!PyDict_Check(dict)) {
3117 /* XXX Get rid of this restriction later */
3118 PyErr_Format(PyExc_TypeError,
3119 "%s() requires a dict argument, not '%s'",
3120 type->tp_name, dict->ob_type->tp_name);
3121 return NULL;
3122 }
3123 dv = PyObject_GC_New(dictviewobject, type);
3124 if (dv == NULL)
3125 return NULL;
3126 Py_INCREF(dict);
3127 dv->dv_dict = (PyDictObject *)dict;
3128 _PyObject_GC_TRACK(dv);
3129 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00003130}
3131
Neal Norwitze36f2ba2007-02-26 23:12:28 +00003132/* TODO(guido): The views objects are not complete:
3133
3134 * support more set operations
3135 * support arbitrary mappings?
3136 - either these should be static or exported in dictobject.h
3137 - if public then they should probably be in builtins
3138*/
3139
Guido van Rossumaac530c2007-08-24 22:33:45 +00003140/* Return 1 if self is a subset of other, iterating over self;
3141 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00003142static int
3143all_contained_in(PyObject *self, PyObject *other)
3144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 PyObject *iter = PyObject_GetIter(self);
3146 int ok = 1;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 if (iter == NULL)
3149 return -1;
3150 for (;;) {
3151 PyObject *next = PyIter_Next(iter);
3152 if (next == NULL) {
3153 if (PyErr_Occurred())
3154 ok = -1;
3155 break;
3156 }
3157 ok = PySequence_Contains(other, next);
3158 Py_DECREF(next);
3159 if (ok <= 0)
3160 break;
3161 }
3162 Py_DECREF(iter);
3163 return ok;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003164}
3165
3166static PyObject *
3167dictview_richcompare(PyObject *self, PyObject *other, int op)
3168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 Py_ssize_t len_self, len_other;
3170 int ok;
3171 PyObject *result;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 assert(self != NULL);
3174 assert(PyDictViewSet_Check(self));
3175 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00003176
Brian Curtindfc80e32011-08-10 20:28:54 -05003177 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
3178 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 len_self = PyObject_Size(self);
3181 if (len_self < 0)
3182 return NULL;
3183 len_other = PyObject_Size(other);
3184 if (len_other < 0)
3185 return NULL;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 ok = 0;
3188 switch(op) {
Guido van Rossumaac530c2007-08-24 22:33:45 +00003189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 case Py_NE:
3191 case Py_EQ:
3192 if (len_self == len_other)
3193 ok = all_contained_in(self, other);
3194 if (op == Py_NE && ok >= 0)
3195 ok = !ok;
3196 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 case Py_LT:
3199 if (len_self < len_other)
3200 ok = all_contained_in(self, other);
3201 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 case Py_LE:
3204 if (len_self <= len_other)
3205 ok = all_contained_in(self, other);
3206 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 case Py_GT:
3209 if (len_self > len_other)
3210 ok = all_contained_in(other, self);
3211 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 case Py_GE:
3214 if (len_self >= len_other)
3215 ok = all_contained_in(other, self);
3216 break;
Guido van Rossumaac530c2007-08-24 22:33:45 +00003217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 }
3219 if (ok < 0)
3220 return NULL;
3221 result = ok ? Py_True : Py_False;
3222 Py_INCREF(result);
3223 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00003224}
3225
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003226static PyObject *
3227dictview_repr(dictviewobject *dv)
3228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 PyObject *seq;
3230 PyObject *result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 seq = PySequence_List((PyObject *)dv);
3233 if (seq == NULL)
3234 return NULL;
3235
3236 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
3237 Py_DECREF(seq);
3238 return result;
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00003239}
3240
Guido van Rossum3ac67412007-02-10 18:55:06 +00003241/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003242
3243static PyObject *
Guido van Rossum3ac67412007-02-10 18:55:06 +00003244dictkeys_iter(dictviewobject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 if (dv->dv_dict == NULL) {
3247 Py_RETURN_NONE;
3248 }
3249 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003250}
3251
3252static int
3253dictkeys_contains(dictviewobject *dv, PyObject *obj)
3254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 if (dv->dv_dict == NULL)
3256 return 0;
3257 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003258}
3259
Guido van Rossum83825ac2007-02-10 04:54:19 +00003260static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 (lenfunc)dictview_len, /* sq_length */
3262 0, /* sq_concat */
3263 0, /* sq_repeat */
3264 0, /* sq_item */
3265 0, /* sq_slice */
3266 0, /* sq_ass_item */
3267 0, /* sq_ass_slice */
3268 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003269};
3270
Guido van Rossum523259b2007-08-24 23:41:22 +00003271static PyObject*
3272dictviews_sub(PyObject* self, PyObject *other)
3273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 PyObject *result = PySet_New(self);
3275 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003276 _Py_IDENTIFIER(difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 if (result == NULL)
3279 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003280
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003281 tmp = _PyObject_CallMethodId(result, &PyId_difference_update, "O", other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 if (tmp == NULL) {
3283 Py_DECREF(result);
3284 return NULL;
3285 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 Py_DECREF(tmp);
3288 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003289}
3290
3291static PyObject*
3292dictviews_and(PyObject* self, PyObject *other)
3293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 PyObject *result = PySet_New(self);
3295 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003296 _Py_IDENTIFIER(intersection_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 if (result == NULL)
3299 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003300
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003301 tmp = _PyObject_CallMethodId(result, &PyId_intersection_update, "O", other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 if (tmp == NULL) {
3303 Py_DECREF(result);
3304 return NULL;
3305 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 Py_DECREF(tmp);
3308 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003309}
3310
3311static PyObject*
3312dictviews_or(PyObject* self, PyObject *other)
3313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 PyObject *result = PySet_New(self);
3315 PyObject *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02003316 _Py_IDENTIFIER(update);
Victor Stinnerd1a9cc22011-10-13 22:51:17 +02003317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 if (result == NULL)
3319 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003320
Victor Stinnerd1a9cc22011-10-13 22:51:17 +02003321 tmp = _PyObject_CallMethodId(result, &PyId_update, "O", other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 if (tmp == NULL) {
3323 Py_DECREF(result);
3324 return NULL;
3325 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003327 Py_DECREF(tmp);
3328 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003329}
3330
3331static PyObject*
3332dictviews_xor(PyObject* self, PyObject *other)
3333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003334 PyObject *result = PySet_New(self);
3335 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003336 _Py_IDENTIFIER(symmetric_difference_update);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 if (result == NULL)
3339 return NULL;
Guido van Rossum523259b2007-08-24 23:41:22 +00003340
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003341 tmp = _PyObject_CallMethodId(result, &PyId_symmetric_difference_update, "O",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 other);
3343 if (tmp == NULL) {
3344 Py_DECREF(result);
3345 return NULL;
3346 }
Guido van Rossum523259b2007-08-24 23:41:22 +00003347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 Py_DECREF(tmp);
3349 return result;
Guido van Rossum523259b2007-08-24 23:41:22 +00003350}
3351
3352static PyNumberMethods dictviews_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 0, /*nb_add*/
3354 (binaryfunc)dictviews_sub, /*nb_subtract*/
3355 0, /*nb_multiply*/
3356 0, /*nb_remainder*/
3357 0, /*nb_divmod*/
3358 0, /*nb_power*/
3359 0, /*nb_negative*/
3360 0, /*nb_positive*/
3361 0, /*nb_absolute*/
3362 0, /*nb_bool*/
3363 0, /*nb_invert*/
3364 0, /*nb_lshift*/
3365 0, /*nb_rshift*/
3366 (binaryfunc)dictviews_and, /*nb_and*/
3367 (binaryfunc)dictviews_xor, /*nb_xor*/
3368 (binaryfunc)dictviews_or, /*nb_or*/
Guido van Rossum523259b2007-08-24 23:41:22 +00003369};
3370
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003371static PyObject*
3372dictviews_isdisjoint(PyObject *self, PyObject *other)
3373{
3374 PyObject *it;
3375 PyObject *item = NULL;
3376
3377 if (self == other) {
3378 if (dictview_len((dictviewobject *)self) == 0)
3379 Py_RETURN_TRUE;
3380 else
3381 Py_RETURN_FALSE;
3382 }
3383
3384 /* Iterate over the shorter object (only if other is a set,
3385 * because PySequence_Contains may be expensive otherwise): */
3386 if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
3387 Py_ssize_t len_self = dictview_len((dictviewobject *)self);
3388 Py_ssize_t len_other = PyObject_Size(other);
3389 if (len_other == -1)
3390 return NULL;
3391
3392 if ((len_other > len_self)) {
3393 PyObject *tmp = other;
3394 other = self;
3395 self = tmp;
3396 }
3397 }
3398
3399 it = PyObject_GetIter(other);
3400 if (it == NULL)
3401 return NULL;
3402
3403 while ((item = PyIter_Next(it)) != NULL) {
3404 int contains = PySequence_Contains(self, item);
3405 Py_DECREF(item);
3406 if (contains == -1) {
3407 Py_DECREF(it);
3408 return NULL;
3409 }
3410
3411 if (contains) {
3412 Py_DECREF(it);
3413 Py_RETURN_FALSE;
3414 }
3415 }
3416 Py_DECREF(it);
3417 if (PyErr_Occurred())
3418 return NULL; /* PyIter_Next raised an exception. */
3419 Py_RETURN_TRUE;
3420}
3421
3422PyDoc_STRVAR(isdisjoint_doc,
3423"Return True if the view and the given iterable have a null intersection.");
3424
Guido van Rossumb90c8482007-02-10 01:11:45 +00003425static PyMethodDef dictkeys_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003426 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
3427 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00003429};
3430
3431PyTypeObject PyDictKeys_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3433 "dict_keys", /* tp_name */
3434 sizeof(dictviewobject), /* tp_basicsize */
3435 0, /* tp_itemsize */
3436 /* methods */
3437 (destructor)dictview_dealloc, /* tp_dealloc */
3438 0, /* tp_print */
3439 0, /* tp_getattr */
3440 0, /* tp_setattr */
3441 0, /* tp_reserved */
3442 (reprfunc)dictview_repr, /* tp_repr */
3443 &dictviews_as_number, /* tp_as_number */
3444 &dictkeys_as_sequence, /* tp_as_sequence */
3445 0, /* tp_as_mapping */
3446 0, /* tp_hash */
3447 0, /* tp_call */
3448 0, /* tp_str */
3449 PyObject_GenericGetAttr, /* tp_getattro */
3450 0, /* tp_setattro */
3451 0, /* tp_as_buffer */
3452 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3453 0, /* tp_doc */
3454 (traverseproc)dictview_traverse, /* tp_traverse */
3455 0, /* tp_clear */
3456 dictview_richcompare, /* tp_richcompare */
3457 0, /* tp_weaklistoffset */
3458 (getiterfunc)dictkeys_iter, /* tp_iter */
3459 0, /* tp_iternext */
3460 dictkeys_methods, /* tp_methods */
3461 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00003462};
3463
3464static PyObject *
3465dictkeys_new(PyObject *dict)
3466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 return dictview_new(dict, &PyDictKeys_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003468}
3469
Guido van Rossum3ac67412007-02-10 18:55:06 +00003470/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003471
3472static PyObject *
Guido van Rossum3ac67412007-02-10 18:55:06 +00003473dictitems_iter(dictviewobject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003475 if (dv->dv_dict == NULL) {
3476 Py_RETURN_NONE;
3477 }
3478 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00003479}
3480
3481static int
3482dictitems_contains(dictviewobject *dv, PyObject *obj)
3483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003484 PyObject *key, *value, *found;
3485 if (dv->dv_dict == NULL)
3486 return 0;
3487 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
3488 return 0;
3489 key = PyTuple_GET_ITEM(obj, 0);
3490 value = PyTuple_GET_ITEM(obj, 1);
3491 found = PyDict_GetItem((PyObject *)dv->dv_dict, key);
3492 if (found == NULL) {
3493 if (PyErr_Occurred())
3494 return -1;
3495 return 0;
3496 }
3497 return PyObject_RichCompareBool(value, found, Py_EQ);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003498}
3499
Guido van Rossum83825ac2007-02-10 04:54:19 +00003500static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 (lenfunc)dictview_len, /* sq_length */
3502 0, /* sq_concat */
3503 0, /* sq_repeat */
3504 0, /* sq_item */
3505 0, /* sq_slice */
3506 0, /* sq_ass_item */
3507 0, /* sq_ass_slice */
3508 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003509};
3510
Guido van Rossumb90c8482007-02-10 01:11:45 +00003511static PyMethodDef dictitems_methods[] = {
Daniel Stutzbach045b3ba2010-09-02 15:06:06 +00003512 {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
3513 isdisjoint_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00003515};
3516
3517PyTypeObject PyDictItems_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3519 "dict_items", /* tp_name */
3520 sizeof(dictviewobject), /* tp_basicsize */
3521 0, /* tp_itemsize */
3522 /* methods */
3523 (destructor)dictview_dealloc, /* tp_dealloc */
3524 0, /* tp_print */
3525 0, /* tp_getattr */
3526 0, /* tp_setattr */
3527 0, /* tp_reserved */
3528 (reprfunc)dictview_repr, /* tp_repr */
3529 &dictviews_as_number, /* tp_as_number */
3530 &dictitems_as_sequence, /* tp_as_sequence */
3531 0, /* tp_as_mapping */
3532 0, /* tp_hash */
3533 0, /* tp_call */
3534 0, /* tp_str */
3535 PyObject_GenericGetAttr, /* tp_getattro */
3536 0, /* tp_setattro */
3537 0, /* tp_as_buffer */
3538 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3539 0, /* tp_doc */
3540 (traverseproc)dictview_traverse, /* tp_traverse */
3541 0, /* tp_clear */
3542 dictview_richcompare, /* tp_richcompare */
3543 0, /* tp_weaklistoffset */
3544 (getiterfunc)dictitems_iter, /* tp_iter */
3545 0, /* tp_iternext */
3546 dictitems_methods, /* tp_methods */
3547 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00003548};
3549
3550static PyObject *
3551dictitems_new(PyObject *dict)
3552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 return dictview_new(dict, &PyDictItems_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003554}
3555
Guido van Rossum3ac67412007-02-10 18:55:06 +00003556/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00003557
3558static PyObject *
Guido van Rossum3ac67412007-02-10 18:55:06 +00003559dictvalues_iter(dictviewobject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00003560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 if (dv->dv_dict == NULL) {
3562 Py_RETURN_NONE;
3563 }
3564 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003565}
3566
Guido van Rossum83825ac2007-02-10 04:54:19 +00003567static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 (lenfunc)dictview_len, /* sq_length */
3569 0, /* sq_concat */
3570 0, /* sq_repeat */
3571 0, /* sq_item */
3572 0, /* sq_slice */
3573 0, /* sq_ass_item */
3574 0, /* sq_ass_slice */
3575 (objobjproc)0, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00003576};
3577
Guido van Rossumb90c8482007-02-10 01:11:45 +00003578static PyMethodDef dictvalues_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 {NULL, NULL} /* sentinel */
Guido van Rossumb90c8482007-02-10 01:11:45 +00003580};
3581
3582PyTypeObject PyDictValues_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3584 "dict_values", /* tp_name */
3585 sizeof(dictviewobject), /* tp_basicsize */
3586 0, /* tp_itemsize */
3587 /* methods */
3588 (destructor)dictview_dealloc, /* tp_dealloc */
3589 0, /* tp_print */
3590 0, /* tp_getattr */
3591 0, /* tp_setattr */
3592 0, /* tp_reserved */
3593 (reprfunc)dictview_repr, /* tp_repr */
3594 0, /* tp_as_number */
3595 &dictvalues_as_sequence, /* tp_as_sequence */
3596 0, /* tp_as_mapping */
3597 0, /* tp_hash */
3598 0, /* tp_call */
3599 0, /* tp_str */
3600 PyObject_GenericGetAttr, /* tp_getattro */
3601 0, /* tp_setattro */
3602 0, /* tp_as_buffer */
3603 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3604 0, /* tp_doc */
3605 (traverseproc)dictview_traverse, /* tp_traverse */
3606 0, /* tp_clear */
3607 0, /* tp_richcompare */
3608 0, /* tp_weaklistoffset */
3609 (getiterfunc)dictvalues_iter, /* tp_iter */
3610 0, /* tp_iternext */
3611 dictvalues_methods, /* tp_methods */
3612 0,
Guido van Rossumb90c8482007-02-10 01:11:45 +00003613};
3614
3615static PyObject *
3616dictvalues_new(PyObject *dict)
3617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 return dictview_new(dict, &PyDictValues_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00003619}
Benjamin Peterson7d95e402012-04-23 11:24:50 -04003620
3621/* Returns NULL if cannot allocate a new PyDictKeysObject,
3622 but does not set an error */
3623PyDictKeysObject *
3624_PyDict_NewKeysForClass(void)
3625{
3626 PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE_SPLIT);
3627 if (keys == NULL)
3628 PyErr_Clear();
3629 else
3630 keys->dk_lookup = lookdict_split;
3631 return keys;
3632}
3633
3634#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
3635
3636PyObject *
3637PyObject_GenericGetDict(PyObject *obj, void *context)
3638{
3639 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
3640 if (dictptr == NULL) {
3641 PyErr_SetString(PyExc_AttributeError,
3642 "This object has no __dict__");
3643 return NULL;
3644 }
3645 dict = *dictptr;
3646 if (dict == NULL) {
3647 PyTypeObject *tp = Py_TYPE(obj);
3648 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
3649 DK_INCREF(CACHED_KEYS(tp));
3650 *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
3651 }
3652 else {
3653 *dictptr = dict = PyDict_New();
3654 }
3655 }
3656 Py_XINCREF(dict);
3657 return dict;
3658}
3659
3660int
3661_PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
3662 PyObject *key, PyObject *value)
3663{
3664 PyObject *dict;
3665 int res;
3666 PyDictKeysObject *cached;
3667
3668 assert(dictptr != NULL);
3669 if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
3670 assert(dictptr != NULL);
3671 dict = *dictptr;
3672 if (dict == NULL) {
3673 DK_INCREF(cached);
3674 dict = new_dict_with_shared_keys(cached);
3675 if (dict == NULL)
3676 return -1;
3677 *dictptr = dict;
3678 }
3679 if (value == NULL) {
3680 res = PyDict_DelItem(dict, key);
3681 if (cached != ((PyDictObject *)dict)->ma_keys) {
3682 CACHED_KEYS(tp) = NULL;
3683 DK_DECREF(cached);
3684 }
3685 } else {
3686 res = PyDict_SetItem(dict, key, value);
3687 if (cached != ((PyDictObject *)dict)->ma_keys) {
3688 /* Either update tp->ht_cached_keys or delete it */
3689 if (cached->dk_refcnt == 1) {
3690 CACHED_KEYS(tp) = make_keys_shared(dict);
3691 if (CACHED_KEYS(tp) == NULL)
3692 return -1;
3693 } else {
3694 CACHED_KEYS(tp) = NULL;
3695 }
3696 DK_DECREF(cached);
3697 }
3698 }
3699 } else {
3700 dict = *dictptr;
3701 if (dict == NULL) {
3702 dict = PyDict_New();
3703 if (dict == NULL)
3704 return -1;
3705 *dictptr = dict;
3706 }
3707 if (value == NULL) {
3708 res = PyDict_DelItem(dict, key);
3709 } else {
3710 res = PyDict_SetItem(dict, key, value);
3711 }
3712 }
3713 return res;
3714}
3715
3716void
3717_PyDictKeys_DecRef(PyDictKeysObject *keys)
3718{
3719 DK_DECREF(keys);
3720}
3721
3722
3723/* ARGSUSED */
3724static PyObject *
3725dummy_repr(PyObject *op)
3726{
3727 return PyUnicode_FromString("<dummy key>");
3728}
3729
3730/* ARGUSED */
3731static void
3732dummy_dealloc(PyObject* ignore)
3733{
3734 /* This should never get called, but we also don't want to SEGV if
3735 * we accidentally decref dummy-key out of existence.
3736 */
3737 Py_FatalError("deallocating <dummy key>");
3738}
3739
3740static PyTypeObject PyDictDummy_Type = {
3741 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3742 "<dummy key> type",
3743 0,
3744 0,
3745 dummy_dealloc, /*tp_dealloc*/ /*never called*/
3746 0, /*tp_print*/
3747 0, /*tp_getattr*/
3748 0, /*tp_setattr*/
3749 0, /*tp_reserved*/
3750 dummy_repr, /*tp_repr*/
3751 0, /*tp_as_number*/
3752 0, /*tp_as_sequence*/
3753 0, /*tp_as_mapping*/
3754 0, /*tp_hash */
3755 0, /*tp_call */
3756 0, /*tp_str */
3757 0, /*tp_getattro */
3758 0, /*tp_setattro */
3759 0, /*tp_as_buffer */
3760 Py_TPFLAGS_DEFAULT, /*tp_flags */
3761};
3762
3763static PyObject _dummy_struct = {
3764 _PyObject_EXTRA_INIT
3765 2, &PyDictDummy_Type
3766};
3767