blob: 9506067c7db466d160d24b6c1355070804adf9d1 [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
Guido van Rossumc0b618a1997-05-02 03:12:38 +000010#include "Python.h"
Guido van Rossum4b1302b1993-03-27 18:11:32 +000011
Guido van Rossum16e93a81997-01-28 00:00:11 +000012
Georg Brandlb9f4ad32006-10-29 18:31:42 +000013/* Set a key error with the specified argument, wrapping it in a
14 * tuple automatically so that tuple keys are not unpacked as the
15 * exception arguments. */
16static void
17set_key_error(PyObject *arg)
18{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000019 PyObject *tup;
20 tup = PyTuple_Pack(1, arg);
21 if (!tup)
22 return; /* caller will expect error to be set anyway */
23 PyErr_SetObject(PyExc_KeyError, tup);
24 Py_DECREF(tup);
Georg Brandlb9f4ad32006-10-29 18:31:42 +000025}
26
Tim Peterseb28ef22001-06-02 05:27:19 +000027/* Define this out if you don't want conversion statistics on exit. */
Fred Drake1bff34a2000-08-31 19:31:38 +000028#undef SHOW_CONVERSION_COUNTS
29
Tim Peterseb28ef22001-06-02 05:27:19 +000030/* See large comment block below. This must be >= 1. */
31#define PERTURB_SHIFT 5
32
Guido van Rossum16e93a81997-01-28 00:00:11 +000033/*
Tim Peterseb28ef22001-06-02 05:27:19 +000034Major subtleties ahead: Most hash schemes depend on having a "good" hash
35function, in the sense of simulating randomness. Python doesn't: its most
36important hash functions (for strings and ints) are very regular in common
37cases:
Tim Peters15d49292001-05-27 07:39:22 +000038
Tim Peterseb28ef22001-06-02 05:27:19 +000039>>> map(hash, (0, 1, 2, 3))
40[0, 1, 2, 3]
41>>> map(hash, ("namea", "nameb", "namec", "named"))
42[-1658398457, -1658398460, -1658398459, -1658398462]
43>>>
Tim Peters15d49292001-05-27 07:39:22 +000044
Tim Peterseb28ef22001-06-02 05:27:19 +000045This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
46the low-order i bits as the initial table index is extremely fast, and there
47are no collisions at all for dicts indexed by a contiguous range of ints.
48The same is approximately true when keys are "consecutive" strings. So this
49gives better-than-random behavior in common cases, and that's very desirable.
Tim Peters15d49292001-05-27 07:39:22 +000050
Tim Peterseb28ef22001-06-02 05:27:19 +000051OTOH, when collisions occur, the tendency to fill contiguous slices of the
52hash table makes a good collision resolution strategy crucial. Taking only
53the last i bits of the hash code is also vulnerable: for example, consider
54[i << 16 for i in range(20000)] as a set of keys. Since ints are their own
55hash codes, and this fits in a dict of size 2**15, the last 15 bits of every
56hash code are all 0: they *all* map to the same table index.
Tim Peters15d49292001-05-27 07:39:22 +000057
Tim Peterseb28ef22001-06-02 05:27:19 +000058But catering to unusual cases should not slow the usual ones, so we just take
59the last i bits anyway. It's up to collision resolution to do the rest. If
60we *usually* find the key we're looking for on the first try (and, it turns
61out, we usually do -- the table load factor is kept under 2/3, so the odds
62are solidly in our favor), then it makes best sense to keep the initial index
63computation dirt cheap.
Tim Peters15d49292001-05-27 07:39:22 +000064
Tim Peterseb28ef22001-06-02 05:27:19 +000065The first half of collision resolution is to visit table indices via this
66recurrence:
Tim Peters15d49292001-05-27 07:39:22 +000067
Tim Peterseb28ef22001-06-02 05:27:19 +000068 j = ((5*j) + 1) mod 2**i
Tim Peters15d49292001-05-27 07:39:22 +000069
Tim Peterseb28ef22001-06-02 05:27:19 +000070For any initial j in range(2**i), repeating that 2**i times generates each
71int in range(2**i) exactly once (see any text on random-number generation for
72proof). By itself, this doesn't help much: like linear probing (setting
73j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
74order. This would be bad, except that's not the only thing we do, and it's
75actually *good* in the common cases where hash keys are consecutive. In an
76example that's really too small to make this entirely clear, for a table of
77size 2**3 the order of indices is:
Tim Peters15d49292001-05-27 07:39:22 +000078
Tim Peterseb28ef22001-06-02 05:27:19 +000079 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
80
81If two things come in at index 5, the first place we look after is index 2,
82not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
83Linear probing is deadly in this case because there the fixed probe order
84is the *same* as the order consecutive keys are likely to arrive. But it's
85extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
86and certain that consecutive hash codes do not.
87
88The other half of the strategy is to get the other bits of the hash code
89into play. This is done by initializing a (unsigned) vrbl "perturb" to the
90full hash code, and changing the recurrence to:
91
92 j = (5*j) + 1 + perturb;
93 perturb >>= PERTURB_SHIFT;
94 use j % 2**i as the next table index;
95
96Now the probe sequence depends (eventually) on every bit in the hash code,
97and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
98because it quickly magnifies small differences in the bits that didn't affect
99the initial index. Note that because perturb is unsigned, if the recurrence
100is executed often enough perturb eventually becomes and remains 0. At that
101point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
102that's certain to find an empty slot eventually (since it generates every int
103in range(2**i), and we make sure there's always at least one empty slot).
104
105Selecting a good value for PERTURB_SHIFT is a balancing act. You want it
106small so that the high bits of the hash code continue to affect the probe
107sequence across iterations; but you want it large so that in really bad cases
108the high-order hash bits have an effect on early iterations. 5 was "the
109best" in minimizing total collisions across experiments Tim Peters ran (on
110both normal and pathological cases), but 4 and 6 weren't significantly worse.
111
112Historical: Reimer Behrends contributed the idea of using a polynomial-based
113approach, using repeated multiplication by x in GF(2**n) where an irreducible
114polynomial for each table size was chosen such that x was a primitive root.
115Christian Tismer later extended that to use division by x instead, as an
116efficient way to get the high bits of the hash code into play. This scheme
117also gave excellent collision statistics, but was more expensive: two
118if-tests were required inside the loop; computing "the next" index took about
119the same number of operations but without as much potential parallelism
120(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
121above, and then shifting perturb can be done while the table index is being
Brett Cannon77ae87c2007-10-10 00:07:50 +0000122masked); and the PyDictObject struct required a member to hold the table's
Tim Peterseb28ef22001-06-02 05:27:19 +0000123polynomial. In Tim's experiments the current scheme ran faster, produced
124equally good collision statistics, needed less code & used less memory.
Tim Peters9b10f7e2006-05-30 04:16:25 +0000125
126Theoretical Python 2.5 headache: hash codes are only C "long", but
127sizeof(Py_ssize_t) > sizeof(long) may be possible. In that case, and if a
128dict is genuinely huge, then only the slots directly reachable via indexing
129by a C long can be the first slot in a probe sequence. The probe sequence
130will still eventually reach every slot in the table, but the collision rate
131on initial probes may be much higher than this scheme was designed for.
132Getting a hash code as fat as Py_ssize_t is the only real cure. But in
133practice, this probably won't make a lick of difference for many years (at
134which point everyone will have terabytes of RAM on 64-bit boxes).
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000135*/
Tim Petersdea48ec2001-05-22 20:40:22 +0000136
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000137/* Object used as dummy key to fill deleted entries */
Brett Cannon77ae87c2007-10-10 00:07:50 +0000138static PyObject *dummy = NULL; /* Initialized by first call to newPyDictObject() */
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000139
Armin Rigoe1709372006-04-12 17:06:05 +0000140#ifdef Py_REF_DEBUG
141PyObject *
142_PyDict_Dummy(void)
143{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000144 return dummy;
Armin Rigoe1709372006-04-12 17:06:05 +0000145}
146#endif
147
Fred Drake1bff34a2000-08-31 19:31:38 +0000148/* forward declarations */
Brett Cannon77ae87c2007-10-10 00:07:50 +0000149static PyDictEntry *
150lookdict_string(PyDictObject *mp, PyObject *key, long hash);
Fred Drake1bff34a2000-08-31 19:31:38 +0000151
152#ifdef SHOW_CONVERSION_COUNTS
153static long created = 0L;
154static long converted = 0L;
155
156static void
157show_counts(void)
158{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000159 fprintf(stderr, "created %ld string dicts\n", created);
160 fprintf(stderr, "converted %ld to normal dicts\n", converted);
161 fprintf(stderr, "%.2f%% conversion rate\n", (100.0*converted)/created);
Fred Drake1bff34a2000-08-31 19:31:38 +0000162}
163#endif
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000164
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000165/* Debug statistic to compare allocations with reuse through the free list */
166#undef SHOW_ALLOC_COUNT
167#ifdef SHOW_ALLOC_COUNT
168static size_t count_alloc = 0;
169static size_t count_reuse = 0;
170
171static void
172show_alloc(void)
173{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000174 fprintf(stderr, "Dict allocations: %" PY_FORMAT_SIZE_T "d\n",
175 count_alloc);
176 fprintf(stderr, "Dict reuse through freelist: %" PY_FORMAT_SIZE_T
177 "d\n", count_reuse);
178 fprintf(stderr, "%.2f%% reuse rate\n\n",
179 (100.0*count_reuse/(count_alloc+count_reuse)));
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000180}
181#endif
182
Antoine Pitrouf8387af2009-03-23 18:41:45 +0000183/* Debug statistic to count GC tracking of dicts */
184#ifdef SHOW_TRACK_COUNT
185static Py_ssize_t count_untracked = 0;
186static Py_ssize_t count_tracked = 0;
187
188static void
189show_track(void)
190{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000191 fprintf(stderr, "Dicts created: %" PY_FORMAT_SIZE_T "d\n",
192 count_tracked + count_untracked);
193 fprintf(stderr, "Dicts tracked by the GC: %" PY_FORMAT_SIZE_T
194 "d\n", count_tracked);
195 fprintf(stderr, "%.2f%% dict tracking rate\n\n",
196 (100.0*count_tracked/(count_untracked+count_tracked)));
Antoine Pitrouf8387af2009-03-23 18:41:45 +0000197}
198#endif
199
200
Tim Peters6d6c1a32001-08-02 04:15:00 +0000201/* Initialization macros.
202 There are two ways to create a dict: PyDict_New() is the main C API
203 function, and the tp_new slot maps to dict_new(). In the latter case we
204 can save a little time over what PyDict_New does because it's guaranteed
205 that the PyDictObject struct is already zeroed out.
206 Everyone except dict_new() should use EMPTY_TO_MINSIZE (unless they have
207 an excellent reason not to).
208*/
209
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000210#define INIT_NONZERO_DICT_SLOTS(mp) do { \
211 (mp)->ma_table = (mp)->ma_smalltable; \
212 (mp)->ma_mask = PyDict_MINSIZE - 1; \
Tim Peters6d6c1a32001-08-02 04:15:00 +0000213 } while(0)
214
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000215#define EMPTY_TO_MINSIZE(mp) do { \
216 memset((mp)->ma_smalltable, 0, sizeof((mp)->ma_smalltable)); \
217 (mp)->ma_used = (mp)->ma_fill = 0; \
218 INIT_NONZERO_DICT_SLOTS(mp); \
Tim Petersdea48ec2001-05-22 20:40:22 +0000219 } while(0)
220
Raymond Hettinger43442782004-03-17 21:55:03 +0000221/* Dictionary reuse scheme to save calls to malloc, free, and memset */
Christian Heimes5b970ad2008-02-06 13:33:44 +0000222#ifndef PyDict_MAXFREELIST
223#define PyDict_MAXFREELIST 80
224#endif
225static PyDictObject *free_list[PyDict_MAXFREELIST];
226static int numfree = 0;
Raymond Hettinger43442782004-03-17 21:55:03 +0000227
Christian Heimesf75dbef2008-02-08 00:11:31 +0000228void
229PyDict_Fini(void)
230{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000231 PyDictObject *op;
Christian Heimesf75dbef2008-02-08 00:11:31 +0000232
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000233 while (numfree) {
234 op = free_list[--numfree];
235 assert(PyDict_CheckExact(op));
236 PyObject_GC_Del(op);
237 }
Christian Heimesf75dbef2008-02-08 00:11:31 +0000238}
239
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000240PyObject *
Thomas Wouters78890102000-07-22 19:25:51 +0000241PyDict_New(void)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000242{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000243 register PyDictObject *mp;
244 if (dummy == NULL) { /* Auto-initialize dummy */
245 dummy = PyString_FromString("<dummy key>");
246 if (dummy == NULL)
247 return NULL;
Fred Drake1bff34a2000-08-31 19:31:38 +0000248#ifdef SHOW_CONVERSION_COUNTS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000249 Py_AtExit(show_counts);
Fred Drake1bff34a2000-08-31 19:31:38 +0000250#endif
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000251#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000252 Py_AtExit(show_alloc);
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000253#endif
Antoine Pitrouf8387af2009-03-23 18:41:45 +0000254#ifdef SHOW_TRACK_COUNT
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000255 Py_AtExit(show_track);
Antoine Pitrouf8387af2009-03-23 18:41:45 +0000256#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000257 }
258 if (numfree) {
259 mp = free_list[--numfree];
260 assert (mp != NULL);
261 assert (Py_TYPE(mp) == &PyDict_Type);
262 _Py_NewReference((PyObject *)mp);
263 if (mp->ma_fill) {
264 EMPTY_TO_MINSIZE(mp);
265 } else {
266 /* At least set ma_table and ma_mask; these are wrong
267 if an empty but presized dict is added to freelist */
268 INIT_NONZERO_DICT_SLOTS(mp);
269 }
270 assert (mp->ma_used == 0);
271 assert (mp->ma_table == mp->ma_smalltable);
272 assert (mp->ma_mask == PyDict_MINSIZE - 1);
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000273#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000274 count_reuse++;
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000275#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000276 } else {
277 mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
278 if (mp == NULL)
279 return NULL;
280 EMPTY_TO_MINSIZE(mp);
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000281#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000282 count_alloc++;
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000283#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000284 }
285 mp->ma_lookup = lookdict_string;
Antoine Pitrouf8387af2009-03-23 18:41:45 +0000286#ifdef SHOW_TRACK_COUNT
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000287 count_untracked++;
Antoine Pitrouf8387af2009-03-23 18:41:45 +0000288#endif
Fred Drake1bff34a2000-08-31 19:31:38 +0000289#ifdef SHOW_CONVERSION_COUNTS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000290 ++created;
Fred Drake1bff34a2000-08-31 19:31:38 +0000291#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000292 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000293}
294
295/*
296The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000297This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000298Open addressing is preferred over chaining since the link overhead for
299chaining would be substantial (100% with typical malloc overhead).
300
Tim Peterseb28ef22001-06-02 05:27:19 +0000301The initial probe index is computed as hash mod the table size. Subsequent
302probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000303
304All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000305
Tim Peterseb28ef22001-06-02 05:27:19 +0000306(The details in this version are due to Tim Peters, building on many past
307contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
308Christian Tismer).
Fred Drake1bff34a2000-08-31 19:31:38 +0000309
Tim Petersd770ebd2006-06-01 15:50:44 +0000310lookdict() is general-purpose, and may return NULL if (and only if) a
311comparison raises an exception (this was new in Python 2.5).
312lookdict_string() below is specialized to string keys, comparison of which can
313never raise an exception; that function can never return NULL. For both, when
Brett Cannon77ae87c2007-10-10 00:07:50 +0000314the key isn't found a PyDictEntry* is returned for which the me_value field is
Tim Petersd770ebd2006-06-01 15:50:44 +0000315NULL; this is the slot in the dict at which the key would have been found, and
316the caller can (if it wishes) add the <key, value> pair to the returned
Brett Cannon77ae87c2007-10-10 00:07:50 +0000317PyDictEntry*.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000318*/
Brett Cannon77ae87c2007-10-10 00:07:50 +0000319static PyDictEntry *
320lookdict(PyDictObject *mp, PyObject *key, register long hash)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000321{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000322 register size_t i;
323 register size_t perturb;
324 register PyDictEntry *freeslot;
325 register size_t mask = (size_t)mp->ma_mask;
326 PyDictEntry *ep0 = mp->ma_table;
327 register PyDictEntry *ep;
328 register int cmp;
329 PyObject *startkey;
Tim Peterseb28ef22001-06-02 05:27:19 +0000330
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000331 i = (size_t)hash & mask;
332 ep = &ep0[i];
333 if (ep->me_key == NULL || ep->me_key == key)
334 return ep;
Tim Peters7b5d0af2001-06-03 04:14:43 +0000335
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000336 if (ep->me_key == dummy)
337 freeslot = ep;
338 else {
339 if (ep->me_hash == hash) {
340 startkey = ep->me_key;
341 Py_INCREF(startkey);
342 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
343 Py_DECREF(startkey);
344 if (cmp < 0)
345 return NULL;
346 if (ep0 == mp->ma_table && ep->me_key == startkey) {
347 if (cmp > 0)
348 return ep;
349 }
350 else {
351 /* The compare did major nasty stuff to the
352 * dict: start over.
353 * XXX A clever adversary could prevent this
354 * XXX from terminating.
355 */
356 return lookdict(mp, key, hash);
357 }
358 }
359 freeslot = NULL;
360 }
Tim Peters15d49292001-05-27 07:39:22 +0000361
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000362 /* In the loop, me_key == dummy is by far (factor of 100s) the
363 least likely outcome, so test for that last. */
364 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
365 i = (i << 2) + i + perturb + 1;
366 ep = &ep0[i & mask];
367 if (ep->me_key == NULL)
368 return freeslot == NULL ? ep : freeslot;
369 if (ep->me_key == key)
370 return ep;
371 if (ep->me_hash == hash && ep->me_key != dummy) {
372 startkey = ep->me_key;
373 Py_INCREF(startkey);
374 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
375 Py_DECREF(startkey);
376 if (cmp < 0)
377 return NULL;
378 if (ep0 == mp->ma_table && ep->me_key == startkey) {
379 if (cmp > 0)
380 return ep;
381 }
382 else {
383 /* The compare did major nasty stuff to the
384 * dict: start over.
385 * XXX A clever adversary could prevent this
386 * XXX from terminating.
387 */
388 return lookdict(mp, key, hash);
389 }
390 }
391 else if (ep->me_key == dummy && freeslot == NULL)
392 freeslot = ep;
393 }
394 assert(0); /* NOT REACHED */
395 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000396}
397
398/*
Fred Drake1bff34a2000-08-31 19:31:38 +0000399 * Hacked up version of lookdict which can assume keys are always strings;
Tim Petersd770ebd2006-06-01 15:50:44 +0000400 * this assumption allows testing for errors during PyObject_RichCompareBool()
401 * to be dropped; string-string comparisons never raise exceptions. This also
402 * means we don't need to go through PyObject_RichCompareBool(); we can always
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000403 * use _PyString_Eq() directly.
Fred Drake1bff34a2000-08-31 19:31:38 +0000404 *
Tim Petersd770ebd2006-06-01 15:50:44 +0000405 * This is valuable because dicts with only string keys are very common.
Fred Drake1bff34a2000-08-31 19:31:38 +0000406 */
Brett Cannon77ae87c2007-10-10 00:07:50 +0000407static PyDictEntry *
408lookdict_string(PyDictObject *mp, PyObject *key, register long hash)
Fred Drake1bff34a2000-08-31 19:31:38 +0000409{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000410 register size_t i;
411 register size_t perturb;
412 register PyDictEntry *freeslot;
413 register size_t mask = (size_t)mp->ma_mask;
414 PyDictEntry *ep0 = mp->ma_table;
415 register PyDictEntry *ep;
Fred Drake1bff34a2000-08-31 19:31:38 +0000416
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000417 /* Make sure this function doesn't have to handle non-string keys,
418 including subclasses of str; e.g., one reason to subclass
419 strings is to override __eq__, and for speed we don't cater to
420 that here. */
421 if (!PyString_CheckExact(key)) {
Fred Drake1bff34a2000-08-31 19:31:38 +0000422#ifdef SHOW_CONVERSION_COUNTS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000423 ++converted;
Fred Drake1bff34a2000-08-31 19:31:38 +0000424#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000425 mp->ma_lookup = lookdict;
426 return lookdict(mp, key, hash);
427 }
428 i = hash & mask;
429 ep = &ep0[i];
430 if (ep->me_key == NULL || ep->me_key == key)
431 return ep;
432 if (ep->me_key == dummy)
433 freeslot = ep;
434 else {
435 if (ep->me_hash == hash && _PyString_Eq(ep->me_key, key))
436 return ep;
437 freeslot = NULL;
438 }
Tim Peters15d49292001-05-27 07:39:22 +0000439
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000440 /* In the loop, me_key == dummy is by far (factor of 100s) the
441 least likely outcome, so test for that last. */
442 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
443 i = (i << 2) + i + perturb + 1;
444 ep = &ep0[i & mask];
445 if (ep->me_key == NULL)
446 return freeslot == NULL ? ep : freeslot;
447 if (ep->me_key == key
448 || (ep->me_hash == hash
449 && ep->me_key != dummy
450 && _PyString_Eq(ep->me_key, key)))
451 return ep;
452 if (ep->me_key == dummy && freeslot == NULL)
453 freeslot = ep;
454 }
455 assert(0); /* NOT REACHED */
456 return 0;
Fred Drake1bff34a2000-08-31 19:31:38 +0000457}
458
Antoine Pitrouf8387af2009-03-23 18:41:45 +0000459#ifdef SHOW_TRACK_COUNT
460#define INCREASE_TRACK_COUNT \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000461 (count_tracked++, count_untracked--);
Antoine Pitrouf8387af2009-03-23 18:41:45 +0000462#define DECREASE_TRACK_COUNT \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000463 (count_tracked--, count_untracked++);
Antoine Pitrouf8387af2009-03-23 18:41:45 +0000464#else
465#define INCREASE_TRACK_COUNT
466#define DECREASE_TRACK_COUNT
467#endif
468
469#define MAINTAIN_TRACKING(mp, key, value) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000470 do { \
471 if (!_PyObject_GC_IS_TRACKED(mp)) { \
472 if (_PyObject_GC_MAY_BE_TRACKED(key) || \
473 _PyObject_GC_MAY_BE_TRACKED(value)) { \
474 _PyObject_GC_TRACK(mp); \
475 INCREASE_TRACK_COUNT \
476 } \
477 } \
478 } while(0)
Antoine Pitrouf8387af2009-03-23 18:41:45 +0000479
480void
481_PyDict_MaybeUntrack(PyObject *op)
482{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000483 PyDictObject *mp;
484 PyObject *value;
485 Py_ssize_t mask, i;
486 PyDictEntry *ep;
Antoine Pitrouf8387af2009-03-23 18:41:45 +0000487
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000488 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
489 return;
490
491 mp = (PyDictObject *) op;
492 ep = mp->ma_table;
493 mask = mp->ma_mask;
494 for (i = 0; i <= mask; i++) {
495 if ((value = ep[i].me_value) == NULL)
496 continue;
497 if (_PyObject_GC_MAY_BE_TRACKED(value) ||
498 _PyObject_GC_MAY_BE_TRACKED(ep[i].me_key))
499 return;
500 }
501 DECREASE_TRACK_COUNT
502 _PyObject_GC_UNTRACK(op);
Antoine Pitrouf8387af2009-03-23 18:41:45 +0000503}
504
Fred Drake1bff34a2000-08-31 19:31:38 +0000505/*
Antoine Pitrou6a1cd1b2012-02-27 00:45:12 +0100506Internal routine to insert a new item into the table when you have entry object.
507Used by insertdict.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000508*/
Armin Rigo35f6d362006-06-01 13:19:12 +0000509static int
Antoine Pitrou6a1cd1b2012-02-27 00:45:12 +0100510insertdict_by_entry(register PyDictObject *mp, PyObject *key, long hash,
511 PyDictEntry *ep, PyObject *value)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000512{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000513 PyObject *old_value;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000514
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000515 MAINTAIN_TRACKING(mp, key, value);
516 if (ep->me_value != NULL) {
517 old_value = ep->me_value;
518 ep->me_value = value;
519 Py_DECREF(old_value); /* which **CAN** re-enter */
520 Py_DECREF(key);
521 }
522 else {
523 if (ep->me_key == NULL)
524 mp->ma_fill++;
525 else {
526 assert(ep->me_key == dummy);
527 Py_DECREF(dummy);
528 }
529 ep->me_key = key;
530 ep->me_hash = (Py_ssize_t)hash;
531 ep->me_value = value;
532 mp->ma_used++;
533 }
534 return 0;
Armin Rigo35f6d362006-06-01 13:19:12 +0000535}
536
Antoine Pitrou6a1cd1b2012-02-27 00:45:12 +0100537
538/*
539Internal routine to insert a new item into the table.
540Used both by the internal resize routine and by the public insert routine.
541Eats a reference to key and one to value.
542Returns -1 if an error occurred, or 0 on success.
543*/
544static int
545insertdict(register PyDictObject *mp, PyObject *key, long hash, PyObject *value)
546{
547 register PyDictEntry *ep;
548
549 assert(mp->ma_lookup != NULL);
550 ep = mp->ma_lookup(mp, key, hash);
551 if (ep == NULL) {
552 Py_DECREF(key);
553 Py_DECREF(value);
554 return -1;
555 }
556 return insertdict_by_entry(mp, key, hash, ep, value);
557}
558
Armin Rigo35f6d362006-06-01 13:19:12 +0000559/*
560Internal routine used by dictresize() to insert an item which is
561known to be absent from the dict. This routine also assumes that
562the dict contains no deleted entries. Besides the performance benefit,
563using insertdict() in dictresize() is dangerous (SF bug #1456209).
Tim Petersd770ebd2006-06-01 15:50:44 +0000564Note that no refcounts are changed by this routine; if needed, the caller
565is responsible for incref'ing `key` and `value`.
Armin Rigo35f6d362006-06-01 13:19:12 +0000566*/
567static void
Brett Cannon77ae87c2007-10-10 00:07:50 +0000568insertdict_clean(register PyDictObject *mp, PyObject *key, long hash,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000569 PyObject *value)
Armin Rigo35f6d362006-06-01 13:19:12 +0000570{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000571 register size_t i;
572 register size_t perturb;
573 register size_t mask = (size_t)mp->ma_mask;
574 PyDictEntry *ep0 = mp->ma_table;
575 register PyDictEntry *ep;
Armin Rigo35f6d362006-06-01 13:19:12 +0000576
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000577 MAINTAIN_TRACKING(mp, key, value);
578 i = hash & mask;
579 ep = &ep0[i];
580 for (perturb = hash; ep->me_key != NULL; perturb >>= PERTURB_SHIFT) {
581 i = (i << 2) + i + perturb + 1;
582 ep = &ep0[i & mask];
583 }
584 assert(ep->me_value == NULL);
585 mp->ma_fill++;
586 ep->me_key = key;
587 ep->me_hash = (Py_ssize_t)hash;
588 ep->me_value = value;
589 mp->ma_used++;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000590}
591
592/*
593Restructure the table by allocating a new table and reinserting all
594items again. When entries have been deleted, the new table may
595actually be smaller than the old one.
596*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000597static int
Brett Cannon77ae87c2007-10-10 00:07:50 +0000598dictresize(PyDictObject *mp, Py_ssize_t minused)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000599{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000600 Py_ssize_t newsize;
601 PyDictEntry *oldtable, *newtable, *ep;
602 Py_ssize_t i;
603 int is_oldtable_malloced;
604 PyDictEntry small_copy[PyDict_MINSIZE];
Tim Peters91a364d2001-05-19 07:04:38 +0000605
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000606 assert(minused >= 0);
Tim Peters0c6010b2001-05-23 23:33:57 +0000607
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000608 /* Find the smallest table size > minused. */
609 for (newsize = PyDict_MINSIZE;
610 newsize <= minused && newsize > 0;
611 newsize <<= 1)
612 ;
613 if (newsize <= 0) {
614 PyErr_NoMemory();
615 return -1;
616 }
Tim Peters0c6010b2001-05-23 23:33:57 +0000617
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000618 /* Get space for a new table. */
619 oldtable = mp->ma_table;
620 assert(oldtable != NULL);
621 is_oldtable_malloced = oldtable != mp->ma_smalltable;
Tim Peters0c6010b2001-05-23 23:33:57 +0000622
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000623 if (newsize == PyDict_MINSIZE) {
624 /* A large table is shrinking, or we can't get any smaller. */
625 newtable = mp->ma_smalltable;
626 if (newtable == oldtable) {
627 if (mp->ma_fill == mp->ma_used) {
628 /* No dummies, so no point doing anything. */
629 return 0;
630 }
631 /* We're not going to resize it, but rebuild the
632 table anyway to purge old dummy entries.
633 Subtle: This is *necessary* if fill==size,
634 as lookdict needs at least one virgin slot to
635 terminate failing searches. If fill < size, it's
636 merely desirable, as dummies slow searches. */
637 assert(mp->ma_fill > mp->ma_used);
638 memcpy(small_copy, oldtable, sizeof(small_copy));
639 oldtable = small_copy;
640 }
641 }
642 else {
643 newtable = PyMem_NEW(PyDictEntry, newsize);
644 if (newtable == NULL) {
645 PyErr_NoMemory();
646 return -1;
647 }
648 }
Tim Peters0c6010b2001-05-23 23:33:57 +0000649
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000650 /* Make the dict empty, using the new table. */
651 assert(newtable != oldtable);
652 mp->ma_table = newtable;
653 mp->ma_mask = newsize - 1;
654 memset(newtable, 0, sizeof(PyDictEntry) * newsize);
655 mp->ma_used = 0;
656 i = mp->ma_fill;
657 mp->ma_fill = 0;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000658
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000659 /* Copy the data over; this is refcount-neutral for active entries;
660 dummy entries aren't copied over, of course */
661 for (ep = oldtable; i > 0; ep++) {
662 if (ep->me_value != NULL) { /* active entry */
663 --i;
664 insertdict_clean(mp, ep->me_key, (long)ep->me_hash,
665 ep->me_value);
666 }
667 else if (ep->me_key != NULL) { /* dummy entry */
668 --i;
669 assert(ep->me_key == dummy);
670 Py_DECREF(ep->me_key);
671 }
672 /* else key == value == NULL: nothing to do */
673 }
Guido van Rossumd7047b31995-01-02 19:07:15 +0000674
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000675 if (is_oldtable_malloced)
676 PyMem_DEL(oldtable);
677 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000678}
679
Raymond Hettingerfd7ed402007-12-18 21:24:09 +0000680/* Create a new dictionary pre-sized to hold an estimated number of elements.
681 Underestimates are okay because the dictionary will resize as necessary.
682 Overestimates just mean the dictionary will be more sparse than usual.
683*/
684
685PyObject *
686_PyDict_NewPresized(Py_ssize_t minused)
687{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000688 PyObject *op = PyDict_New();
Raymond Hettingerfd7ed402007-12-18 21:24:09 +0000689
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000690 if (minused>5 && op != NULL && dictresize((PyDictObject *)op, minused) == -1) {
691 Py_DECREF(op);
692 return NULL;
693 }
694 return op;
Raymond Hettingerfd7ed402007-12-18 21:24:09 +0000695}
696
Tim Petersd770ebd2006-06-01 15:50:44 +0000697/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
698 * that may occur (originally dicts supported only string keys, and exceptions
699 * weren't possible). So, while the original intent was that a NULL return
Andrew M. Kuchling0067b5f2006-08-04 20:37:43 +0000700 * meant the key wasn't present, in reality it can mean that, or that an error
Tim Petersd770ebd2006-06-01 15:50:44 +0000701 * (suppressed) occurred while computing the key's hash, or that some error
702 * (suppressed) occurred when comparing keys in the dict's internal probe
703 * sequence. A nasty example of the latter is when a Python-coded comparison
704 * function hits a stack-depth error, which can cause this to return NULL
705 * even if the key is present.
706 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000707PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000708PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000709{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000710 long hash;
711 PyDictObject *mp = (PyDictObject *)op;
712 PyDictEntry *ep;
713 PyThreadState *tstate;
714 if (!PyDict_Check(op))
715 return NULL;
716 if (!PyString_CheckExact(key) ||
717 (hash = ((PyStringObject *) key)->ob_shash) == -1)
718 {
719 hash = PyObject_Hash(key);
720 if (hash == -1) {
721 PyErr_Clear();
722 return NULL;
723 }
724 }
Armin Rigo35f6d362006-06-01 13:19:12 +0000725
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000726 /* We can arrive here with a NULL tstate during initialization: try
727 running "python -Wi" for an example related to string interning.
728 Let's just hope that no exception occurs then... This must be
729 _PyThreadState_Current and not PyThreadState_GET() because in debug
730 mode, the latter complains if tstate is NULL. */
731 tstate = _PyThreadState_Current;
732 if (tstate != NULL && tstate->curexc_type != NULL) {
733 /* preserve the existing exception */
734 PyObject *err_type, *err_value, *err_tb;
735 PyErr_Fetch(&err_type, &err_value, &err_tb);
736 ep = (mp->ma_lookup)(mp, key, hash);
737 /* ignore errors */
738 PyErr_Restore(err_type, err_value, err_tb);
739 if (ep == NULL)
740 return NULL;
741 }
742 else {
743 ep = (mp->ma_lookup)(mp, key, hash);
744 if (ep == NULL) {
745 PyErr_Clear();
746 return NULL;
747 }
748 }
749 return ep->me_value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000750}
751
Serhiy Storchaka1c496172016-02-10 10:28:06 +0200752/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
753 This returns NULL *with* an exception set if an exception occurred.
754 It returns NULL *without* an exception set if the key wasn't present.
755*/
756PyObject *
757_PyDict_GetItemWithError(PyObject *op, PyObject *key)
758{
759 long hash;
760 PyDictObject *mp = (PyDictObject *)op;
761 PyDictEntry *ep;
762 if (!PyDict_Check(op)) {
763 PyErr_BadInternalCall();
764 return NULL;
765 }
766 if (!PyString_CheckExact(key) ||
767 (hash = ((PyStringObject *) key)->ob_shash) == -1)
768 {
769 hash = PyObject_Hash(key);
770 if (hash == -1) {
771 return NULL;
772 }
773 }
774
775 ep = (mp->ma_lookup)(mp, key, hash);
776 if (ep == NULL) {
777 return NULL;
778 }
779 return ep->me_value;
780}
781
Antoine Pitrou6a1cd1b2012-02-27 00:45:12 +0100782static int
783dict_set_item_by_hash_or_entry(register PyObject *op, PyObject *key,
784 long hash, PyDictEntry *ep, PyObject *value)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000785{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000786 register PyDictObject *mp;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000787 register Py_ssize_t n_used;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000788
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000789 mp = (PyDictObject *)op;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000790 assert(mp->ma_fill <= mp->ma_mask); /* at least one empty slot */
791 n_used = mp->ma_used;
792 Py_INCREF(value);
793 Py_INCREF(key);
Antoine Pitrou6a1cd1b2012-02-27 00:45:12 +0100794 if (ep == NULL) {
795 if (insertdict(mp, key, hash, value) != 0)
796 return -1;
797 }
798 else {
799 if (insertdict_by_entry(mp, key, hash, ep, value) != 0)
800 return -1;
801 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000802 /* If we added a key, we can safely resize. Otherwise just return!
803 * If fill >= 2/3 size, adjust size. Normally, this doubles or
804 * quaduples the size, but it's also possible for the dict to shrink
805 * (if ma_fill is much larger than ma_used, meaning a lot of dict
806 * keys have been * deleted).
807 *
808 * Quadrupling the size improves average dictionary sparseness
809 * (reducing collisions) at the cost of some memory and iteration
810 * speed (which loops over every possible entry). It also halves
811 * the number of expensive resize operations in a growing dictionary.
812 *
813 * Very large dictionaries (over 50K items) use doubling instead.
814 * This may help applications with severe memory constraints.
815 */
816 if (!(mp->ma_used > n_used && mp->ma_fill*3 >= (mp->ma_mask+1)*2))
817 return 0;
818 return dictresize(mp, (mp->ma_used > 50000 ? 2 : 4) * mp->ma_used);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000819}
820
Antoine Pitrou6a1cd1b2012-02-27 00:45:12 +0100821/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
822 * dictionary if it's merely replacing the value for an existing key.
823 * This means that it's safe to loop over a dictionary with PyDict_Next()
824 * and occasionally replace a value -- but you can't insert new keys or
825 * remove them.
826 */
827int
828PyDict_SetItem(register PyObject *op, PyObject *key, PyObject *value)
829{
830 register long hash;
831
832 if (!PyDict_Check(op)) {
833 PyErr_BadInternalCall();
834 return -1;
835 }
836 assert(key);
837 assert(value);
838 if (PyString_CheckExact(key)) {
839 hash = ((PyStringObject *)key)->ob_shash;
840 if (hash == -1)
841 hash = PyObject_Hash(key);
842 }
843 else {
844 hash = PyObject_Hash(key);
845 if (hash == -1)
846 return -1;
847 }
848 return dict_set_item_by_hash_or_entry(op, key, hash, NULL, value);
849}
850
Antoine Pitrouf939b3c2016-12-27 15:08:27 +0100851static int
852delitem_common(PyDictObject *mp, PyDictEntry *ep)
853{
854 PyObject *old_value, *old_key;
855
856 old_key = ep->me_key;
857 Py_INCREF(dummy);
858 ep->me_key = dummy;
859 old_value = ep->me_value;
860 ep->me_value = NULL;
861 mp->ma_used--;
862 Py_DECREF(old_value);
863 Py_DECREF(old_key);
864 return 0;
865}
866
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000867int
Tim Peters1f5871e2000-07-04 17:44:48 +0000868PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000869{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000870 register PyDictObject *mp;
871 register long hash;
872 register PyDictEntry *ep;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000873
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000874 if (!PyDict_Check(op)) {
875 PyErr_BadInternalCall();
876 return -1;
877 }
878 assert(key);
879 if (!PyString_CheckExact(key) ||
880 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
881 hash = PyObject_Hash(key);
882 if (hash == -1)
883 return -1;
884 }
885 mp = (PyDictObject *)op;
886 ep = (mp->ma_lookup)(mp, key, hash);
887 if (ep == NULL)
888 return -1;
889 if (ep->me_value == NULL) {
890 set_key_error(key);
891 return -1;
892 }
Antoine Pitrouf939b3c2016-12-27 15:08:27 +0100893
894 return delitem_common(mp, ep);
895}
896
897int
898_PyDict_DelItemIf(PyObject *op, PyObject *key,
899 int (*predicate)(PyObject *value))
900{
901 register PyDictObject *mp;
902 register long hash;
903 register PyDictEntry *ep;
904 int res;
905
906 if (!PyDict_Check(op)) {
907 PyErr_BadInternalCall();
908 return -1;
909 }
910 assert(key);
911 if (!PyString_CheckExact(key) ||
912 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
913 hash = PyObject_Hash(key);
914 if (hash == -1)
915 return -1;
916 }
917 mp = (PyDictObject *)op;
918 ep = (mp->ma_lookup)(mp, key, hash);
919 if (ep == NULL)
920 return -1;
921 if (ep->me_value == NULL) {
922 set_key_error(key);
923 return -1;
924 }
925 res = predicate(ep->me_value);
926 if (res == -1)
927 return -1;
928 if (res > 0)
929 return delitem_common(mp, ep);
930 else
931 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000932}
933
Guido van Rossum25831651993-05-19 14:50:45 +0000934void
Tim Peters1f5871e2000-07-04 17:44:48 +0000935PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000936{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000937 PyDictObject *mp;
938 PyDictEntry *ep, *table;
939 int table_is_malloced;
940 Py_ssize_t fill;
941 PyDictEntry small_copy[PyDict_MINSIZE];
Tim Petersdea48ec2001-05-22 20:40:22 +0000942#ifdef Py_DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000943 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +0000944#endif
945
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000946 if (!PyDict_Check(op))
947 return;
948 mp = (PyDictObject *)op;
Tim Petersdea48ec2001-05-22 20:40:22 +0000949#ifdef Py_DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000950 n = mp->ma_mask + 1;
951 i = 0;
Tim Petersdea48ec2001-05-22 20:40:22 +0000952#endif
953
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000954 table = mp->ma_table;
955 assert(table != NULL);
956 table_is_malloced = table != mp->ma_smalltable;
Tim Petersdea48ec2001-05-22 20:40:22 +0000957
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000958 /* This is delicate. During the process of clearing the dict,
959 * decrefs can cause the dict to mutate. To avoid fatal confusion
960 * (voice of experience), we have to make the dict empty before
961 * clearing the slots, and never refer to anything via mp->xxx while
962 * clearing.
963 */
964 fill = mp->ma_fill;
965 if (table_is_malloced)
966 EMPTY_TO_MINSIZE(mp);
Tim Petersdea48ec2001-05-22 20:40:22 +0000967
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000968 else if (fill > 0) {
969 /* It's a small table with something that needs to be cleared.
970 * Afraid the only safe way is to copy the dict entries into
971 * another small table first.
972 */
973 memcpy(small_copy, table, sizeof(small_copy));
974 table = small_copy;
975 EMPTY_TO_MINSIZE(mp);
976 }
977 /* else it's a small table that's already empty */
Tim Petersdea48ec2001-05-22 20:40:22 +0000978
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000979 /* Now we can finally clear things. If C had refcounts, we could
980 * assert that the refcount on table is 1 now, i.e. that this function
981 * has unique access to it, so decref side-effects can't alter it.
982 */
983 for (ep = table; fill > 0; ++ep) {
Tim Petersdea48ec2001-05-22 20:40:22 +0000984#ifdef Py_DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000985 assert(i < n);
986 ++i;
Tim Petersdea48ec2001-05-22 20:40:22 +0000987#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000988 if (ep->me_key) {
989 --fill;
990 Py_DECREF(ep->me_key);
991 Py_XDECREF(ep->me_value);
992 }
Tim Petersdea48ec2001-05-22 20:40:22 +0000993#ifdef Py_DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000994 else
995 assert(ep->me_value == NULL);
Tim Petersdea48ec2001-05-22 20:40:22 +0000996#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000997 }
Tim Petersdea48ec2001-05-22 20:40:22 +0000998
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000999 if (table_is_malloced)
1000 PyMem_DEL(table);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001001}
1002
Tim Peters080c88b2003-02-15 03:01:11 +00001003/*
1004 * Iterate over a dict. Use like so:
1005 *
Tim Peters9b10f7e2006-05-30 04:16:25 +00001006 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +00001007 * PyObject *key, *value;
1008 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +00001009 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Tim Peters080c88b2003-02-15 03:01:11 +00001010 * Refer to borrowed references in key and value.
1011 * }
1012 *
1013 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +00001014 * mutates the dict. One exception: it is safe if the loop merely changes
1015 * the values associated with the keys (but doesn't insert new keys or
1016 * delete keys), via PyDict_SetItem().
1017 */
Guido van Rossum25831651993-05-19 14:50:45 +00001018int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001019PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001020{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001021 register Py_ssize_t i;
1022 register Py_ssize_t mask;
1023 register PyDictEntry *ep;
Raymond Hettinger43442782004-03-17 21:55:03 +00001024
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001025 if (!PyDict_Check(op))
1026 return 0;
1027 i = *ppos;
1028 if (i < 0)
1029 return 0;
1030 ep = ((PyDictObject *)op)->ma_table;
1031 mask = ((PyDictObject *)op)->ma_mask;
1032 while (i <= mask && ep[i].me_value == NULL)
1033 i++;
1034 *ppos = i+1;
1035 if (i > mask)
1036 return 0;
1037 if (pkey)
1038 *pkey = ep[i].me_key;
1039 if (pvalue)
1040 *pvalue = ep[i].me_value;
1041 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001042}
1043
Raymond Hettingerd6fc72a2007-02-19 02:03:19 +00001044/* Internal version of PyDict_Next that returns a hash value in addition to the key and value.*/
1045int
1046_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue, long *phash)
1047{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001048 register Py_ssize_t i;
1049 register Py_ssize_t mask;
1050 register PyDictEntry *ep;
Raymond Hettingerd6fc72a2007-02-19 02:03:19 +00001051
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001052 if (!PyDict_Check(op))
1053 return 0;
1054 i = *ppos;
1055 if (i < 0)
1056 return 0;
1057 ep = ((PyDictObject *)op)->ma_table;
1058 mask = ((PyDictObject *)op)->ma_mask;
1059 while (i <= mask && ep[i].me_value == NULL)
1060 i++;
1061 *ppos = i+1;
1062 if (i > mask)
1063 return 0;
1064 *phash = (long)(ep[i].me_hash);
1065 if (pkey)
1066 *pkey = ep[i].me_key;
1067 if (pvalue)
1068 *pvalue = ep[i].me_value;
1069 return 1;
Raymond Hettingerd6fc72a2007-02-19 02:03:19 +00001070}
1071
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001072/* Methods */
1073
1074static void
Brett Cannon77ae87c2007-10-10 00:07:50 +00001075dict_dealloc(register PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001076{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001077 register PyDictEntry *ep;
1078 Py_ssize_t fill = mp->ma_fill;
1079 PyObject_GC_UnTrack(mp);
1080 Py_TRASHCAN_SAFE_BEGIN(mp)
1081 for (ep = mp->ma_table; fill > 0; ep++) {
1082 if (ep->me_key) {
1083 --fill;
1084 Py_DECREF(ep->me_key);
1085 Py_XDECREF(ep->me_value);
1086 }
1087 }
1088 if (mp->ma_table != mp->ma_smalltable)
1089 PyMem_DEL(mp->ma_table);
1090 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
1091 free_list[numfree++] = mp;
1092 else
1093 Py_TYPE(mp)->tp_free((PyObject *)mp);
1094 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001095}
1096
1097static int
Brett Cannon77ae87c2007-10-10 00:07:50 +00001098dict_print(register PyDictObject *mp, register FILE *fp, register int flags)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001099{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001100 register Py_ssize_t i;
1101 register Py_ssize_t any;
1102 int status;
Guido van Rossum255443b1998-04-10 22:47:14 +00001103
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001104 status = Py_ReprEnter((PyObject*)mp);
1105 if (status != 0) {
1106 if (status < 0)
1107 return status;
1108 Py_BEGIN_ALLOW_THREADS
1109 fprintf(fp, "{...}");
1110 Py_END_ALLOW_THREADS
1111 return 0;
1112 }
Guido van Rossum255443b1998-04-10 22:47:14 +00001113
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001114 Py_BEGIN_ALLOW_THREADS
1115 fprintf(fp, "{");
1116 Py_END_ALLOW_THREADS
1117 any = 0;
1118 for (i = 0; i <= mp->ma_mask; i++) {
1119 PyDictEntry *ep = mp->ma_table + i;
1120 PyObject *pvalue = ep->me_value;
1121 if (pvalue != NULL) {
1122 /* Prevent PyObject_Repr from deleting value during
1123 key format */
1124 Py_INCREF(pvalue);
1125 if (any++ > 0) {
1126 Py_BEGIN_ALLOW_THREADS
1127 fprintf(fp, ", ");
1128 Py_END_ALLOW_THREADS
1129 }
1130 if (PyObject_Print((PyObject *)ep->me_key, fp, 0)!=0) {
1131 Py_DECREF(pvalue);
1132 Py_ReprLeave((PyObject*)mp);
1133 return -1;
1134 }
1135 Py_BEGIN_ALLOW_THREADS
1136 fprintf(fp, ": ");
1137 Py_END_ALLOW_THREADS
1138 if (PyObject_Print(pvalue, fp, 0) != 0) {
1139 Py_DECREF(pvalue);
1140 Py_ReprLeave((PyObject*)mp);
1141 return -1;
1142 }
1143 Py_DECREF(pvalue);
1144 }
1145 }
1146 Py_BEGIN_ALLOW_THREADS
1147 fprintf(fp, "}");
1148 Py_END_ALLOW_THREADS
1149 Py_ReprLeave((PyObject*)mp);
1150 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001151}
1152
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001153static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00001154dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001155{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001156 Py_ssize_t i;
1157 PyObject *s, *temp, *colon = NULL;
1158 PyObject *pieces = NULL, *result = NULL;
1159 PyObject *key, *value;
Guido van Rossum255443b1998-04-10 22:47:14 +00001160
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001161 i = Py_ReprEnter((PyObject *)mp);
1162 if (i != 0) {
1163 return i > 0 ? PyString_FromString("{...}") : NULL;
1164 }
Guido van Rossum255443b1998-04-10 22:47:14 +00001165
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001166 if (mp->ma_used == 0) {
1167 result = PyString_FromString("{}");
1168 goto Done;
1169 }
Tim Petersa7259592001-06-16 05:11:17 +00001170
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001171 pieces = PyList_New(0);
1172 if (pieces == NULL)
1173 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +00001174
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001175 colon = PyString_FromString(": ");
1176 if (colon == NULL)
1177 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +00001178
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001179 /* Do repr() on each key+value pair, and insert ": " between them.
1180 Note that repr may mutate the dict. */
1181 i = 0;
1182 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
1183 int status;
1184 /* Prevent repr from deleting value during key format. */
1185 Py_INCREF(value);
1186 s = PyObject_Repr(key);
1187 PyString_Concat(&s, colon);
1188 PyString_ConcatAndDel(&s, PyObject_Repr(value));
1189 Py_DECREF(value);
1190 if (s == NULL)
1191 goto Done;
1192 status = PyList_Append(pieces, s);
1193 Py_DECREF(s); /* append created a new ref */
1194 if (status < 0)
1195 goto Done;
1196 }
Tim Petersa7259592001-06-16 05:11:17 +00001197
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001198 /* Add "{}" decorations to the first and last items. */
1199 assert(PyList_GET_SIZE(pieces) > 0);
1200 s = PyString_FromString("{");
1201 if (s == NULL)
1202 goto Done;
1203 temp = PyList_GET_ITEM(pieces, 0);
1204 PyString_ConcatAndDel(&s, temp);
1205 PyList_SET_ITEM(pieces, 0, s);
1206 if (s == NULL)
1207 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +00001208
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001209 s = PyString_FromString("}");
1210 if (s == NULL)
1211 goto Done;
1212 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
1213 PyString_ConcatAndDel(&temp, s);
1214 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
1215 if (temp == NULL)
1216 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +00001217
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001218 /* Paste them all together with ", " between. */
1219 s = PyString_FromString(", ");
1220 if (s == NULL)
1221 goto Done;
1222 result = _PyString_Join(s, pieces);
1223 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +00001224
1225Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001226 Py_XDECREF(pieces);
1227 Py_XDECREF(colon);
1228 Py_ReprLeave((PyObject *)mp);
1229 return result;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001230}
1231
Martin v. Löwis18e16552006-02-15 17:27:45 +00001232static Py_ssize_t
Brett Cannon77ae87c2007-10-10 00:07:50 +00001233dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001234{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001235 return mp->ma_used;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001236}
1237
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001238static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00001239dict_subscript(PyDictObject *mp, register PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001240{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001241 PyObject *v;
1242 long hash;
1243 PyDictEntry *ep;
1244 assert(mp->ma_table != NULL);
1245 if (!PyString_CheckExact(key) ||
1246 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
1247 hash = PyObject_Hash(key);
1248 if (hash == -1)
1249 return NULL;
1250 }
1251 ep = (mp->ma_lookup)(mp, key, hash);
1252 if (ep == NULL)
1253 return NULL;
1254 v = ep->me_value;
1255 if (v == NULL) {
1256 if (!PyDict_CheckExact(mp)) {
1257 /* Look up __missing__ method if we're a subclass. */
1258 PyObject *missing, *res;
1259 static PyObject *missing_str = NULL;
1260 missing = _PyObject_LookupSpecial((PyObject *)mp,
1261 "__missing__",
1262 &missing_str);
1263 if (missing != NULL) {
1264 res = PyObject_CallFunctionObjArgs(missing,
1265 key, NULL);
1266 Py_DECREF(missing);
1267 return res;
1268 }
1269 else if (PyErr_Occurred())
1270 return NULL;
1271 }
1272 set_key_error(key);
1273 return NULL;
1274 }
1275 else
1276 Py_INCREF(v);
1277 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001278}
1279
1280static int
Brett Cannon77ae87c2007-10-10 00:07:50 +00001281dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001282{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001283 if (w == NULL)
1284 return PyDict_DelItem((PyObject *)mp, v);
1285 else
1286 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001287}
1288
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001289static PyMappingMethods dict_as_mapping = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001290 (lenfunc)dict_length, /*mp_length*/
1291 (binaryfunc)dict_subscript, /*mp_subscript*/
1292 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001293};
1294
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001295static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00001296dict_keys(register PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001297{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001298 register PyObject *v;
1299 register Py_ssize_t i, j;
1300 PyDictEntry *ep;
1301 Py_ssize_t mask, n;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001302
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001303 again:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001304 n = mp->ma_used;
1305 v = PyList_New(n);
1306 if (v == NULL)
1307 return NULL;
1308 if (n != mp->ma_used) {
1309 /* Durnit. The allocations caused the dict to resize.
1310 * Just start over, this shouldn't normally happen.
1311 */
1312 Py_DECREF(v);
1313 goto again;
1314 }
1315 ep = mp->ma_table;
1316 mask = mp->ma_mask;
1317 for (i = 0, j = 0; i <= mask; i++) {
1318 if (ep[i].me_value != NULL) {
1319 PyObject *key = ep[i].me_key;
1320 Py_INCREF(key);
1321 PyList_SET_ITEM(v, j, key);
1322 j++;
1323 }
1324 }
1325 assert(j == n);
1326 return v;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001327}
1328
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001329static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00001330dict_values(register PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001331{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001332 register PyObject *v;
1333 register Py_ssize_t i, j;
1334 PyDictEntry *ep;
1335 Py_ssize_t mask, n;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001336
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001337 again:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001338 n = mp->ma_used;
1339 v = PyList_New(n);
1340 if (v == NULL)
1341 return NULL;
1342 if (n != mp->ma_used) {
1343 /* Durnit. The allocations caused the dict to resize.
1344 * Just start over, this shouldn't normally happen.
1345 */
1346 Py_DECREF(v);
1347 goto again;
1348 }
1349 ep = mp->ma_table;
1350 mask = mp->ma_mask;
1351 for (i = 0, j = 0; i <= mask; i++) {
1352 if (ep[i].me_value != NULL) {
1353 PyObject *value = ep[i].me_value;
1354 Py_INCREF(value);
1355 PyList_SET_ITEM(v, j, value);
1356 j++;
1357 }
1358 }
1359 assert(j == n);
1360 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00001361}
1362
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001363static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00001364dict_items(register PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001365{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001366 register PyObject *v;
1367 register Py_ssize_t i, j, n;
1368 Py_ssize_t mask;
1369 PyObject *item, *key, *value;
1370 PyDictEntry *ep;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001371
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001372 /* Preallocate the list of tuples, to avoid allocations during
1373 * the loop over the items, which could trigger GC, which
1374 * could resize the dict. :-(
1375 */
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001376 again:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001377 n = mp->ma_used;
1378 v = PyList_New(n);
1379 if (v == NULL)
1380 return NULL;
1381 for (i = 0; i < n; i++) {
1382 item = PyTuple_New(2);
1383 if (item == NULL) {
1384 Py_DECREF(v);
1385 return NULL;
1386 }
1387 PyList_SET_ITEM(v, i, item);
1388 }
1389 if (n != mp->ma_used) {
1390 /* Durnit. The allocations caused the dict to resize.
1391 * Just start over, this shouldn't normally happen.
1392 */
1393 Py_DECREF(v);
1394 goto again;
1395 }
1396 /* Nothing we do below makes any function calls. */
1397 ep = mp->ma_table;
1398 mask = mp->ma_mask;
1399 for (i = 0, j = 0; i <= mask; i++) {
1400 if ((value=ep[i].me_value) != NULL) {
1401 key = ep[i].me_key;
1402 item = PyList_GET_ITEM(v, j);
1403 Py_INCREF(key);
1404 PyTuple_SET_ITEM(item, 0, key);
1405 Py_INCREF(value);
1406 PyTuple_SET_ITEM(item, 1, value);
1407 j++;
1408 }
1409 }
1410 assert(j == n);
1411 return v;
Guido van Rossum25831651993-05-19 14:50:45 +00001412}
1413
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001414static PyObject *
Tim Petersbca1cbc2002-12-09 22:56:13 +00001415dict_fromkeys(PyObject *cls, PyObject *args)
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001416{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001417 PyObject *seq;
1418 PyObject *value = Py_None;
1419 PyObject *it; /* iter(seq) */
1420 PyObject *key;
1421 PyObject *d;
1422 int status;
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001423
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001424 if (!PyArg_UnpackTuple(args, "fromkeys", 1, 2, &seq, &value))
1425 return NULL;
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001426
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001427 d = PyObject_CallObject(cls, NULL);
1428 if (d == NULL)
1429 return NULL;
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001430
Benjamin Peterson47fa4d52012-10-31 14:22:12 -04001431 if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
Benjamin Peterson0ec820f2012-10-31 14:05:55 -04001432 if (PyDict_CheckExact(seq)) {
1433 PyDictObject *mp = (PyDictObject *)d;
1434 PyObject *oldvalue;
1435 Py_ssize_t pos = 0;
1436 PyObject *key;
1437 long hash;
Raymond Hettingercdcf8872007-11-07 02:26:17 +00001438
INADA Naokie126f982016-12-20 16:07:18 +09001439 if (dictresize(mp, ((PyDictObject *)seq)->ma_used / 2 * 3)) {
Petri Lehtinen8ffbab82011-10-24 20:59:29 +03001440 Py_DECREF(d);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001441 return NULL;
Petri Lehtinen8ffbab82011-10-24 20:59:29 +03001442 }
Benjamin Peterson0ec820f2012-10-31 14:05:55 -04001443
1444 while (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash)) {
1445 Py_INCREF(key);
1446 Py_INCREF(value);
1447 if (insertdict(mp, key, hash, value)) {
1448 Py_DECREF(d);
1449 return NULL;
1450 }
1451 }
1452 return d;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001453 }
Benjamin Peterson0ec820f2012-10-31 14:05:55 -04001454 if (PyAnySet_CheckExact(seq)) {
1455 PyDictObject *mp = (PyDictObject *)d;
1456 Py_ssize_t pos = 0;
1457 PyObject *key;
1458 long hash;
Raymond Hettingercdcf8872007-11-07 02:26:17 +00001459
Raymond Hettinger77b3ae52015-05-13 03:13:28 -07001460 if (dictresize(mp, PySet_GET_SIZE(seq) / 2 * 3)) {
Petri Lehtinen8ffbab82011-10-24 20:59:29 +03001461 Py_DECREF(d);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001462 return NULL;
Petri Lehtinen8ffbab82011-10-24 20:59:29 +03001463 }
Benjamin Peterson0ec820f2012-10-31 14:05:55 -04001464
1465 while (_PySet_NextEntry(seq, &pos, &key, &hash)) {
1466 Py_INCREF(key);
1467 Py_INCREF(value);
1468 if (insertdict(mp, key, hash, value)) {
1469 Py_DECREF(d);
1470 return NULL;
1471 }
1472 }
1473 return d;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001474 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001475 }
Raymond Hettinger0bbbfc42007-03-20 21:27:24 +00001476
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001477 it = PyObject_GetIter(seq);
1478 if (it == NULL){
1479 Py_DECREF(d);
1480 return NULL;
1481 }
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001482
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001483 if (PyDict_CheckExact(d)) {
1484 while ((key = PyIter_Next(it)) != NULL) {
1485 status = PyDict_SetItem(d, key, value);
1486 Py_DECREF(key);
1487 if (status < 0)
1488 goto Fail;
1489 }
1490 } else {
1491 while ((key = PyIter_Next(it)) != NULL) {
1492 status = PyObject_SetItem(d, key, value);
1493 Py_DECREF(key);
1494 if (status < 0)
1495 goto Fail;
1496 }
1497 }
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001498
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001499 if (PyErr_Occurred())
1500 goto Fail;
1501 Py_DECREF(it);
1502 return d;
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001503
1504Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001505 Py_DECREF(it);
1506 Py_DECREF(d);
1507 return NULL;
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001508}
1509
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001510static int
1511dict_update_common(PyObject *self, PyObject *args, PyObject *kwds, char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001512{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001513 PyObject *arg = NULL;
1514 int result = 0;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001515
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001516 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
1517 result = -1;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001518
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001519 else if (arg != NULL) {
1520 if (PyObject_HasAttrString(arg, "keys"))
1521 result = PyDict_Merge(self, arg, 1);
1522 else
1523 result = PyDict_MergeFromSeq2(self, arg, 1);
1524 }
1525 if (result == 0 && kwds != NULL)
1526 result = PyDict_Merge(self, kwds, 1);
1527 return result;
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001528}
1529
1530static PyObject *
1531dict_update(PyObject *self, PyObject *args, PyObject *kwds)
1532{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001533 if (dict_update_common(self, args, kwds, "update") != -1)
1534 Py_RETURN_NONE;
1535 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001536}
1537
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001538/* Update unconditionally replaces existing items.
1539 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00001540 otherwise it leaves existing items unchanged.
1541
1542 PyDict_{Update,Merge} update/merge from a mapping object.
1543
Tim Petersf582b822001-12-11 18:51:08 +00001544 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00001545 producing iterable objects of length 2.
1546*/
1547
Tim Petersf582b822001-12-11 18:51:08 +00001548int
Tim Peters1fc240e2001-10-26 05:06:50 +00001549PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
1550{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001551 PyObject *it; /* iter(seq2) */
1552 Py_ssize_t i; /* index into seq2 of current element */
1553 PyObject *item; /* seq2[i] */
1554 PyObject *fast; /* item as a 2-tuple or 2-list */
Tim Peters1fc240e2001-10-26 05:06:50 +00001555
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001556 assert(d != NULL);
1557 assert(PyDict_Check(d));
1558 assert(seq2 != NULL);
Tim Peters1fc240e2001-10-26 05:06:50 +00001559
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001560 it = PyObject_GetIter(seq2);
1561 if (it == NULL)
1562 return -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00001563
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001564 for (i = 0; ; ++i) {
1565 PyObject *key, *value;
1566 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00001567
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001568 fast = NULL;
1569 item = PyIter_Next(it);
1570 if (item == NULL) {
1571 if (PyErr_Occurred())
1572 goto Fail;
1573 break;
1574 }
Tim Peters1fc240e2001-10-26 05:06:50 +00001575
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001576 /* Convert item to sequence, and verify length 2. */
1577 fast = PySequence_Fast(item, "");
1578 if (fast == NULL) {
1579 if (PyErr_ExceptionMatches(PyExc_TypeError))
1580 PyErr_Format(PyExc_TypeError,
1581 "cannot convert dictionary update "
1582 "sequence element #%zd to a sequence",
1583 i);
1584 goto Fail;
1585 }
1586 n = PySequence_Fast_GET_SIZE(fast);
1587 if (n != 2) {
1588 PyErr_Format(PyExc_ValueError,
1589 "dictionary update sequence element #%zd "
1590 "has length %zd; 2 is required",
1591 i, n);
1592 goto Fail;
1593 }
Tim Peters1fc240e2001-10-26 05:06:50 +00001594
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001595 /* Update/merge with this (key, value) pair. */
1596 key = PySequence_Fast_GET_ITEM(fast, 0);
1597 value = PySequence_Fast_GET_ITEM(fast, 1);
Serhiy Storchakae6a0b592017-05-20 20:05:27 +03001598 Py_INCREF(key);
1599 Py_INCREF(value);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001600 if (override || PyDict_GetItem(d, key) == NULL) {
1601 int status = PyDict_SetItem(d, key, value);
Serhiy Storchakae6a0b592017-05-20 20:05:27 +03001602 if (status < 0) {
1603 Py_DECREF(key);
1604 Py_DECREF(value);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001605 goto Fail;
Serhiy Storchakae6a0b592017-05-20 20:05:27 +03001606 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001607 }
Serhiy Storchakae6a0b592017-05-20 20:05:27 +03001608 Py_DECREF(key);
1609 Py_DECREF(value);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001610 Py_DECREF(fast);
1611 Py_DECREF(item);
1612 }
Tim Peters1fc240e2001-10-26 05:06:50 +00001613
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001614 i = 0;
1615 goto Return;
Tim Peters1fc240e2001-10-26 05:06:50 +00001616Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001617 Py_XDECREF(item);
1618 Py_XDECREF(fast);
1619 i = -1;
Tim Peters1fc240e2001-10-26 05:06:50 +00001620Return:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001621 Py_DECREF(it);
1622 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00001623}
1624
Tim Peters6d6c1a32001-08-02 04:15:00 +00001625int
1626PyDict_Update(PyObject *a, PyObject *b)
1627{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001628 return PyDict_Merge(a, b, 1);
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001629}
1630
1631int
1632PyDict_Merge(PyObject *a, PyObject *b, int override)
1633{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001634 register PyDictObject *mp, *other;
1635 register Py_ssize_t i;
1636 PyDictEntry *entry;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001637
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001638 /* We accept for the argument either a concrete dictionary object,
1639 * or an abstract "mapping" object. For the former, we can do
1640 * things quite efficiently. For the latter, we only require that
1641 * PyMapping_Keys() and PyObject_GetItem() be supported.
1642 */
1643 if (a == NULL || !PyDict_Check(a) || b == NULL) {
1644 PyErr_BadInternalCall();
1645 return -1;
1646 }
1647 mp = (PyDictObject*)a;
1648 if (PyDict_Check(b)) {
1649 other = (PyDictObject*)b;
1650 if (other == mp || other->ma_used == 0)
1651 /* a.update(a) or a.update({}); nothing to do */
1652 return 0;
1653 if (mp->ma_used == 0)
1654 /* Since the target dict is empty, PyDict_GetItem()
1655 * always returns NULL. Setting override to 1
1656 * skips the unnecessary test.
1657 */
1658 override = 1;
1659 /* Do one big resize at the start, rather than
1660 * incrementally resizing as we insert new items. Expect
1661 * that there will be no (or few) overlapping keys.
1662 */
1663 if ((mp->ma_fill + other->ma_used)*3 >= (mp->ma_mask+1)*2) {
1664 if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0)
1665 return -1;
1666 }
1667 for (i = 0; i <= other->ma_mask; i++) {
1668 entry = &other->ma_table[i];
1669 if (entry->me_value != NULL &&
1670 (override ||
1671 PyDict_GetItem(a, entry->me_key) == NULL)) {
1672 Py_INCREF(entry->me_key);
1673 Py_INCREF(entry->me_value);
1674 if (insertdict(mp, entry->me_key,
1675 (long)entry->me_hash,
1676 entry->me_value) != 0)
1677 return -1;
1678 }
1679 }
1680 }
1681 else {
1682 /* Do it the generic, slower way */
1683 PyObject *keys = PyMapping_Keys(b);
1684 PyObject *iter;
1685 PyObject *key, *value;
1686 int status;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001687
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001688 if (keys == NULL)
1689 /* Docstring says this is equivalent to E.keys() so
1690 * if E doesn't have a .keys() method we want
1691 * AttributeError to percolate up. Might as well
1692 * do the same for any other error.
1693 */
1694 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001695
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001696 iter = PyObject_GetIter(keys);
1697 Py_DECREF(keys);
1698 if (iter == NULL)
1699 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001700
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001701 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
1702 if (!override && PyDict_GetItem(a, key) != NULL) {
1703 Py_DECREF(key);
1704 continue;
1705 }
1706 value = PyObject_GetItem(b, key);
1707 if (value == NULL) {
1708 Py_DECREF(iter);
1709 Py_DECREF(key);
1710 return -1;
1711 }
1712 status = PyDict_SetItem(a, key, value);
1713 Py_DECREF(key);
1714 Py_DECREF(value);
1715 if (status < 0) {
1716 Py_DECREF(iter);
1717 return -1;
1718 }
1719 }
1720 Py_DECREF(iter);
1721 if (PyErr_Occurred())
1722 /* Iterator completed, via error */
1723 return -1;
1724 }
1725 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001726}
1727
1728static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00001729dict_copy(register PyDictObject *mp)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001730{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001731 return PyDict_Copy((PyObject*)mp);
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001732}
1733
1734PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001735PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001736{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001737 PyObject *copy;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001738
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001739 if (o == NULL || !PyDict_Check(o)) {
1740 PyErr_BadInternalCall();
1741 return NULL;
1742 }
1743 copy = PyDict_New();
1744 if (copy == NULL)
1745 return NULL;
1746 if (PyDict_Merge(copy, o, 1) == 0)
1747 return copy;
1748 Py_DECREF(copy);
1749 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001750}
1751
Martin v. Löwis18e16552006-02-15 17:27:45 +00001752Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00001753PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00001754{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001755 if (mp == NULL || !PyDict_Check(mp)) {
1756 PyErr_BadInternalCall();
1757 return -1;
1758 }
1759 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00001760}
1761
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001762PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001763PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001764{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001765 if (mp == NULL || !PyDict_Check(mp)) {
1766 PyErr_BadInternalCall();
1767 return NULL;
1768 }
1769 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001770}
1771
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001772PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001773PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001774{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001775 if (mp == NULL || !PyDict_Check(mp)) {
1776 PyErr_BadInternalCall();
1777 return NULL;
1778 }
1779 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00001780}
1781
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001782PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001783PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001784{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001785 if (mp == NULL || !PyDict_Check(mp)) {
1786 PyErr_BadInternalCall();
1787 return NULL;
1788 }
1789 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00001790}
1791
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001792/* Subroutine which returns the smallest key in a for which b's value
1793 is different or absent. The value is returned too, through the
Tim Peters95bf9392001-05-10 08:32:44 +00001794 pval argument. Both are NULL if no key in a is found for which b's status
1795 differs. The refcounts on (and only on) non-NULL *pval and function return
1796 values must be decremented by the caller (characterize() increments them
1797 to ensure that mutating comparison and PyDict_GetItem calls can't delete
1798 them before the caller is done looking at them). */
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001799
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001800static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00001801characterize(PyDictObject *a, PyDictObject *b, PyObject **pval)
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001802{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001803 PyObject *akey = NULL; /* smallest key in a s.t. a[akey] != b[akey] */
1804 PyObject *aval = NULL; /* a[akey] */
1805 Py_ssize_t i;
1806 int cmp;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001807
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001808 for (i = 0; i <= a->ma_mask; i++) {
1809 PyObject *thiskey, *thisaval, *thisbval;
1810 if (a->ma_table[i].me_value == NULL)
1811 continue;
1812 thiskey = a->ma_table[i].me_key;
1813 Py_INCREF(thiskey); /* keep alive across compares */
1814 if (akey != NULL) {
1815 cmp = PyObject_RichCompareBool(akey, thiskey, Py_LT);
1816 if (cmp < 0) {
1817 Py_DECREF(thiskey);
1818 goto Fail;
1819 }
1820 if (cmp > 0 ||
1821 i > a->ma_mask ||
1822 a->ma_table[i].me_value == NULL)
1823 {
1824 /* Not the *smallest* a key; or maybe it is
1825 * but the compare shrunk the dict so we can't
1826 * find its associated value anymore; or
1827 * maybe it is but the compare deleted the
1828 * a[thiskey] entry.
1829 */
1830 Py_DECREF(thiskey);
1831 continue;
1832 }
1833 }
Tim Peters95bf9392001-05-10 08:32:44 +00001834
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001835 /* Compare a[thiskey] to b[thiskey]; cmp <- true iff equal. */
1836 thisaval = a->ma_table[i].me_value;
1837 assert(thisaval);
1838 Py_INCREF(thisaval); /* keep alive */
1839 thisbval = PyDict_GetItem((PyObject *)b, thiskey);
1840 if (thisbval == NULL)
1841 cmp = 0;
1842 else {
1843 /* both dicts have thiskey: same values? */
1844 cmp = PyObject_RichCompareBool(
1845 thisaval, thisbval, Py_EQ);
1846 if (cmp < 0) {
1847 Py_DECREF(thiskey);
1848 Py_DECREF(thisaval);
1849 goto Fail;
1850 }
1851 }
1852 if (cmp == 0) {
1853 /* New winner. */
1854 Py_XDECREF(akey);
1855 Py_XDECREF(aval);
1856 akey = thiskey;
1857 aval = thisaval;
1858 }
1859 else {
1860 Py_DECREF(thiskey);
1861 Py_DECREF(thisaval);
1862 }
1863 }
1864 *pval = aval;
1865 return akey;
Tim Peters95bf9392001-05-10 08:32:44 +00001866
1867Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001868 Py_XDECREF(akey);
1869 Py_XDECREF(aval);
1870 *pval = NULL;
1871 return NULL;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001872}
1873
1874static int
Brett Cannon77ae87c2007-10-10 00:07:50 +00001875dict_compare(PyDictObject *a, PyDictObject *b)
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001876{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001877 PyObject *adiff, *bdiff, *aval, *bval;
1878 int res;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001879
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001880 /* Compare lengths first */
1881 if (a->ma_used < b->ma_used)
1882 return -1; /* a is shorter */
1883 else if (a->ma_used > b->ma_used)
1884 return 1; /* b is shorter */
Tim Peters95bf9392001-05-10 08:32:44 +00001885
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001886 /* Same length -- check all keys */
1887 bdiff = bval = NULL;
1888 adiff = characterize(a, b, &aval);
1889 if (adiff == NULL) {
1890 assert(!aval);
1891 /* Either an error, or a is a subset with the same length so
1892 * must be equal.
1893 */
1894 res = PyErr_Occurred() ? -1 : 0;
1895 goto Finished;
1896 }
1897 bdiff = characterize(b, a, &bval);
1898 if (bdiff == NULL && PyErr_Occurred()) {
1899 assert(!bval);
1900 res = -1;
1901 goto Finished;
1902 }
1903 res = 0;
1904 if (bdiff) {
1905 /* bdiff == NULL "should be" impossible now, but perhaps
1906 * the last comparison done by the characterize() on a had
1907 * the side effect of making the dicts equal!
1908 */
1909 res = PyObject_Compare(adiff, bdiff);
1910 }
1911 if (res == 0 && bval != NULL)
1912 res = PyObject_Compare(aval, bval);
Tim Peters95bf9392001-05-10 08:32:44 +00001913
1914Finished:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001915 Py_XDECREF(adiff);
1916 Py_XDECREF(bdiff);
1917 Py_XDECREF(aval);
1918 Py_XDECREF(bval);
1919 return res;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001920}
1921
Tim Peterse63415e2001-05-08 04:38:29 +00001922/* Return 1 if dicts equal, 0 if not, -1 if error.
1923 * Gets out as soon as any difference is detected.
1924 * Uses only Py_EQ comparison.
1925 */
1926static int
Brett Cannon77ae87c2007-10-10 00:07:50 +00001927dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00001928{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001929 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00001930
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001931 if (a->ma_used != b->ma_used)
1932 /* can't be equal if # of entries differ */
1933 return 0;
Tim Peterseb28ef22001-06-02 05:27:19 +00001934
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001935 /* Same # of entries -- check all of 'em. Exit early on any diff. */
1936 for (i = 0; i <= a->ma_mask; i++) {
1937 PyObject *aval = a->ma_table[i].me_value;
1938 if (aval != NULL) {
1939 int cmp;
1940 PyObject *bval;
1941 PyObject *key = a->ma_table[i].me_key;
1942 /* temporarily bump aval's refcount to ensure it stays
1943 alive until we're done with it */
1944 Py_INCREF(aval);
1945 /* ditto for key */
1946 Py_INCREF(key);
1947 bval = PyDict_GetItem((PyObject *)b, key);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001948 if (bval == NULL) {
Serhiy Storchakae6a0b592017-05-20 20:05:27 +03001949 Py_DECREF(key);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001950 Py_DECREF(aval);
1951 return 0;
1952 }
1953 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
Serhiy Storchakae6a0b592017-05-20 20:05:27 +03001954 Py_DECREF(key);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001955 Py_DECREF(aval);
1956 if (cmp <= 0) /* error or not equal */
1957 return cmp;
1958 }
1959 }
1960 return 1;
Tim Peterse63415e2001-05-08 04:38:29 +00001961 }
1962
1963static PyObject *
1964dict_richcompare(PyObject *v, PyObject *w, int op)
1965{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001966 int cmp;
1967 PyObject *res;
Tim Peterse63415e2001-05-08 04:38:29 +00001968
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001969 if (!PyDict_Check(v) || !PyDict_Check(w)) {
1970 res = Py_NotImplemented;
1971 }
1972 else if (op == Py_EQ || op == Py_NE) {
1973 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
1974 if (cmp < 0)
1975 return NULL;
1976 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
1977 }
1978 else {
1979 /* Py3K warning if comparison isn't == or != */
1980 if (PyErr_WarnPy3k("dict inequality comparisons not supported "
1981 "in 3.x", 1) < 0) {
1982 return NULL;
1983 }
1984 res = Py_NotImplemented;
1985 }
1986 Py_INCREF(res);
1987 return res;
Tim Peterse63415e2001-05-08 04:38:29 +00001988 }
1989
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001990static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00001991dict_contains(register PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001992{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001993 long hash;
1994 PyDictEntry *ep;
Tim Petersd770ebd2006-06-01 15:50:44 +00001995
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001996 if (!PyString_CheckExact(key) ||
1997 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
1998 hash = PyObject_Hash(key);
1999 if (hash == -1)
2000 return NULL;
2001 }
2002 ep = (mp->ma_lookup)(mp, key, hash);
2003 if (ep == NULL)
2004 return NULL;
2005 return PyBool_FromLong(ep->me_value != NULL);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002006}
2007
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002008static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00002009dict_has_key(register PyDictObject *mp, PyObject *key)
Neal Norwitz8b2bfbc2007-05-23 06:35:32 +00002010{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002011 if (PyErr_WarnPy3k("dict.has_key() not supported in 3.x; "
2012 "use the in operator", 1) < 0)
2013 return NULL;
2014 return dict_contains(mp, key);
Neal Norwitz8b2bfbc2007-05-23 06:35:32 +00002015}
2016
2017static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00002018dict_get(register PyDictObject *mp, PyObject *args)
Barry Warsawc38c5da1997-10-06 17:49:20 +00002019{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002020 PyObject *key;
2021 PyObject *failobj = Py_None;
2022 PyObject *val = NULL;
2023 long hash;
2024 PyDictEntry *ep;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002025
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002026 if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
2027 return NULL;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002028
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002029 if (!PyString_CheckExact(key) ||
2030 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
2031 hash = PyObject_Hash(key);
2032 if (hash == -1)
2033 return NULL;
2034 }
2035 ep = (mp->ma_lookup)(mp, key, hash);
2036 if (ep == NULL)
2037 return NULL;
2038 val = ep->me_value;
2039 if (val == NULL)
2040 val = failobj;
2041 Py_INCREF(val);
2042 return val;
Barry Warsawc38c5da1997-10-06 17:49:20 +00002043}
2044
2045
2046static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00002047dict_setdefault(register PyDictObject *mp, PyObject *args)
Guido van Rossum164452c2000-08-08 16:12:54 +00002048{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002049 PyObject *key;
2050 PyObject *failobj = Py_None;
2051 PyObject *val = NULL;
2052 long hash;
2053 PyDictEntry *ep;
Guido van Rossum164452c2000-08-08 16:12:54 +00002054
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002055 if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &failobj))
2056 return NULL;
Guido van Rossum164452c2000-08-08 16:12:54 +00002057
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002058 if (!PyString_CheckExact(key) ||
2059 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
2060 hash = PyObject_Hash(key);
2061 if (hash == -1)
2062 return NULL;
2063 }
2064 ep = (mp->ma_lookup)(mp, key, hash);
2065 if (ep == NULL)
2066 return NULL;
2067 val = ep->me_value;
2068 if (val == NULL) {
Antoine Pitrou6a1cd1b2012-02-27 00:45:12 +01002069 if (dict_set_item_by_hash_or_entry((PyObject*)mp, key, hash, ep,
2070 failobj) == 0)
2071 val = failobj;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002072 }
2073 Py_XINCREF(val);
2074 return val;
Guido van Rossum164452c2000-08-08 16:12:54 +00002075}
2076
2077
2078static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00002079dict_clear(register PyDictObject *mp)
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002080{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002081 PyDict_Clear((PyObject *)mp);
2082 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00002083}
2084
Guido van Rossumba6ab842000-12-12 22:02:18 +00002085static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00002086dict_pop(PyDictObject *mp, PyObject *args)
Guido van Rossume027d982002-04-12 15:11:59 +00002087{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002088 long hash;
2089 PyDictEntry *ep;
2090 PyObject *old_value, *old_key;
2091 PyObject *key, *deflt = NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00002092
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002093 if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
2094 return NULL;
2095 if (mp->ma_used == 0) {
2096 if (deflt) {
2097 Py_INCREF(deflt);
2098 return deflt;
2099 }
Raymond Hettinger2ad17e12010-10-30 08:17:46 +00002100 set_key_error(key);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002101 return NULL;
2102 }
2103 if (!PyString_CheckExact(key) ||
2104 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
2105 hash = PyObject_Hash(key);
2106 if (hash == -1)
2107 return NULL;
2108 }
2109 ep = (mp->ma_lookup)(mp, key, hash);
2110 if (ep == NULL)
2111 return NULL;
2112 if (ep->me_value == NULL) {
2113 if (deflt) {
2114 Py_INCREF(deflt);
2115 return deflt;
2116 }
2117 set_key_error(key);
2118 return NULL;
2119 }
2120 old_key = ep->me_key;
2121 Py_INCREF(dummy);
2122 ep->me_key = dummy;
2123 old_value = ep->me_value;
2124 ep->me_value = NULL;
2125 mp->ma_used--;
2126 Py_DECREF(old_key);
2127 return old_value;
Guido van Rossume027d982002-04-12 15:11:59 +00002128}
2129
2130static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00002131dict_popitem(PyDictObject *mp)
Guido van Rossumba6ab842000-12-12 22:02:18 +00002132{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002133 Py_ssize_t i = 0;
2134 PyDictEntry *ep;
2135 PyObject *res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002136
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002137 /* Allocate the result tuple before checking the size. Believe it
2138 * or not, this allocation could trigger a garbage collection which
2139 * could empty the dict, so if we checked the size first and that
2140 * happened, the result would be an infinite loop (searching for an
2141 * entry that no longer exists). Note that the usual popitem()
2142 * idiom is "while d: k, v = d.popitem()". so needing to throw the
2143 * tuple away if the dict *is* empty isn't a significant
2144 * inefficiency -- possible, but unlikely in practice.
2145 */
2146 res = PyTuple_New(2);
2147 if (res == NULL)
2148 return NULL;
2149 if (mp->ma_used == 0) {
2150 Py_DECREF(res);
2151 PyErr_SetString(PyExc_KeyError,
2152 "popitem(): dictionary is empty");
2153 return NULL;
2154 }
2155 /* Set ep to "the first" dict entry with a value. We abuse the hash
2156 * field of slot 0 to hold a search finger:
2157 * If slot 0 has a value, use slot 0.
2158 * Else slot 0 is being used to hold a search finger,
2159 * and we use its hash value as the first index to look.
2160 */
2161 ep = &mp->ma_table[0];
2162 if (ep->me_value == NULL) {
2163 i = ep->me_hash;
2164 /* The hash field may be a real hash value, or it may be a
2165 * legit search finger, or it may be a once-legit search
2166 * finger that's out of bounds now because it wrapped around
2167 * or the table shrunk -- simply make sure it's in bounds now.
2168 */
2169 if (i > mp->ma_mask || i < 1)
2170 i = 1; /* skip slot 0 */
2171 while ((ep = &mp->ma_table[i])->me_value == NULL) {
2172 i++;
2173 if (i > mp->ma_mask)
2174 i = 1;
2175 }
2176 }
2177 PyTuple_SET_ITEM(res, 0, ep->me_key);
2178 PyTuple_SET_ITEM(res, 1, ep->me_value);
2179 Py_INCREF(dummy);
2180 ep->me_key = dummy;
2181 ep->me_value = NULL;
2182 mp->ma_used--;
2183 assert(mp->ma_table[0].me_value == NULL);
2184 mp->ma_table[0].me_hash = i + 1; /* next place to start */
2185 return res;
Guido van Rossumba6ab842000-12-12 22:02:18 +00002186}
2187
Jeremy Hylton8caad492000-06-23 14:18:11 +00002188static int
2189dict_traverse(PyObject *op, visitproc visit, void *arg)
2190{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002191 Py_ssize_t i = 0;
2192 PyObject *pk;
2193 PyObject *pv;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002194
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002195 while (PyDict_Next(op, &i, &pk, &pv)) {
2196 Py_VISIT(pk);
2197 Py_VISIT(pv);
2198 }
2199 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002200}
2201
2202static int
2203dict_tp_clear(PyObject *op)
2204{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002205 PyDict_Clear(op);
2206 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002207}
2208
Tim Petersf7f88b12000-12-13 23:18:45 +00002209
Raymond Hettinger019a1482004-03-18 02:41:19 +00002210extern PyTypeObject PyDictIterKey_Type; /* Forward */
2211extern PyTypeObject PyDictIterValue_Type; /* Forward */
2212extern PyTypeObject PyDictIterItem_Type; /* Forward */
Brett Cannon77ae87c2007-10-10 00:07:50 +00002213static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00002214
2215static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00002216dict_iterkeys(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00002217{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002218 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00002219}
2220
2221static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00002222dict_itervalues(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00002223{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002224 return dictiter_new(dict, &PyDictIterValue_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00002225}
2226
2227static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00002228dict_iteritems(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00002229{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002230 return dictiter_new(dict, &PyDictIterItem_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00002231}
2232
Robert Schuppenies51df0642008-06-01 16:16:17 +00002233static PyObject *
2234dict_sizeof(PyDictObject *mp)
2235{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002236 Py_ssize_t res;
Robert Schuppenies51df0642008-06-01 16:16:17 +00002237
Serhiy Storchakac06a6d02015-12-19 20:07:48 +02002238 res = _PyObject_SIZE(Py_TYPE(mp));
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002239 if (mp->ma_table != mp->ma_smalltable)
2240 res = res + (mp->ma_mask + 1) * sizeof(PyDictEntry);
2241 return PyInt_FromSsize_t(res);
Robert Schuppenies51df0642008-06-01 16:16:17 +00002242}
Guido van Rossum09e563a2001-05-01 12:10:21 +00002243
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002244PyDoc_STRVAR(has_key__doc__,
Raymond Hettinger574aa322003-09-01 22:12:08 +00002245"D.has_key(k) -> True if D has a key k, else False");
Tim Petersf7f88b12000-12-13 23:18:45 +00002246
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002247PyDoc_STRVAR(contains__doc__,
2248"D.__contains__(k) -> True if D has a key k, else False");
2249
2250PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
2251
Robert Schuppenies51df0642008-06-01 16:16:17 +00002252PyDoc_STRVAR(sizeof__doc__,
Georg Brandl7a6de8b2008-06-01 16:42:16 +00002253"D.__sizeof__() -> size of D in memory, in bytes");
Robert Schuppenies51df0642008-06-01 16:16:17 +00002254
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002255PyDoc_STRVAR(get__doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00002256"D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002257
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002258PyDoc_STRVAR(setdefault_doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00002259"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 +00002260
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002261PyDoc_STRVAR(pop__doc__,
Andrew M. Kuchlinga4127172008-10-04 21:51:59 +00002262"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00002263If key is not found, d is returned if given, otherwise KeyError is raised");
Guido van Rossume027d982002-04-12 15:11:59 +00002264
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002265PyDoc_STRVAR(popitem__doc__,
Tim Petersf7f88b12000-12-13 23:18:45 +00002266"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
Andrew M. Kuchlinga4127172008-10-04 21:51:59 +000022672-tuple; but raise KeyError if D is empty.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002268
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002269PyDoc_STRVAR(keys__doc__,
2270"D.keys() -> list of D's keys");
Tim Petersf7f88b12000-12-13 23:18:45 +00002271
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002272PyDoc_STRVAR(items__doc__,
2273"D.items() -> list of D's (key, value) pairs, as 2-tuples");
Tim Petersf7f88b12000-12-13 23:18:45 +00002274
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002275PyDoc_STRVAR(values__doc__,
2276"D.values() -> list of D's values");
Tim Petersf7f88b12000-12-13 23:18:45 +00002277
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002278PyDoc_STRVAR(update__doc__,
Georg Brandl6f14c332011-12-18 19:30:55 +01002279"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n"
2280"If E present and has a .keys() method, does: for k in E: D[k] = E[k]\n\
2281If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v\n\
Andrew M. Kuchlinga4127172008-10-04 21:51:59 +00002282In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00002283
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002284PyDoc_STRVAR(fromkeys__doc__,
2285"dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.\n\
2286v defaults to None.");
2287
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002288PyDoc_STRVAR(clear__doc__,
2289"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00002290
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002291PyDoc_STRVAR(copy__doc__,
2292"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00002293
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002294PyDoc_STRVAR(iterkeys__doc__,
2295"D.iterkeys() -> an iterator over the keys of D");
Guido van Rossum09e563a2001-05-01 12:10:21 +00002296
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002297PyDoc_STRVAR(itervalues__doc__,
2298"D.itervalues() -> an iterator over the values of D");
Guido van Rossum09e563a2001-05-01 12:10:21 +00002299
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002300PyDoc_STRVAR(iteritems__doc__,
2301"D.iteritems() -> an iterator over the (key, value) items of D");
Guido van Rossum09e563a2001-05-01 12:10:21 +00002302
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002303/* Forward */
2304static PyObject *dictkeys_new(PyObject *);
2305static PyObject *dictitems_new(PyObject *);
2306static PyObject *dictvalues_new(PyObject *);
2307
2308PyDoc_STRVAR(viewkeys__doc__,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002309 "D.viewkeys() -> a set-like object providing a view on D's keys");
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002310PyDoc_STRVAR(viewitems__doc__,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002311 "D.viewitems() -> a set-like object providing a view on D's items");
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002312PyDoc_STRVAR(viewvalues__doc__,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002313 "D.viewvalues() -> an object providing a view on D's values");
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002314
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002315static PyMethodDef mapp_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002316 {"__contains__",(PyCFunction)dict_contains, METH_O | METH_COEXIST,
2317 contains__doc__},
2318 {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
2319 getitem__doc__},
2320 {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS,
2321 sizeof__doc__},
2322 {"has_key", (PyCFunction)dict_has_key, METH_O,
2323 has_key__doc__},
2324 {"get", (PyCFunction)dict_get, METH_VARARGS,
2325 get__doc__},
2326 {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS,
2327 setdefault_doc__},
2328 {"pop", (PyCFunction)dict_pop, METH_VARARGS,
2329 pop__doc__},
2330 {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
2331 popitem__doc__},
2332 {"keys", (PyCFunction)dict_keys, METH_NOARGS,
2333 keys__doc__},
2334 {"items", (PyCFunction)dict_items, METH_NOARGS,
2335 items__doc__},
2336 {"values", (PyCFunction)dict_values, METH_NOARGS,
2337 values__doc__},
2338 {"viewkeys", (PyCFunction)dictkeys_new, METH_NOARGS,
2339 viewkeys__doc__},
2340 {"viewitems", (PyCFunction)dictitems_new, METH_NOARGS,
2341 viewitems__doc__},
2342 {"viewvalues", (PyCFunction)dictvalues_new, METH_NOARGS,
2343 viewvalues__doc__},
2344 {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
2345 update__doc__},
2346 {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS,
2347 fromkeys__doc__},
2348 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
2349 clear__doc__},
2350 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
2351 copy__doc__},
2352 {"iterkeys", (PyCFunction)dict_iterkeys, METH_NOARGS,
2353 iterkeys__doc__},
2354 {"itervalues", (PyCFunction)dict_itervalues, METH_NOARGS,
2355 itervalues__doc__},
2356 {"iteritems", (PyCFunction)dict_iteritems, METH_NOARGS,
2357 iteritems__doc__},
2358 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002359};
2360
Tim Petersd770ebd2006-06-01 15:50:44 +00002361/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00002362int
2363PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002364{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002365 long hash;
2366 PyDictObject *mp = (PyDictObject *)op;
2367 PyDictEntry *ep;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002368
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002369 if (!PyString_CheckExact(key) ||
2370 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
2371 hash = PyObject_Hash(key);
2372 if (hash == -1)
2373 return -1;
2374 }
2375 ep = (mp->ma_lookup)(mp, key, hash);
2376 return ep == NULL ? -1 : (ep->me_value != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002377}
2378
Raymond Hettingerd6fc72a2007-02-19 02:03:19 +00002379/* Internal version of PyDict_Contains used when the hash value is already known */
2380int
2381_PyDict_Contains(PyObject *op, PyObject *key, long hash)
2382{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002383 PyDictObject *mp = (PyDictObject *)op;
2384 PyDictEntry *ep;
Raymond Hettingerd6fc72a2007-02-19 02:03:19 +00002385
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002386 ep = (mp->ma_lookup)(mp, key, hash);
2387 return ep == NULL ? -1 : (ep->me_value != NULL);
Raymond Hettingerd6fc72a2007-02-19 02:03:19 +00002388}
2389
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002390/* Hack to implement "key in dict" */
2391static PySequenceMethods dict_as_sequence = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002392 0, /* sq_length */
2393 0, /* sq_concat */
2394 0, /* sq_repeat */
2395 0, /* sq_item */
2396 0, /* sq_slice */
2397 0, /* sq_ass_item */
2398 0, /* sq_ass_slice */
2399 PyDict_Contains, /* sq_contains */
2400 0, /* sq_inplace_concat */
2401 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002402};
2403
Guido van Rossum09e563a2001-05-01 12:10:21 +00002404static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002405dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2406{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002407 PyObject *self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002408
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002409 assert(type != NULL && type->tp_alloc != NULL);
2410 self = type->tp_alloc(type, 0);
2411 if (self != NULL) {
2412 PyDictObject *d = (PyDictObject *)self;
2413 /* It's guaranteed that tp->alloc zeroed out the struct. */
2414 assert(d->ma_table == NULL && d->ma_fill == 0 && d->ma_used == 0);
2415 INIT_NONZERO_DICT_SLOTS(d);
2416 d->ma_lookup = lookdict_string;
Ezio Melottic2077b02011-03-16 12:34:31 +02002417 /* The object has been implicitly tracked by tp_alloc */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002418 if (type == &PyDict_Type)
2419 _PyObject_GC_UNTRACK(d);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002420#ifdef SHOW_CONVERSION_COUNTS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002421 ++created;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002422#endif
Antoine Pitrouf8387af2009-03-23 18:41:45 +00002423#ifdef SHOW_TRACK_COUNT
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002424 if (_PyObject_GC_IS_TRACKED(d))
2425 count_tracked++;
2426 else
2427 count_untracked++;
Antoine Pitrouf8387af2009-03-23 18:41:45 +00002428#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002429 }
2430 return self;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002431}
2432
Tim Peters25786c02001-09-02 08:22:48 +00002433static int
2434dict_init(PyObject *self, PyObject *args, PyObject *kwds)
2435{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002436 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00002437}
2438
Tim Peters6d6c1a32001-08-02 04:15:00 +00002439static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00002440dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00002441{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002442 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00002443}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002444
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002445PyDoc_STRVAR(dictionary_doc,
Ezio Melottifb501122010-02-28 23:59:00 +00002446"dict() -> new empty dictionary\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00002447"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Ezio Melottifb501122010-02-28 23:59:00 +00002448" (key, value) pairs\n"
Georg Brandlbca11692010-02-28 18:19:17 +00002449"dict(iterable) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00002450" d = {}\n"
Georg Brandlbca11692010-02-28 18:19:17 +00002451" for k, v in iterable:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00002452" d[k] = v\n"
2453"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
2454" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00002455
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002456PyTypeObject PyDict_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002457 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2458 "dict",
2459 sizeof(PyDictObject),
2460 0,
2461 (destructor)dict_dealloc, /* tp_dealloc */
2462 (printfunc)dict_print, /* tp_print */
2463 0, /* tp_getattr */
2464 0, /* tp_setattr */
2465 (cmpfunc)dict_compare, /* tp_compare */
2466 (reprfunc)dict_repr, /* tp_repr */
2467 0, /* tp_as_number */
2468 &dict_as_sequence, /* tp_as_sequence */
2469 &dict_as_mapping, /* tp_as_mapping */
2470 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
2471 0, /* tp_call */
2472 0, /* tp_str */
2473 PyObject_GenericGetAttr, /* tp_getattro */
2474 0, /* tp_setattro */
2475 0, /* tp_as_buffer */
2476 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2477 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
2478 dictionary_doc, /* tp_doc */
2479 dict_traverse, /* tp_traverse */
2480 dict_tp_clear, /* tp_clear */
2481 dict_richcompare, /* tp_richcompare */
2482 0, /* tp_weaklistoffset */
2483 (getiterfunc)dict_iter, /* tp_iter */
2484 0, /* tp_iternext */
2485 mapp_methods, /* tp_methods */
2486 0, /* tp_members */
2487 0, /* tp_getset */
2488 0, /* tp_base */
2489 0, /* tp_dict */
2490 0, /* tp_descr_get */
2491 0, /* tp_descr_set */
2492 0, /* tp_dictoffset */
2493 dict_init, /* tp_init */
2494 PyType_GenericAlloc, /* tp_alloc */
2495 dict_new, /* tp_new */
2496 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002497};
2498
Guido van Rossum3cca2451997-05-16 14:23:33 +00002499/* For backward compatibility with old dictionary interface */
2500
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002501PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00002502PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002503{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002504 PyObject *kv, *rv;
2505 kv = PyString_FromString(key);
2506 if (kv == NULL)
2507 return NULL;
2508 rv = PyDict_GetItem(v, kv);
2509 Py_DECREF(kv);
2510 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002511}
2512
2513int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00002514PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002515{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002516 PyObject *kv;
2517 int err;
2518 kv = PyString_FromString(key);
2519 if (kv == NULL)
2520 return -1;
2521 PyString_InternInPlace(&kv); /* XXX Should we really? */
2522 err = PyDict_SetItem(v, kv, item);
2523 Py_DECREF(kv);
2524 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002525}
2526
2527int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00002528PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002529{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002530 PyObject *kv;
2531 int err;
2532 kv = PyString_FromString(key);
2533 if (kv == NULL)
2534 return -1;
2535 err = PyDict_DelItem(v, kv);
2536 Py_DECREF(kv);
2537 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002538}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002539
Raymond Hettinger019a1482004-03-18 02:41:19 +00002540/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002541
2542typedef struct {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002543 PyObject_HEAD
2544 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
2545 Py_ssize_t di_used;
2546 Py_ssize_t di_pos;
2547 PyObject* di_result; /* reusable result tuple for iteritems */
2548 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002549} dictiterobject;
2550
2551static PyObject *
Brett Cannon77ae87c2007-10-10 00:07:50 +00002552dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002553{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002554 dictiterobject *di;
2555 di = PyObject_GC_New(dictiterobject, itertype);
2556 if (di == NULL)
2557 return NULL;
2558 Py_INCREF(dict);
2559 di->di_dict = dict;
2560 di->di_used = dict->ma_used;
2561 di->di_pos = 0;
2562 di->len = dict->ma_used;
2563 if (itertype == &PyDictIterItem_Type) {
2564 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
2565 if (di->di_result == NULL) {
2566 Py_DECREF(di);
2567 return NULL;
2568 }
2569 }
2570 else
2571 di->di_result = NULL;
2572 _PyObject_GC_TRACK(di);
2573 return (PyObject *)di;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002574}
2575
2576static void
2577dictiter_dealloc(dictiterobject *di)
2578{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002579 Py_XDECREF(di->di_dict);
2580 Py_XDECREF(di->di_result);
2581 PyObject_GC_Del(di);
Antoine Pitrouaa687902009-01-01 14:11:22 +00002582}
2583
2584static int
2585dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
2586{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002587 Py_VISIT(di->di_dict);
2588 Py_VISIT(di->di_result);
2589 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002590}
2591
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002592static PyObject *
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002593dictiter_len(dictiterobject *di)
2594{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002595 Py_ssize_t len = 0;
2596 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
2597 len = di->len;
2598 return PyInt_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002599}
2600
Armin Rigof5b3e362006-02-11 21:32:43 +00002601PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002602
2603static PyMethodDef dictiter_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002604 {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS, length_hint_doc},
2605 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002606};
2607
Raymond Hettinger019a1482004-03-18 02:41:19 +00002608static PyObject *dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00002609{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002610 PyObject *key;
2611 register Py_ssize_t i, mask;
2612 register PyDictEntry *ep;
2613 PyDictObject *d = di->di_dict;
Guido van Rossum213c7a62001-04-23 14:08:49 +00002614
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002615 if (d == NULL)
2616 return NULL;
2617 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00002618
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002619 if (di->di_used != d->ma_used) {
2620 PyErr_SetString(PyExc_RuntimeError,
2621 "dictionary changed size during iteration");
2622 di->di_used = -1; /* Make this state sticky */
2623 return NULL;
2624 }
Guido van Rossum2147df72002-07-16 20:30:22 +00002625
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002626 i = di->di_pos;
2627 if (i < 0)
2628 goto fail;
2629 ep = d->ma_table;
2630 mask = d->ma_mask;
2631 while (i <= mask && ep[i].me_value == NULL)
2632 i++;
2633 di->di_pos = i+1;
2634 if (i > mask)
2635 goto fail;
2636 di->len--;
2637 key = ep[i].me_key;
2638 Py_INCREF(key);
2639 return key;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002640
2641fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002642 di->di_dict = NULL;
Serhiy Storchaka14a7d632016-03-30 20:43:06 +03002643 Py_DECREF(d);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002644 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002645}
2646
Raymond Hettinger019a1482004-03-18 02:41:19 +00002647PyTypeObject PyDictIterKey_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002648 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2649 "dictionary-keyiterator", /* tp_name */
2650 sizeof(dictiterobject), /* tp_basicsize */
2651 0, /* tp_itemsize */
2652 /* methods */
2653 (destructor)dictiter_dealloc, /* tp_dealloc */
2654 0, /* tp_print */
2655 0, /* tp_getattr */
2656 0, /* tp_setattr */
2657 0, /* tp_compare */
2658 0, /* tp_repr */
2659 0, /* tp_as_number */
2660 0, /* tp_as_sequence */
2661 0, /* tp_as_mapping */
2662 0, /* tp_hash */
2663 0, /* tp_call */
2664 0, /* tp_str */
2665 PyObject_GenericGetAttr, /* tp_getattro */
2666 0, /* tp_setattro */
2667 0, /* tp_as_buffer */
2668 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2669 0, /* tp_doc */
2670 (traverseproc)dictiter_traverse, /* tp_traverse */
2671 0, /* tp_clear */
2672 0, /* tp_richcompare */
2673 0, /* tp_weaklistoffset */
2674 PyObject_SelfIter, /* tp_iter */
2675 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
2676 dictiter_methods, /* tp_methods */
2677 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00002678};
2679
2680static PyObject *dictiter_iternextvalue(dictiterobject *di)
2681{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002682 PyObject *value;
2683 register Py_ssize_t i, mask;
2684 register PyDictEntry *ep;
2685 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002686
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002687 if (d == NULL)
2688 return NULL;
2689 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00002690
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002691 if (di->di_used != d->ma_used) {
2692 PyErr_SetString(PyExc_RuntimeError,
2693 "dictionary changed size during iteration");
2694 di->di_used = -1; /* Make this state sticky */
2695 return NULL;
2696 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00002697
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002698 i = di->di_pos;
2699 mask = d->ma_mask;
2700 if (i < 0 || i > mask)
2701 goto fail;
2702 ep = d->ma_table;
2703 while ((value=ep[i].me_value) == NULL) {
2704 i++;
2705 if (i > mask)
2706 goto fail;
2707 }
2708 di->di_pos = i+1;
2709 di->len--;
2710 Py_INCREF(value);
2711 return value;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002712
2713fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002714 di->di_dict = NULL;
Serhiy Storchaka14a7d632016-03-30 20:43:06 +03002715 Py_DECREF(d);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002716 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002717}
2718
2719PyTypeObject PyDictIterValue_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002720 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2721 "dictionary-valueiterator", /* tp_name */
2722 sizeof(dictiterobject), /* tp_basicsize */
2723 0, /* tp_itemsize */
2724 /* methods */
2725 (destructor)dictiter_dealloc, /* tp_dealloc */
2726 0, /* tp_print */
2727 0, /* tp_getattr */
2728 0, /* tp_setattr */
2729 0, /* tp_compare */
2730 0, /* tp_repr */
2731 0, /* tp_as_number */
2732 0, /* tp_as_sequence */
2733 0, /* tp_as_mapping */
2734 0, /* tp_hash */
2735 0, /* tp_call */
2736 0, /* tp_str */
2737 PyObject_GenericGetAttr, /* tp_getattro */
2738 0, /* tp_setattro */
2739 0, /* tp_as_buffer */
2740 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2741 0, /* tp_doc */
2742 (traverseproc)dictiter_traverse, /* tp_traverse */
2743 0, /* tp_clear */
2744 0, /* tp_richcompare */
2745 0, /* tp_weaklistoffset */
2746 PyObject_SelfIter, /* tp_iter */
2747 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
2748 dictiter_methods, /* tp_methods */
2749 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00002750};
2751
2752static PyObject *dictiter_iternextitem(dictiterobject *di)
2753{
Serhiy Storchakae6a0b592017-05-20 20:05:27 +03002754 PyObject *key, *value, *result;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002755 register Py_ssize_t i, mask;
2756 register PyDictEntry *ep;
2757 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002758
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002759 if (d == NULL)
2760 return NULL;
2761 assert (PyDict_Check(d));
Raymond Hettinger019a1482004-03-18 02:41:19 +00002762
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002763 if (di->di_used != d->ma_used) {
2764 PyErr_SetString(PyExc_RuntimeError,
2765 "dictionary changed size during iteration");
2766 di->di_used = -1; /* Make this state sticky */
2767 return NULL;
2768 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00002769
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002770 i = di->di_pos;
2771 if (i < 0)
2772 goto fail;
2773 ep = d->ma_table;
2774 mask = d->ma_mask;
2775 while (i <= mask && ep[i].me_value == NULL)
2776 i++;
2777 di->di_pos = i+1;
2778 if (i > mask)
2779 goto fail;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002780
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002781 di->len--;
2782 key = ep[i].me_key;
2783 value = ep[i].me_value;
2784 Py_INCREF(key);
2785 Py_INCREF(value);
Serhiy Storchakae6a0b592017-05-20 20:05:27 +03002786 result = di->di_result;
2787 if (Py_REFCNT(result) == 1) {
2788 PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
2789 PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
2790 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
2791 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
2792 Py_INCREF(result);
2793 Py_DECREF(oldkey);
2794 Py_DECREF(oldvalue);
2795 } else {
2796 result = PyTuple_New(2);
2797 if (result == NULL)
2798 return NULL;
2799 PyTuple_SET_ITEM(result, 0, key); /* steals reference */
2800 PyTuple_SET_ITEM(result, 1, value); /* steals reference */
2801 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002802 return result;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002803
2804fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002805 di->di_dict = NULL;
Serhiy Storchaka14a7d632016-03-30 20:43:06 +03002806 Py_DECREF(d);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002807 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002808}
2809
2810PyTypeObject PyDictIterItem_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002811 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2812 "dictionary-itemiterator", /* tp_name */
2813 sizeof(dictiterobject), /* tp_basicsize */
2814 0, /* tp_itemsize */
2815 /* methods */
2816 (destructor)dictiter_dealloc, /* tp_dealloc */
2817 0, /* tp_print */
2818 0, /* tp_getattr */
2819 0, /* tp_setattr */
2820 0, /* tp_compare */
2821 0, /* tp_repr */
2822 0, /* tp_as_number */
2823 0, /* tp_as_sequence */
2824 0, /* tp_as_mapping */
2825 0, /* tp_hash */
2826 0, /* tp_call */
2827 0, /* tp_str */
2828 PyObject_GenericGetAttr, /* tp_getattro */
2829 0, /* tp_setattro */
2830 0, /* tp_as_buffer */
2831 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2832 0, /* tp_doc */
2833 (traverseproc)dictiter_traverse, /* tp_traverse */
2834 0, /* tp_clear */
2835 0, /* tp_richcompare */
2836 0, /* tp_weaklistoffset */
2837 PyObject_SelfIter, /* tp_iter */
2838 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
2839 dictiter_methods, /* tp_methods */
2840 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002841};
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002842
2843/***********************************************/
2844/* View objects for keys(), items(), values(). */
2845/***********************************************/
2846
2847/* The instance lay-out is the same for all three; but the type differs. */
2848
2849typedef struct {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002850 PyObject_HEAD
2851 PyDictObject *dv_dict;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002852} dictviewobject;
2853
2854
2855static void
2856dictview_dealloc(dictviewobject *dv)
2857{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002858 Py_XDECREF(dv->dv_dict);
2859 PyObject_GC_Del(dv);
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002860}
2861
2862static int
2863dictview_traverse(dictviewobject *dv, visitproc visit, void *arg)
2864{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002865 Py_VISIT(dv->dv_dict);
2866 return 0;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002867}
2868
2869static Py_ssize_t
2870dictview_len(dictviewobject *dv)
2871{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002872 Py_ssize_t len = 0;
2873 if (dv->dv_dict != NULL)
2874 len = dv->dv_dict->ma_used;
2875 return len;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002876}
2877
2878static PyObject *
2879dictview_new(PyObject *dict, PyTypeObject *type)
2880{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002881 dictviewobject *dv;
2882 if (dict == NULL) {
2883 PyErr_BadInternalCall();
2884 return NULL;
2885 }
2886 if (!PyDict_Check(dict)) {
2887 /* XXX Get rid of this restriction later */
2888 PyErr_Format(PyExc_TypeError,
2889 "%s() requires a dict argument, not '%s'",
2890 type->tp_name, dict->ob_type->tp_name);
2891 return NULL;
2892 }
2893 dv = PyObject_GC_New(dictviewobject, type);
2894 if (dv == NULL)
2895 return NULL;
2896 Py_INCREF(dict);
2897 dv->dv_dict = (PyDictObject *)dict;
2898 _PyObject_GC_TRACK(dv);
2899 return (PyObject *)dv;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002900}
2901
2902/* TODO(guido): The views objects are not complete:
2903
2904 * support more set operations
2905 * support arbitrary mappings?
2906 - either these should be static or exported in dictobject.h
2907 - if public then they should probably be in builtins
2908*/
2909
2910/* Return 1 if self is a subset of other, iterating over self;
2911 0 if not; -1 if an error occurred. */
2912static int
2913all_contained_in(PyObject *self, PyObject *other)
2914{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002915 PyObject *iter = PyObject_GetIter(self);
2916 int ok = 1;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002917
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002918 if (iter == NULL)
2919 return -1;
2920 for (;;) {
2921 PyObject *next = PyIter_Next(iter);
2922 if (next == NULL) {
2923 if (PyErr_Occurred())
2924 ok = -1;
2925 break;
2926 }
2927 ok = PySequence_Contains(other, next);
2928 Py_DECREF(next);
2929 if (ok <= 0)
2930 break;
2931 }
2932 Py_DECREF(iter);
2933 return ok;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002934}
2935
2936static PyObject *
2937dictview_richcompare(PyObject *self, PyObject *other, int op)
2938{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002939 Py_ssize_t len_self, len_other;
2940 int ok;
2941 PyObject *result;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002942
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002943 assert(self != NULL);
2944 assert(PyDictViewSet_Check(self));
2945 assert(other != NULL);
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002946
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002947 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other)) {
2948 Py_INCREF(Py_NotImplemented);
2949 return Py_NotImplemented;
2950 }
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002951
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002952 len_self = PyObject_Size(self);
2953 if (len_self < 0)
2954 return NULL;
2955 len_other = PyObject_Size(other);
2956 if (len_other < 0)
2957 return NULL;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002958
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002959 ok = 0;
2960 switch(op) {
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002961
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002962 case Py_NE:
2963 case Py_EQ:
2964 if (len_self == len_other)
2965 ok = all_contained_in(self, other);
2966 if (op == Py_NE && ok >= 0)
2967 ok = !ok;
2968 break;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002969
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002970 case Py_LT:
2971 if (len_self < len_other)
2972 ok = all_contained_in(self, other);
2973 break;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002974
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002975 case Py_LE:
2976 if (len_self <= len_other)
2977 ok = all_contained_in(self, other);
2978 break;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002979
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002980 case Py_GT:
2981 if (len_self > len_other)
2982 ok = all_contained_in(other, self);
2983 break;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002984
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002985 case Py_GE:
2986 if (len_self >= len_other)
2987 ok = all_contained_in(other, self);
2988 break;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002989
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002990 }
2991 if (ok < 0)
2992 return NULL;
2993 result = ok ? Py_True : Py_False;
2994 Py_INCREF(result);
2995 return result;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00002996}
2997
2998static PyObject *
2999dictview_repr(dictviewobject *dv)
3000{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003001 PyObject *seq;
3002 PyObject *seq_str;
3003 PyObject *result;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003004
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003005 seq = PySequence_List((PyObject *)dv);
3006 if (seq == NULL)
3007 return NULL;
3008
3009 seq_str = PyObject_Repr(seq);
Benjamin Petersonb91ef002013-05-19 19:38:12 -07003010 if (seq_str == NULL) {
3011 Py_DECREF(seq);
3012 return NULL;
3013 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003014 result = PyString_FromFormat("%s(%s)", Py_TYPE(dv)->tp_name,
3015 PyString_AS_STRING(seq_str));
3016 Py_DECREF(seq_str);
3017 Py_DECREF(seq);
3018 return result;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003019}
3020
3021/*** dict_keys ***/
3022
3023static PyObject *
3024dictkeys_iter(dictviewobject *dv)
3025{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003026 if (dv->dv_dict == NULL) {
3027 Py_RETURN_NONE;
3028 }
3029 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003030}
3031
3032static int
3033dictkeys_contains(dictviewobject *dv, PyObject *obj)
3034{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003035 if (dv->dv_dict == NULL)
3036 return 0;
3037 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003038}
3039
3040static PySequenceMethods dictkeys_as_sequence = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003041 (lenfunc)dictview_len, /* sq_length */
3042 0, /* sq_concat */
3043 0, /* sq_repeat */
3044 0, /* sq_item */
3045 0, /* sq_slice */
3046 0, /* sq_ass_item */
3047 0, /* sq_ass_slice */
3048 (objobjproc)dictkeys_contains, /* sq_contains */
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003049};
3050
3051static PyObject*
3052dictviews_sub(PyObject* self, PyObject *other)
3053{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003054 PyObject *result = PySet_New(self);
3055 PyObject *tmp;
3056 if (result == NULL)
3057 return NULL;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003058
Benjamin Peterson4ddb44a2016-03-03 22:05:36 -08003059
3060 tmp = PyObject_CallMethod(result, "difference_update", "(O)", other);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003061 if (tmp == NULL) {
3062 Py_DECREF(result);
3063 return NULL;
3064 }
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003065
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003066 Py_DECREF(tmp);
3067 return result;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003068}
3069
3070static PyObject*
3071dictviews_and(PyObject* self, PyObject *other)
3072{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003073 PyObject *result = PySet_New(self);
3074 PyObject *tmp;
3075 if (result == NULL)
3076 return NULL;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003077
Benjamin Peterson4ddb44a2016-03-03 22:05:36 -08003078 tmp = PyObject_CallMethod(result, "intersection_update", "(O)", other);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003079 if (tmp == NULL) {
3080 Py_DECREF(result);
3081 return NULL;
3082 }
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003083
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003084 Py_DECREF(tmp);
3085 return result;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003086}
3087
3088static PyObject*
3089dictviews_or(PyObject* self, PyObject *other)
3090{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003091 PyObject *result = PySet_New(self);
3092 PyObject *tmp;
3093 if (result == NULL)
3094 return NULL;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003095
Benjamin Peterson4ddb44a2016-03-03 22:05:36 -08003096 tmp = PyObject_CallMethod(result, "update", "(O)", other);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003097 if (tmp == NULL) {
3098 Py_DECREF(result);
3099 return NULL;
3100 }
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003101
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003102 Py_DECREF(tmp);
3103 return result;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003104}
3105
3106static PyObject*
3107dictviews_xor(PyObject* self, PyObject *other)
3108{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003109 PyObject *result = PySet_New(self);
3110 PyObject *tmp;
3111 if (result == NULL)
3112 return NULL;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003113
Benjamin Peterson4ddb44a2016-03-03 22:05:36 -08003114 tmp = PyObject_CallMethod(result, "symmetric_difference_update", "(O)", other);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003115 if (tmp == NULL) {
3116 Py_DECREF(result);
3117 return NULL;
3118 }
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003119
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003120 Py_DECREF(tmp);
3121 return result;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003122}
3123
3124static PyNumberMethods dictviews_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003125 0, /*nb_add*/
3126 (binaryfunc)dictviews_sub, /*nb_subtract*/
3127 0, /*nb_multiply*/
3128 0, /*nb_divide*/
3129 0, /*nb_remainder*/
3130 0, /*nb_divmod*/
3131 0, /*nb_power*/
3132 0, /*nb_negative*/
3133 0, /*nb_positive*/
3134 0, /*nb_absolute*/
3135 0, /*nb_nonzero*/
3136 0, /*nb_invert*/
3137 0, /*nb_lshift*/
3138 0, /*nb_rshift*/
3139 (binaryfunc)dictviews_and, /*nb_and*/
3140 (binaryfunc)dictviews_xor, /*nb_xor*/
3141 (binaryfunc)dictviews_or, /*nb_or*/
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003142};
3143
3144static PyMethodDef dictkeys_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003145 {NULL, NULL} /* sentinel */
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003146};
3147
3148PyTypeObject PyDictKeys_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003149 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3150 "dict_keys", /* tp_name */
3151 sizeof(dictviewobject), /* tp_basicsize */
3152 0, /* tp_itemsize */
3153 /* methods */
3154 (destructor)dictview_dealloc, /* tp_dealloc */
3155 0, /* tp_print */
3156 0, /* tp_getattr */
3157 0, /* tp_setattr */
3158 0, /* tp_reserved */
3159 (reprfunc)dictview_repr, /* tp_repr */
3160 &dictviews_as_number, /* tp_as_number */
3161 &dictkeys_as_sequence, /* tp_as_sequence */
3162 0, /* tp_as_mapping */
3163 0, /* tp_hash */
3164 0, /* tp_call */
3165 0, /* tp_str */
3166 PyObject_GenericGetAttr, /* tp_getattro */
3167 0, /* tp_setattro */
3168 0, /* tp_as_buffer */
3169 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3170 Py_TPFLAGS_CHECKTYPES, /* tp_flags */
3171 0, /* tp_doc */
3172 (traverseproc)dictview_traverse, /* tp_traverse */
3173 0, /* tp_clear */
3174 dictview_richcompare, /* tp_richcompare */
3175 0, /* tp_weaklistoffset */
3176 (getiterfunc)dictkeys_iter, /* tp_iter */
3177 0, /* tp_iternext */
3178 dictkeys_methods, /* tp_methods */
3179 0,
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003180};
3181
3182static PyObject *
3183dictkeys_new(PyObject *dict)
3184{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003185 return dictview_new(dict, &PyDictKeys_Type);
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003186}
3187
3188/*** dict_items ***/
3189
3190static PyObject *
3191dictitems_iter(dictviewobject *dv)
3192{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003193 if (dv->dv_dict == NULL) {
3194 Py_RETURN_NONE;
3195 }
3196 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003197}
3198
3199static int
3200dictitems_contains(dictviewobject *dv, PyObject *obj)
3201{
Serhiy Storchakae6a0b592017-05-20 20:05:27 +03003202 int result;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003203 PyObject *key, *value, *found;
3204 if (dv->dv_dict == NULL)
3205 return 0;
3206 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
3207 return 0;
3208 key = PyTuple_GET_ITEM(obj, 0);
3209 value = PyTuple_GET_ITEM(obj, 1);
3210 found = PyDict_GetItem((PyObject *)dv->dv_dict, key);
3211 if (found == NULL) {
3212 if (PyErr_Occurred())
3213 return -1;
3214 return 0;
3215 }
Serhiy Storchakae6a0b592017-05-20 20:05:27 +03003216 Py_INCREF(found);
3217 result = PyObject_RichCompareBool(value, found, Py_EQ);
3218 Py_DECREF(found);
3219 return result;
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003220}
3221
3222static PySequenceMethods dictitems_as_sequence = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003223 (lenfunc)dictview_len, /* sq_length */
3224 0, /* sq_concat */
3225 0, /* sq_repeat */
3226 0, /* sq_item */
3227 0, /* sq_slice */
3228 0, /* sq_ass_item */
3229 0, /* sq_ass_slice */
3230 (objobjproc)dictitems_contains, /* sq_contains */
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003231};
3232
3233static PyMethodDef dictitems_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003234 {NULL, NULL} /* sentinel */
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003235};
3236
3237PyTypeObject PyDictItems_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003238 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3239 "dict_items", /* tp_name */
3240 sizeof(dictviewobject), /* tp_basicsize */
3241 0, /* tp_itemsize */
3242 /* methods */
3243 (destructor)dictview_dealloc, /* tp_dealloc */
3244 0, /* tp_print */
3245 0, /* tp_getattr */
3246 0, /* tp_setattr */
3247 0, /* tp_reserved */
3248 (reprfunc)dictview_repr, /* tp_repr */
3249 &dictviews_as_number, /* tp_as_number */
3250 &dictitems_as_sequence, /* tp_as_sequence */
3251 0, /* tp_as_mapping */
3252 0, /* tp_hash */
3253 0, /* tp_call */
3254 0, /* tp_str */
3255 PyObject_GenericGetAttr, /* tp_getattro */
3256 0, /* tp_setattro */
3257 0, /* tp_as_buffer */
3258 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3259 Py_TPFLAGS_CHECKTYPES, /* tp_flags */
3260 0, /* tp_doc */
3261 (traverseproc)dictview_traverse, /* tp_traverse */
3262 0, /* tp_clear */
3263 dictview_richcompare, /* tp_richcompare */
3264 0, /* tp_weaklistoffset */
3265 (getiterfunc)dictitems_iter, /* tp_iter */
3266 0, /* tp_iternext */
3267 dictitems_methods, /* tp_methods */
3268 0,
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003269};
3270
3271static PyObject *
3272dictitems_new(PyObject *dict)
3273{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003274 return dictview_new(dict, &PyDictItems_Type);
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003275}
3276
3277/*** dict_values ***/
3278
3279static PyObject *
3280dictvalues_iter(dictviewobject *dv)
3281{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003282 if (dv->dv_dict == NULL) {
3283 Py_RETURN_NONE;
3284 }
3285 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003286}
3287
3288static PySequenceMethods dictvalues_as_sequence = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003289 (lenfunc)dictview_len, /* sq_length */
3290 0, /* sq_concat */
3291 0, /* sq_repeat */
3292 0, /* sq_item */
3293 0, /* sq_slice */
3294 0, /* sq_ass_item */
3295 0, /* sq_ass_slice */
3296 (objobjproc)0, /* sq_contains */
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003297};
3298
3299static PyMethodDef dictvalues_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003300 {NULL, NULL} /* sentinel */
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003301};
3302
3303PyTypeObject PyDictValues_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003304 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3305 "dict_values", /* tp_name */
3306 sizeof(dictviewobject), /* tp_basicsize */
3307 0, /* tp_itemsize */
3308 /* methods */
3309 (destructor)dictview_dealloc, /* tp_dealloc */
3310 0, /* tp_print */
3311 0, /* tp_getattr */
3312 0, /* tp_setattr */
3313 0, /* tp_reserved */
3314 (reprfunc)dictview_repr, /* tp_repr */
3315 0, /* tp_as_number */
3316 &dictvalues_as_sequence, /* tp_as_sequence */
3317 0, /* tp_as_mapping */
3318 0, /* tp_hash */
3319 0, /* tp_call */
3320 0, /* tp_str */
3321 PyObject_GenericGetAttr, /* tp_getattro */
3322 0, /* tp_setattro */
3323 0, /* tp_as_buffer */
3324 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3325 0, /* tp_doc */
3326 (traverseproc)dictview_traverse, /* tp_traverse */
3327 0, /* tp_clear */
3328 0, /* tp_richcompare */
3329 0, /* tp_weaklistoffset */
3330 (getiterfunc)dictvalues_iter, /* tp_iter */
3331 0, /* tp_iternext */
3332 dictvalues_methods, /* tp_methods */
3333 0,
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003334};
3335
3336static PyObject *
3337dictvalues_new(PyObject *dict)
3338{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003339 return dictview_new(dict, &PyDictValues_Type);
Alexandre Vassalotti69eb5162010-01-11 23:17:10 +00003340}