blob: e005f8ea5ca4e83412cd64c44880a3b95f5a0154 [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"
Christian Heimes0ded5b52007-12-10 15:50:56 +000011#include "stringlib/eq.h"
Guido van Rossum4b1302b1993-03-27 18:11:32 +000012
Guido van Rossum16e93a81997-01-28 00:00:11 +000013
Thomas Wouters89f507f2006-12-13 04:49:30 +000014/* Set a key error with the specified argument, wrapping it in a
15 * tuple automatically so that tuple keys are not unpacked as the
16 * exception arguments. */
17static void
18set_key_error(PyObject *arg)
19{
20 PyObject *tup;
21 tup = PyTuple_Pack(1, arg);
22 if (!tup)
23 return; /* caller will expect error to be set anyway */
24 PyErr_SetObject(PyExc_KeyError, tup);
25 Py_DECREF(tup);
26}
27
Tim Peterseb28ef22001-06-02 05:27:19 +000028/* Define this out if you don't want conversion statistics on exit. */
Fred Drake1bff34a2000-08-31 19:31:38 +000029#undef SHOW_CONVERSION_COUNTS
30
Tim Peterseb28ef22001-06-02 05:27:19 +000031/* See large comment block below. This must be >= 1. */
32#define PERTURB_SHIFT 5
33
Guido van Rossum16e93a81997-01-28 00:00:11 +000034/*
Tim Peterseb28ef22001-06-02 05:27:19 +000035Major subtleties ahead: Most hash schemes depend on having a "good" hash
36function, in the sense of simulating randomness. Python doesn't: its most
37important hash functions (for strings and ints) are very regular in common
38cases:
Tim Peters15d49292001-05-27 07:39:22 +000039
Guido van Rossumdc5f6b22006-08-24 21:29:26 +000040 >>> map(hash, (0, 1, 2, 3))
41 [0, 1, 2, 3]
42 >>> map(hash, ("namea", "nameb", "namec", "named"))
43 [-1658398457, -1658398460, -1658398459, -1658398462]
44 >>>
Tim Peters15d49292001-05-27 07:39:22 +000045
Tim Peterseb28ef22001-06-02 05:27:19 +000046This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
47the low-order i bits as the initial table index is extremely fast, and there
48are no collisions at all for dicts indexed by a contiguous range of ints.
49The same is approximately true when keys are "consecutive" strings. So this
50gives better-than-random behavior in common cases, and that's very desirable.
Tim Peters15d49292001-05-27 07:39:22 +000051
Tim Peterseb28ef22001-06-02 05:27:19 +000052OTOH, when collisions occur, the tendency to fill contiguous slices of the
53hash table makes a good collision resolution strategy crucial. Taking only
54the last i bits of the hash code is also vulnerable: for example, consider
Guido van Rossumdc5f6b22006-08-24 21:29:26 +000055the list [i << 16 for i in range(20000)] as a set of keys. Since ints are
56their own hash codes, and this fits in a dict of size 2**15, the last 15 bits
57 of every hash code are all 0: they *all* map to the same table index.
Tim Peters15d49292001-05-27 07:39:22 +000058
Tim Peterseb28ef22001-06-02 05:27:19 +000059But catering to unusual cases should not slow the usual ones, so we just take
60the last i bits anyway. It's up to collision resolution to do the rest. If
61we *usually* find the key we're looking for on the first try (and, it turns
62out, we usually do -- the table load factor is kept under 2/3, so the odds
63are solidly in our favor), then it makes best sense to keep the initial index
64computation dirt cheap.
Tim Peters15d49292001-05-27 07:39:22 +000065
Tim Peterseb28ef22001-06-02 05:27:19 +000066The first half of collision resolution is to visit table indices via this
67recurrence:
Tim Peters15d49292001-05-27 07:39:22 +000068
Tim Peterseb28ef22001-06-02 05:27:19 +000069 j = ((5*j) + 1) mod 2**i
Tim Peters15d49292001-05-27 07:39:22 +000070
Tim Peterseb28ef22001-06-02 05:27:19 +000071For any initial j in range(2**i), repeating that 2**i times generates each
72int in range(2**i) exactly once (see any text on random-number generation for
73proof). By itself, this doesn't help much: like linear probing (setting
74j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
75order. This would be bad, except that's not the only thing we do, and it's
76actually *good* in the common cases where hash keys are consecutive. In an
77example that's really too small to make this entirely clear, for a table of
78size 2**3 the order of indices is:
Tim Peters15d49292001-05-27 07:39:22 +000079
Tim Peterseb28ef22001-06-02 05:27:19 +000080 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
81
82If two things come in at index 5, the first place we look after is index 2,
83not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
84Linear probing is deadly in this case because there the fixed probe order
85is the *same* as the order consecutive keys are likely to arrive. But it's
86extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
87and certain that consecutive hash codes do not.
88
89The other half of the strategy is to get the other bits of the hash code
90into play. This is done by initializing a (unsigned) vrbl "perturb" to the
91full hash code, and changing the recurrence to:
92
93 j = (5*j) + 1 + perturb;
94 perturb >>= PERTURB_SHIFT;
95 use j % 2**i as the next table index;
96
97Now the probe sequence depends (eventually) on every bit in the hash code,
98and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
99because it quickly magnifies small differences in the bits that didn't affect
100the initial index. Note that because perturb is unsigned, if the recurrence
101is executed often enough perturb eventually becomes and remains 0. At that
102point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
103that's certain to find an empty slot eventually (since it generates every int
104in range(2**i), and we make sure there's always at least one empty slot).
105
106Selecting a good value for PERTURB_SHIFT is a balancing act. You want it
107small so that the high bits of the hash code continue to affect the probe
108sequence across iterations; but you want it large so that in really bad cases
109the high-order hash bits have an effect on early iterations. 5 was "the
110best" in minimizing total collisions across experiments Tim Peters ran (on
111both normal and pathological cases), but 4 and 6 weren't significantly worse.
112
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000113Historical: Reimer Behrends contributed the idea of using a polynomial-based
Tim Peterseb28ef22001-06-02 05:27:19 +0000114approach, using repeated multiplication by x in GF(2**n) where an irreducible
115polynomial for each table size was chosen such that x was a primitive root.
116Christian Tismer later extended that to use division by x instead, as an
117efficient way to get the high bits of the hash code into play. This scheme
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000118also gave excellent collision statistics, but was more expensive: two
119if-tests were required inside the loop; computing "the next" index took about
120the same number of operations but without as much potential parallelism
121(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
122above, and then shifting perturb can be done while the table index is being
123masked); and the PyDictObject struct required a member to hold the table's
124polynomial. In Tim's experiments the current scheme ran faster, produced
125equally good collision statistics, needed less code & used less memory.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000126
127Theoretical Python 2.5 headache: hash codes are only C "long", but
128sizeof(Py_ssize_t) > sizeof(long) may be possible. In that case, and if a
129dict is genuinely huge, then only the slots directly reachable via indexing
130by a C long can be the first slot in a probe sequence. The probe sequence
131will still eventually reach every slot in the table, but the collision rate
132on initial probes may be much higher than this scheme was designed for.
133Getting a hash code as fat as Py_ssize_t is the only real cure. But in
134practice, this probably won't make a lick of difference for many years (at
135which point everyone will have terabytes of RAM on 64-bit boxes).
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000136*/
Tim Petersdea48ec2001-05-22 20:40:22 +0000137
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000138/* Object used as dummy key to fill deleted entries */
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000139static PyObject *dummy = NULL; /* Initialized by first call to newPyDictObject() */
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000140
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000141#ifdef Py_REF_DEBUG
142PyObject *
143_PyDict_Dummy(void)
144{
145 return dummy;
146}
147#endif
148
Fred Drake1bff34a2000-08-31 19:31:38 +0000149/* forward declarations */
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000150static PyDictEntry *
151lookdict_unicode(PyDictObject *mp, PyObject *key, long hash);
Fred Drake1bff34a2000-08-31 19:31:38 +0000152
153#ifdef SHOW_CONVERSION_COUNTS
154static long created = 0L;
155static long converted = 0L;
156
157static void
158show_counts(void)
159{
160 fprintf(stderr, "created %ld string dicts\n", created);
161 fprintf(stderr, "converted %ld to normal dicts\n", converted);
162 fprintf(stderr, "%.2f%% conversion rate\n", (100.0*converted)/created);
163}
164#endif
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000165
Christian Heimes77c02eb2008-02-09 02:18:51 +0000166/* Debug statistic to compare allocations with reuse through the free list */
167#undef SHOW_ALLOC_COUNT
168#ifdef SHOW_ALLOC_COUNT
169static size_t count_alloc = 0;
170static size_t count_reuse = 0;
171
172static void
173show_alloc(void)
174{
Christian Heimes23daade2008-02-25 12:39:23 +0000175 fprintf(stderr, "Dict allocations: %" PY_FORMAT_SIZE_T "d\n",
176 count_alloc);
177 fprintf(stderr, "Dict reuse through freelist: %" PY_FORMAT_SIZE_T
178 "d\n", count_reuse);
Christian Heimes77c02eb2008-02-09 02:18:51 +0000179 fprintf(stderr, "%.2f%% reuse rate\n\n",
180 (100.0*count_reuse/(count_alloc+count_reuse)));
181}
182#endif
183
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000184/* Debug statistic to count GC tracking of dicts */
185#ifdef SHOW_TRACK_COUNT
186static Py_ssize_t count_untracked = 0;
187static Py_ssize_t count_tracked = 0;
188
189static void
190show_track(void)
191{
192 fprintf(stderr, "Dicts created: %" PY_FORMAT_SIZE_T "d\n",
193 count_tracked + count_untracked);
194 fprintf(stderr, "Dicts tracked by the GC: %" PY_FORMAT_SIZE_T
195 "d\n", count_tracked);
196 fprintf(stderr, "%.2f%% dict tracking rate\n\n",
197 (100.0*count_tracked/(count_untracked+count_tracked)));
198}
199#endif
200
201
Tim Peters6d6c1a32001-08-02 04:15:00 +0000202/* Initialization macros.
203 There are two ways to create a dict: PyDict_New() is the main C API
204 function, and the tp_new slot maps to dict_new(). In the latter case we
205 can save a little time over what PyDict_New does because it's guaranteed
206 that the PyDictObject struct is already zeroed out.
207 Everyone except dict_new() should use EMPTY_TO_MINSIZE (unless they have
208 an excellent reason not to).
209*/
210
211#define INIT_NONZERO_DICT_SLOTS(mp) do { \
Tim Petersdea48ec2001-05-22 20:40:22 +0000212 (mp)->ma_table = (mp)->ma_smalltable; \
Tim Peters6d6c1a32001-08-02 04:15:00 +0000213 (mp)->ma_mask = PyDict_MINSIZE - 1; \
214 } while(0)
215
216#define EMPTY_TO_MINSIZE(mp) do { \
217 memset((mp)->ma_smalltable, 0, sizeof((mp)->ma_smalltable)); \
Tim Petersdea48ec2001-05-22 20:40:22 +0000218 (mp)->ma_used = (mp)->ma_fill = 0; \
Tim Peters6d6c1a32001-08-02 04:15:00 +0000219 INIT_NONZERO_DICT_SLOTS(mp); \
Tim Petersdea48ec2001-05-22 20:40:22 +0000220 } while(0)
221
Raymond Hettinger43442782004-03-17 21:55:03 +0000222/* Dictionary reuse scheme to save calls to malloc, free, and memset */
Christian Heimes2202f872008-02-06 14:31:34 +0000223#ifndef PyDict_MAXFREELIST
224#define PyDict_MAXFREELIST 80
225#endif
226static PyDictObject *free_list[PyDict_MAXFREELIST];
227static int numfree = 0;
Raymond Hettinger43442782004-03-17 21:55:03 +0000228
Christian Heimes77c02eb2008-02-09 02:18:51 +0000229void
230PyDict_Fini(void)
231{
232 PyDictObject *op;
233
234 while (numfree) {
235 op = free_list[--numfree];
236 assert(PyDict_CheckExact(op));
237 PyObject_GC_Del(op);
238 }
239}
240
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000241PyObject *
Thomas Wouters78890102000-07-22 19:25:51 +0000242PyDict_New(void)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000243{
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000244 register PyDictObject *mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000245 if (dummy == NULL) { /* Auto-initialize dummy */
Neal Norwitz53cbdaa2007-08-23 21:42:55 +0000246 dummy = PyUnicode_FromString("<dummy key>");
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000247 if (dummy == NULL)
248 return NULL;
Fred Drake1bff34a2000-08-31 19:31:38 +0000249#ifdef SHOW_CONVERSION_COUNTS
250 Py_AtExit(show_counts);
251#endif
Christian Heimes77c02eb2008-02-09 02:18:51 +0000252#ifdef SHOW_ALLOC_COUNT
253 Py_AtExit(show_alloc);
254#endif
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000255#ifdef SHOW_TRACK_COUNT
256 Py_AtExit(show_track);
257#endif
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000258 }
Christian Heimes2202f872008-02-06 14:31:34 +0000259 if (numfree) {
260 mp = free_list[--numfree];
Raymond Hettinger43442782004-03-17 21:55:03 +0000261 assert (mp != NULL);
Christian Heimes90aa7642007-12-19 02:45:37 +0000262 assert (Py_TYPE(mp) == &PyDict_Type);
Raymond Hettinger43442782004-03-17 21:55:03 +0000263 _Py_NewReference((PyObject *)mp);
264 if (mp->ma_fill) {
265 EMPTY_TO_MINSIZE(mp);
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000266 } else {
267 /* At least set ma_table and ma_mask; these are wrong
268 if an empty but presized dict is added to freelist */
269 INIT_NONZERO_DICT_SLOTS(mp);
Raymond Hettinger43442782004-03-17 21:55:03 +0000270 }
271 assert (mp->ma_used == 0);
272 assert (mp->ma_table == mp->ma_smalltable);
273 assert (mp->ma_mask == PyDict_MINSIZE - 1);
Christian Heimes77c02eb2008-02-09 02:18:51 +0000274#ifdef SHOW_ALLOC_COUNT
275 count_reuse++;
276#endif
Raymond Hettinger43442782004-03-17 21:55:03 +0000277 } else {
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000278 mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
Raymond Hettinger43442782004-03-17 21:55:03 +0000279 if (mp == NULL)
280 return NULL;
281 EMPTY_TO_MINSIZE(mp);
Christian Heimes77c02eb2008-02-09 02:18:51 +0000282#ifdef SHOW_ALLOC_COUNT
283 count_alloc++;
284#endif
Raymond Hettinger43442782004-03-17 21:55:03 +0000285 }
Guido van Rossum89d8c602007-09-18 17:26:56 +0000286 mp->ma_lookup = lookdict_unicode;
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000287#ifdef SHOW_TRACK_COUNT
288 count_untracked++;
289#endif
Fred Drake1bff34a2000-08-31 19:31:38 +0000290#ifdef SHOW_CONVERSION_COUNTS
291 ++created;
292#endif
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000293 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000294}
295
296/*
297The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000298This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000299Open addressing is preferred over chaining since the link overhead for
300chaining would be substantial (100% with typical malloc overhead).
301
Tim Peterseb28ef22001-06-02 05:27:19 +0000302The initial probe index is computed as hash mod the table size. Subsequent
303probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000304
305All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000306
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000307The details in this version are due to Tim Peters, building on many past
Tim Peterseb28ef22001-06-02 05:27:19 +0000308contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000309Christian Tismer.
Fred Drake1bff34a2000-08-31 19:31:38 +0000310
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000311lookdict() is general-purpose, and may return NULL if (and only if) a
312comparison raises an exception (this was new in Python 2.5).
Guido van Rossum89d8c602007-09-18 17:26:56 +0000313lookdict_unicode() below is specialized to string keys, comparison of which can
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000314never raise an exception; that function can never return NULL. For both, when
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000315the key isn't found a PyDictEntry* is returned for which the me_value field is
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000316NULL; this is the slot in the dict at which the key would have been found, and
317the caller can (if it wishes) add the <key, value> pair to the returned
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000318PyDictEntry*.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000319*/
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000320static PyDictEntry *
321lookdict(PyDictObject *mp, PyObject *key, register long hash)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000322{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000323 register size_t i;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000324 register size_t perturb;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000325 register PyDictEntry *freeslot;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000326 register size_t mask = (size_t)mp->ma_mask;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000327 PyDictEntry *ep0 = mp->ma_table;
328 register PyDictEntry *ep;
Fred Drakec88b99c2000-08-31 19:04:07 +0000329 register int cmp;
Tim Peters453163d2001-06-03 04:54:32 +0000330 PyObject *startkey;
Tim Peterseb28ef22001-06-02 05:27:19 +0000331
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000332 i = (size_t)hash & mask;
Guido van Rossumefb46091997-01-29 15:53:56 +0000333 ep = &ep0[i];
Guido van Rossumc1c7b1a1998-10-06 16:01:14 +0000334 if (ep->me_key == NULL || ep->me_key == key)
Guido van Rossum7d181591997-01-16 21:06:45 +0000335 return ep;
Tim Peters7b5d0af2001-06-03 04:14:43 +0000336
Guido van Rossum16e93a81997-01-28 00:00:11 +0000337 if (ep->me_key == dummy)
Guido van Rossum7d181591997-01-16 21:06:45 +0000338 freeslot = ep;
Guido van Rossumfd7a0b81997-08-18 21:52:47 +0000339 else {
Fred Drakec88b99c2000-08-31 19:04:07 +0000340 if (ep->me_hash == hash) {
Tim Peters453163d2001-06-03 04:54:32 +0000341 startkey = ep->me_key;
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000342 Py_INCREF(startkey);
Tim Peters453163d2001-06-03 04:54:32 +0000343 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000344 Py_DECREF(startkey);
Tim Peters7b5d0af2001-06-03 04:14:43 +0000345 if (cmp < 0)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000346 return NULL;
Tim Peters453163d2001-06-03 04:54:32 +0000347 if (ep0 == mp->ma_table && ep->me_key == startkey) {
348 if (cmp > 0)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000349 return ep;
Tim Peters453163d2001-06-03 04:54:32 +0000350 }
351 else {
352 /* The compare did major nasty stuff to the
353 * dict: start over.
354 * XXX A clever adversary could prevent this
355 * XXX from terminating.
356 */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000357 return lookdict(mp, key, hash);
Tim Peters453163d2001-06-03 04:54:32 +0000358 }
Guido van Rossumfd7a0b81997-08-18 21:52:47 +0000359 }
360 freeslot = NULL;
Guido van Rossum2a61e741997-01-18 07:55:05 +0000361 }
Tim Peters15d49292001-05-27 07:39:22 +0000362
Tim Peters342c65e2001-05-13 06:43:53 +0000363 /* In the loop, me_key == dummy is by far (factor of 100s) the
364 least likely outcome, so test for that last. */
Tim Peterseb28ef22001-06-02 05:27:19 +0000365 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
366 i = (i << 2) + i + perturb + 1;
367 ep = &ep0[i & mask];
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000368 if (ep->me_key == NULL)
369 return freeslot == NULL ? ep : freeslot;
Tim Peters7b5d0af2001-06-03 04:14:43 +0000370 if (ep->me_key == key)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000371 return ep;
Tim Peters7b5d0af2001-06-03 04:14:43 +0000372 if (ep->me_hash == hash && ep->me_key != dummy) {
Tim Peters453163d2001-06-03 04:54:32 +0000373 startkey = ep->me_key;
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000374 Py_INCREF(startkey);
Tim Peters453163d2001-06-03 04:54:32 +0000375 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000376 Py_DECREF(startkey);
Tim Peters7b5d0af2001-06-03 04:14:43 +0000377 if (cmp < 0)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000378 return NULL;
Tim Peters453163d2001-06-03 04:54:32 +0000379 if (ep0 == mp->ma_table && ep->me_key == startkey) {
380 if (cmp > 0)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000381 return ep;
Tim Peters453163d2001-06-03 04:54:32 +0000382 }
383 else {
384 /* The compare did major nasty stuff to the
385 * dict: start over.
386 * XXX A clever adversary could prevent this
387 * XXX from terminating.
388 */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000389 return lookdict(mp, key, hash);
Tim Peters453163d2001-06-03 04:54:32 +0000390 }
Guido van Rossum16e93a81997-01-28 00:00:11 +0000391 }
Tim Peters342c65e2001-05-13 06:43:53 +0000392 else if (ep->me_key == dummy && freeslot == NULL)
393 freeslot = ep;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000394 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000395 assert(0); /* NOT REACHED */
396 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000397}
398
399/*
Guido van Rossum89d8c602007-09-18 17:26:56 +0000400 * Hacked up version of lookdict which can assume keys are always
401 * unicodes; this assumption allows testing for errors during
402 * PyObject_RichCompareBool() to be dropped; unicode-unicode
403 * comparisons never raise exceptions. This also means we don't need
404 * to go through PyObject_RichCompareBool(); we can always use
405 * unicode_eq() directly.
Fred Drake1bff34a2000-08-31 19:31:38 +0000406 *
Guido van Rossum89d8c602007-09-18 17:26:56 +0000407 * This is valuable because dicts with only unicode keys are very common.
Fred Drake1bff34a2000-08-31 19:31:38 +0000408 */
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000409static PyDictEntry *
410lookdict_unicode(PyDictObject *mp, PyObject *key, register long hash)
Fred Drake1bff34a2000-08-31 19:31:38 +0000411{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000412 register size_t i;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000413 register size_t perturb;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000414 register PyDictEntry *freeslot;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000415 register size_t mask = (size_t)mp->ma_mask;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000416 PyDictEntry *ep0 = mp->ma_table;
417 register PyDictEntry *ep;
Fred Drake1bff34a2000-08-31 19:31:38 +0000418
Guido van Rossum89d8c602007-09-18 17:26:56 +0000419 /* Make sure this function doesn't have to handle non-unicode keys,
Tim Peters0ab085c2001-09-14 00:25:33 +0000420 including subclasses of str; e.g., one reason to subclass
Guido van Rossum89d8c602007-09-18 17:26:56 +0000421 unicodes is to override __eq__, and for speed we don't cater to
Tim Peters0ab085c2001-09-14 00:25:33 +0000422 that here. */
Guido van Rossum89d8c602007-09-18 17:26:56 +0000423 if (!PyUnicode_CheckExact(key)) {
Fred Drake1bff34a2000-08-31 19:31:38 +0000424#ifdef SHOW_CONVERSION_COUNTS
425 ++converted;
426#endif
427 mp->ma_lookup = lookdict;
428 return lookdict(mp, key, hash);
429 }
Tim Peters2f228e72001-05-13 00:19:31 +0000430 i = hash & mask;
Fred Drake1bff34a2000-08-31 19:31:38 +0000431 ep = &ep0[i];
432 if (ep->me_key == NULL || ep->me_key == key)
433 return ep;
434 if (ep->me_key == dummy)
435 freeslot = ep;
436 else {
Guido van Rossum89d8c602007-09-18 17:26:56 +0000437 if (ep->me_hash == hash && unicode_eq(ep->me_key, key))
Fred Drake1bff34a2000-08-31 19:31:38 +0000438 return ep;
Fred Drake1bff34a2000-08-31 19:31:38 +0000439 freeslot = NULL;
440 }
Tim Peters15d49292001-05-27 07:39:22 +0000441
Tim Peters342c65e2001-05-13 06:43:53 +0000442 /* In the loop, me_key == dummy is by far (factor of 100s) the
443 least likely outcome, so test for that last. */
Tim Peterseb28ef22001-06-02 05:27:19 +0000444 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
445 i = (i << 2) + i + perturb + 1;
446 ep = &ep0[i & mask];
Tim Peters342c65e2001-05-13 06:43:53 +0000447 if (ep->me_key == NULL)
448 return freeslot == NULL ? ep : freeslot;
449 if (ep->me_key == key
450 || (ep->me_hash == hash
451 && ep->me_key != dummy
Guido van Rossum89d8c602007-09-18 17:26:56 +0000452 && unicode_eq(ep->me_key, key)))
Fred Drake1bff34a2000-08-31 19:31:38 +0000453 return ep;
Tim Petersdea48ec2001-05-22 20:40:22 +0000454 if (ep->me_key == dummy && freeslot == NULL)
Tim Peters342c65e2001-05-13 06:43:53 +0000455 freeslot = ep;
Fred Drake1bff34a2000-08-31 19:31:38 +0000456 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000457 assert(0); /* NOT REACHED */
458 return 0;
Fred Drake1bff34a2000-08-31 19:31:38 +0000459}
460
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000461#ifdef SHOW_TRACK_COUNT
462#define INCREASE_TRACK_COUNT \
463 (count_tracked++, count_untracked--);
464#define DECREASE_TRACK_COUNT \
465 (count_tracked--, count_untracked++);
466#else
467#define INCREASE_TRACK_COUNT
468#define DECREASE_TRACK_COUNT
469#endif
470
471#define MAINTAIN_TRACKING(mp, key, value) \
472 do { \
473 if (!_PyObject_GC_IS_TRACKED(mp)) { \
474 if (_PyObject_GC_MAY_BE_TRACKED(key) || \
475 _PyObject_GC_MAY_BE_TRACKED(value)) { \
476 _PyObject_GC_TRACK(mp); \
477 INCREASE_TRACK_COUNT \
478 } \
479 } \
480 } while(0)
481
482void
483_PyDict_MaybeUntrack(PyObject *op)
484{
485 PyDictObject *mp;
486 PyObject *value;
487 Py_ssize_t mask, i;
488 PyDictEntry *ep;
489
490 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
491 return;
492
493 mp = (PyDictObject *) op;
494 ep = mp->ma_table;
495 mask = mp->ma_mask;
496 for (i = 0; i <= mask; i++) {
497 if ((value = ep[i].me_value) == NULL)
498 continue;
499 if (_PyObject_GC_MAY_BE_TRACKED(value) ||
500 _PyObject_GC_MAY_BE_TRACKED(ep[i].me_key))
501 return;
502 }
503 _PyObject_GC_UNTRACK(op);
504}
505
506
Fred Drake1bff34a2000-08-31 19:31:38 +0000507/*
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000508Internal routine to insert a new item into the table.
509Used both by the internal resize routine and by the public insert routine.
510Eats a reference to key and one to value.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000511Returns -1 if an error occurred, or 0 on success.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000512*/
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000513static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000514insertdict(register PyDictObject *mp, PyObject *key, long hash, PyObject *value)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000515{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000516 PyObject *old_value;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000517 register PyDictEntry *ep;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000518 typedef PyDictEntry *(*lookupfunc)(PyDictObject *, PyObject *, long);
519
520 assert(mp->ma_lookup != NULL);
521 ep = mp->ma_lookup(mp, key, hash);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000522 if (ep == NULL) {
523 Py_DECREF(key);
524 Py_DECREF(value);
525 return -1;
526 }
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000527 MAINTAIN_TRACKING(mp, key, value);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000528 if (ep->me_value != NULL) {
Guido van Rossumd7047b31995-01-02 19:07:15 +0000529 old_value = ep->me_value;
530 ep->me_value = value;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000531 Py_DECREF(old_value); /* which **CAN** re-enter */
532 Py_DECREF(key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000533 }
534 else {
535 if (ep->me_key == NULL)
536 mp->ma_fill++;
Raymond Hettinger07ead172005-02-05 23:42:57 +0000537 else {
538 assert(ep->me_key == dummy);
539 Py_DECREF(dummy);
540 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000541 ep->me_key = key;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000542 ep->me_hash = (Py_ssize_t)hash;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000543 ep->me_value = value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000544 mp->ma_used++;
545 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000546 return 0;
547}
548
549/*
550Internal routine used by dictresize() to insert an item which is
551known to be absent from the dict. This routine also assumes that
552the dict contains no deleted entries. Besides the performance benefit,
553using insertdict() in dictresize() is dangerous (SF bug #1456209).
554Note that no refcounts are changed by this routine; if needed, the caller
555is responsible for incref'ing `key` and `value`.
556*/
557static void
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000558insertdict_clean(register PyDictObject *mp, PyObject *key, long hash,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000559 PyObject *value)
560{
561 register size_t i;
562 register size_t perturb;
563 register size_t mask = (size_t)mp->ma_mask;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000564 PyDictEntry *ep0 = mp->ma_table;
565 register PyDictEntry *ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000566
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000567 MAINTAIN_TRACKING(mp, key, value);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000568 i = hash & mask;
569 ep = &ep0[i];
570 for (perturb = hash; ep->me_key != NULL; perturb >>= PERTURB_SHIFT) {
571 i = (i << 2) + i + perturb + 1;
572 ep = &ep0[i & mask];
573 }
574 assert(ep->me_value == NULL);
575 mp->ma_fill++;
576 ep->me_key = key;
577 ep->me_hash = (Py_ssize_t)hash;
578 ep->me_value = value;
579 mp->ma_used++;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000580}
581
582/*
583Restructure the table by allocating a new table and reinserting all
584items again. When entries have been deleted, the new table may
585actually be smaller than the old one.
586*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000587static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000588dictresize(PyDictObject *mp, Py_ssize_t minused)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000589{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000590 Py_ssize_t newsize;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000591 PyDictEntry *oldtable, *newtable, *ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000592 Py_ssize_t i;
Tim Peters0c6010b2001-05-23 23:33:57 +0000593 int is_oldtable_malloced;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000594 PyDictEntry small_copy[PyDict_MINSIZE];
Tim Peters91a364d2001-05-19 07:04:38 +0000595
596 assert(minused >= 0);
Tim Peters0c6010b2001-05-23 23:33:57 +0000597
Tim Peterseb28ef22001-06-02 05:27:19 +0000598 /* Find the smallest table size > minused. */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000599 for (newsize = PyDict_MINSIZE;
Tim Peterseb28ef22001-06-02 05:27:19 +0000600 newsize <= minused && newsize > 0;
601 newsize <<= 1)
602 ;
603 if (newsize <= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000604 PyErr_NoMemory();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000605 return -1;
606 }
Tim Peters0c6010b2001-05-23 23:33:57 +0000607
608 /* Get space for a new table. */
609 oldtable = mp->ma_table;
610 assert(oldtable != NULL);
611 is_oldtable_malloced = oldtable != mp->ma_smalltable;
612
Tim Peters6d6c1a32001-08-02 04:15:00 +0000613 if (newsize == PyDict_MINSIZE) {
Tim Petersf8a548c2001-05-24 16:26:40 +0000614 /* A large table is shrinking, or we can't get any smaller. */
Tim Petersdea48ec2001-05-22 20:40:22 +0000615 newtable = mp->ma_smalltable;
Tim Peters0c6010b2001-05-23 23:33:57 +0000616 if (newtable == oldtable) {
Tim Petersf8a548c2001-05-24 16:26:40 +0000617 if (mp->ma_fill == mp->ma_used) {
618 /* No dummies, so no point doing anything. */
Tim Peters0c6010b2001-05-23 23:33:57 +0000619 return 0;
Tim Petersf8a548c2001-05-24 16:26:40 +0000620 }
621 /* We're not going to resize it, but rebuild the
622 table anyway to purge old dummy entries.
623 Subtle: This is *necessary* if fill==size,
624 as lookdict needs at least one virgin slot to
625 terminate failing searches. If fill < size, it's
626 merely desirable, as dummies slow searches. */
627 assert(mp->ma_fill > mp->ma_used);
Tim Peters0c6010b2001-05-23 23:33:57 +0000628 memcpy(small_copy, oldtable, sizeof(small_copy));
629 oldtable = small_copy;
630 }
Tim Petersdea48ec2001-05-22 20:40:22 +0000631 }
632 else {
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000633 newtable = PyMem_NEW(PyDictEntry, newsize);
Tim Petersdea48ec2001-05-22 20:40:22 +0000634 if (newtable == NULL) {
635 PyErr_NoMemory();
636 return -1;
637 }
638 }
Tim Peters0c6010b2001-05-23 23:33:57 +0000639
640 /* Make the dict empty, using the new table. */
Tim Petersdea48ec2001-05-22 20:40:22 +0000641 assert(newtable != oldtable);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000642 mp->ma_table = newtable;
Tim Petersafb6ae82001-06-04 21:00:21 +0000643 mp->ma_mask = newsize - 1;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000644 memset(newtable, 0, sizeof(PyDictEntry) * newsize);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000645 mp->ma_used = 0;
Tim Petersdea48ec2001-05-22 20:40:22 +0000646 i = mp->ma_fill;
647 mp->ma_fill = 0;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000648
Tim Peters19283142001-05-17 22:25:34 +0000649 /* Copy the data over; this is refcount-neutral for active entries;
650 dummy entries aren't copied over, of course */
Tim Petersdea48ec2001-05-22 20:40:22 +0000651 for (ep = oldtable; i > 0; ep++) {
652 if (ep->me_value != NULL) { /* active entry */
653 --i;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000654 insertdict_clean(mp, ep->me_key, (long)ep->me_hash,
655 ep->me_value);
Tim Petersdea48ec2001-05-22 20:40:22 +0000656 }
Tim Peters19283142001-05-17 22:25:34 +0000657 else if (ep->me_key != NULL) { /* dummy entry */
Tim Petersdea48ec2001-05-22 20:40:22 +0000658 --i;
Tim Peters19283142001-05-17 22:25:34 +0000659 assert(ep->me_key == dummy);
660 Py_DECREF(ep->me_key);
Guido van Rossum255443b1998-04-10 22:47:14 +0000661 }
Tim Peters19283142001-05-17 22:25:34 +0000662 /* else key == value == NULL: nothing to do */
Guido van Rossumd7047b31995-01-02 19:07:15 +0000663 }
664
Tim Peters0c6010b2001-05-23 23:33:57 +0000665 if (is_oldtable_malloced)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000666 PyMem_DEL(oldtable);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000667 return 0;
668}
669
Christian Heimes99170a52007-12-19 02:07:34 +0000670/* Create a new dictionary pre-sized to hold an estimated number of elements.
671 Underestimates are okay because the dictionary will resize as necessary.
672 Overestimates just mean the dictionary will be more sparse than usual.
673*/
674
675PyObject *
676_PyDict_NewPresized(Py_ssize_t minused)
677{
678 PyObject *op = PyDict_New();
679
680 if (minused>5 && op != NULL && dictresize((PyDictObject *)op, minused) == -1) {
681 Py_DECREF(op);
682 return NULL;
683 }
684 return op;
685}
686
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000687/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
688 * that may occur (originally dicts supported only string keys, and exceptions
689 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000690 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000691 * (suppressed) occurred while computing the key's hash, or that some error
692 * (suppressed) occurred when comparing keys in the dict's internal probe
693 * sequence. A nasty example of the latter is when a Python-coded comparison
694 * function hits a stack-depth error, which can cause this to return NULL
695 * even if the key is present.
696 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000697PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000698PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000699{
700 long hash;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000701 PyDictObject *mp = (PyDictObject *)op;
702 PyDictEntry *ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000703 PyThreadState *tstate;
704 if (!PyDict_Check(op))
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000705 return NULL;
Guido van Rossum4d027722007-09-18 04:30:42 +0000706 if (!PyUnicode_CheckExact(key) ||
707 (hash = ((PyUnicodeObject *) key)->hash) == -1)
Guido van Rossumca756f21997-01-23 19:39:29 +0000708 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000709 hash = PyObject_Hash(key);
Guido van Rossum474b19e1998-05-14 01:00:51 +0000710 if (hash == -1) {
711 PyErr_Clear();
Guido van Rossumca756f21997-01-23 19:39:29 +0000712 return NULL;
Guido van Rossum474b19e1998-05-14 01:00:51 +0000713 }
Guido van Rossumca756f21997-01-23 19:39:29 +0000714 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000715
716 /* We can arrive here with a NULL tstate during initialization:
717 try running "python -Wi" for an example related to string
718 interning. Let's just hope that no exception occurs then... */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000719 tstate = _PyThreadState_Current;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000720 if (tstate != NULL && tstate->curexc_type != NULL) {
721 /* preserve the existing exception */
722 PyObject *err_type, *err_value, *err_tb;
723 PyErr_Fetch(&err_type, &err_value, &err_tb);
724 ep = (mp->ma_lookup)(mp, key, hash);
725 /* ignore errors */
726 PyErr_Restore(err_type, err_value, err_tb);
727 if (ep == NULL)
728 return NULL;
729 }
730 else {
731 ep = (mp->ma_lookup)(mp, key, hash);
732 if (ep == NULL) {
733 PyErr_Clear();
734 return NULL;
735 }
736 }
737 return ep->me_value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000738}
739
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000740/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
741 This returns NULL *with* an exception set if an exception occurred.
742 It returns NULL *without* an exception set if the key wasn't present.
743*/
744PyObject *
745PyDict_GetItemWithError(PyObject *op, PyObject *key)
746{
747 long hash;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000748 PyDictObject*mp = (PyDictObject *)op;
749 PyDictEntry *ep;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000750
751 if (!PyDict_Check(op)) {
752 PyErr_BadInternalCall();
753 return NULL;
754 }
Guido van Rossum89d8c602007-09-18 17:26:56 +0000755 if (!PyUnicode_CheckExact(key) ||
756 (hash = ((PyUnicodeObject *) key)->hash) == -1)
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000757 {
758 hash = PyObject_Hash(key);
759 if (hash == -1) {
760 return NULL;
761 }
762 }
763
764 ep = (mp->ma_lookup)(mp, key, hash);
765 if (ep == NULL)
766 return NULL;
767 return ep->me_value;
768}
769
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000770/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
Tim Peters60b29962006-01-01 01:19:23 +0000771 * dictionary if it's merely replacing the value for an existing key.
772 * This means that it's safe to loop over a dictionary with PyDict_Next()
773 * and occasionally replace a value -- but you can't insert new keys or
774 * remove them.
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000775 */
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000776int
Tim Peters1f5871e2000-07-04 17:44:48 +0000777PyDict_SetItem(register PyObject *op, PyObject *key, PyObject *value)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000778{
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000779 register PyDictObject *mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000780 register long hash;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000781 register Py_ssize_t n_used;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000782
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000783 if (!PyDict_Check(op)) {
784 PyErr_BadInternalCall();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000785 return -1;
786 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000787 assert(key);
788 assert(value);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000789 mp = (PyDictObject *)op;
Guido van Rossum4d027722007-09-18 04:30:42 +0000790 if (!PyUnicode_CheckExact(key) ||
791 (hash = ((PyUnicodeObject *) key)->hash) == -1)
792 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000793 hash = PyObject_Hash(key);
Guido van Rossum2a61e741997-01-18 07:55:05 +0000794 if (hash == -1)
795 return -1;
Guido van Rossum2a61e741997-01-18 07:55:05 +0000796 }
Tim Petersafb6ae82001-06-04 21:00:21 +0000797 assert(mp->ma_fill <= mp->ma_mask); /* at least one empty slot */
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000798 n_used = mp->ma_used;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000799 Py_INCREF(value);
800 Py_INCREF(key);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000801 if (insertdict(mp, key, hash, value) != 0)
802 return -1;
Raymond Hettinger3539f6b2003-05-05 22:22:10 +0000803 /* If we added a key, we can safely resize. Otherwise just return!
804 * If fill >= 2/3 size, adjust size. Normally, this doubles or
805 * quaduples the size, but it's also possible for the dict to shrink
Tim Peters60b29962006-01-01 01:19:23 +0000806 * (if ma_fill is much larger than ma_used, meaning a lot of dict
Raymond Hettinger3539f6b2003-05-05 22:22:10 +0000807 * keys have been * deleted).
Tim Peters60b29962006-01-01 01:19:23 +0000808 *
Raymond Hettinger3539f6b2003-05-05 22:22:10 +0000809 * Quadrupling the size improves average dictionary sparseness
810 * (reducing collisions) at the cost of some memory and iteration
811 * speed (which loops over every possible entry). It also halves
812 * the number of expensive resize operations in a growing dictionary.
Tim Peters60b29962006-01-01 01:19:23 +0000813 *
814 * Very large dictionaries (over 50K items) use doubling instead.
Raymond Hettinger3539f6b2003-05-05 22:22:10 +0000815 * This may help applications with severe memory constraints.
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000816 */
Raymond Hettinger3539f6b2003-05-05 22:22:10 +0000817 if (!(mp->ma_used > n_used && mp->ma_fill*3 >= (mp->ma_mask+1)*2))
818 return 0;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000819 return dictresize(mp, (mp->ma_used > 50000 ? 2 : 4) * mp->ma_used);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000820}
821
822int
Tim Peters1f5871e2000-07-04 17:44:48 +0000823PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000824{
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000825 register PyDictObject *mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000826 register long hash;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000827 register PyDictEntry *ep;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000828 PyObject *old_value, *old_key;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000829
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000830 if (!PyDict_Check(op)) {
831 PyErr_BadInternalCall();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000832 return -1;
833 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000834 assert(key);
Guido van Rossum89d8c602007-09-18 17:26:56 +0000835 if (!PyUnicode_CheckExact(key) ||
836 (hash = ((PyUnicodeObject *) key)->hash) == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000837 hash = PyObject_Hash(key);
Guido van Rossumca756f21997-01-23 19:39:29 +0000838 if (hash == -1)
839 return -1;
840 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000841 mp = (PyDictObject *)op;
Fred Drake1bff34a2000-08-31 19:31:38 +0000842 ep = (mp->ma_lookup)(mp, key, hash);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000843 if (ep == NULL)
844 return -1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000845 if (ep->me_value == NULL) {
Thomas Wouters89f507f2006-12-13 04:49:30 +0000846 set_key_error(key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000847 return -1;
848 }
Guido van Rossumd7047b31995-01-02 19:07:15 +0000849 old_key = ep->me_key;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000850 Py_INCREF(dummy);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000851 ep->me_key = dummy;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000852 old_value = ep->me_value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000853 ep->me_value = NULL;
854 mp->ma_used--;
Tim Petersea8f2bf2000-12-13 01:02:46 +0000855 Py_DECREF(old_value);
856 Py_DECREF(old_key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000857 return 0;
858}
859
Guido van Rossum25831651993-05-19 14:50:45 +0000860void
Tim Peters1f5871e2000-07-04 17:44:48 +0000861PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000862{
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000863 PyDictObject *mp;
864 PyDictEntry *ep, *table;
Tim Petersdea48ec2001-05-22 20:40:22 +0000865 int table_is_malloced;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000866 Py_ssize_t fill;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000867 PyDictEntry small_copy[PyDict_MINSIZE];
Tim Petersdea48ec2001-05-22 20:40:22 +0000868#ifdef Py_DEBUG
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000869 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +0000870#endif
871
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000872 if (!PyDict_Check(op))
Guido van Rossum25831651993-05-19 14:50:45 +0000873 return;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000874 mp = (PyDictObject *)op;
Tim Petersdea48ec2001-05-22 20:40:22 +0000875#ifdef Py_DEBUG
Tim Petersafb6ae82001-06-04 21:00:21 +0000876 n = mp->ma_mask + 1;
Tim Petersdea48ec2001-05-22 20:40:22 +0000877 i = 0;
878#endif
879
880 table = mp->ma_table;
881 assert(table != NULL);
882 table_is_malloced = table != mp->ma_smalltable;
883
884 /* This is delicate. During the process of clearing the dict,
885 * decrefs can cause the dict to mutate. To avoid fatal confusion
886 * (voice of experience), we have to make the dict empty before
887 * clearing the slots, and never refer to anything via mp->xxx while
888 * clearing.
889 */
890 fill = mp->ma_fill;
891 if (table_is_malloced)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000892 EMPTY_TO_MINSIZE(mp);
Tim Petersdea48ec2001-05-22 20:40:22 +0000893
894 else if (fill > 0) {
895 /* It's a small table with something that needs to be cleared.
896 * Afraid the only safe way is to copy the dict entries into
897 * another small table first.
898 */
899 memcpy(small_copy, table, sizeof(small_copy));
900 table = small_copy;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000901 EMPTY_TO_MINSIZE(mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000902 }
Tim Petersdea48ec2001-05-22 20:40:22 +0000903 /* else it's a small table that's already empty */
904
905 /* Now we can finally clear things. If C had refcounts, we could
906 * assert that the refcount on table is 1 now, i.e. that this function
907 * has unique access to it, so decref side-effects can't alter it.
908 */
909 for (ep = table; fill > 0; ++ep) {
910#ifdef Py_DEBUG
911 assert(i < n);
912 ++i;
913#endif
914 if (ep->me_key) {
915 --fill;
916 Py_DECREF(ep->me_key);
917 Py_XDECREF(ep->me_value);
918 }
919#ifdef Py_DEBUG
920 else
921 assert(ep->me_value == NULL);
922#endif
923 }
924
925 if (table_is_malloced)
926 PyMem_DEL(table);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000927}
928
Tim Peters080c88b2003-02-15 03:01:11 +0000929/*
930 * Iterate over a dict. Use like so:
931 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000932 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +0000933 * PyObject *key, *value;
934 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +0000935 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Tim Peters080c88b2003-02-15 03:01:11 +0000936 * Refer to borrowed references in key and value.
937 * }
938 *
939 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +0000940 * mutates the dict. One exception: it is safe if the loop merely changes
941 * the values associated with the keys (but doesn't insert new keys or
942 * delete keys), via PyDict_SetItem().
943 */
Guido van Rossum25831651993-05-19 14:50:45 +0000944int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000945PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000946{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000947 register Py_ssize_t i;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000948 register Py_ssize_t mask;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000949 register PyDictEntry *ep;
Raymond Hettinger43442782004-03-17 21:55:03 +0000950
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000951 if (!PyDict_Check(op))
Guido van Rossum25831651993-05-19 14:50:45 +0000952 return 0;
Guido van Rossum25831651993-05-19 14:50:45 +0000953 i = *ppos;
954 if (i < 0)
955 return 0;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000956 ep = ((PyDictObject *)op)->ma_table;
957 mask = ((PyDictObject *)op)->ma_mask;
Raymond Hettinger43442782004-03-17 21:55:03 +0000958 while (i <= mask && ep[i].me_value == NULL)
Guido van Rossum25831651993-05-19 14:50:45 +0000959 i++;
960 *ppos = i+1;
Raymond Hettinger43442782004-03-17 21:55:03 +0000961 if (i > mask)
Guido van Rossum25831651993-05-19 14:50:45 +0000962 return 0;
963 if (pkey)
Raymond Hettinger43442782004-03-17 21:55:03 +0000964 *pkey = ep[i].me_key;
Guido van Rossum25831651993-05-19 14:50:45 +0000965 if (pvalue)
Raymond Hettinger43442782004-03-17 21:55:03 +0000966 *pvalue = ep[i].me_value;
Guido van Rossum25831651993-05-19 14:50:45 +0000967 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000968}
969
Thomas Wouterscf297e42007-02-23 15:07:44 +0000970/* Internal version of PyDict_Next that returns a hash value in addition to the key and value.*/
971int
972_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue, long *phash)
973{
974 register Py_ssize_t i;
975 register Py_ssize_t mask;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000976 register PyDictEntry *ep;
Thomas Wouterscf297e42007-02-23 15:07:44 +0000977
978 if (!PyDict_Check(op))
979 return 0;
980 i = *ppos;
981 if (i < 0)
982 return 0;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000983 ep = ((PyDictObject *)op)->ma_table;
984 mask = ((PyDictObject *)op)->ma_mask;
Thomas Wouterscf297e42007-02-23 15:07:44 +0000985 while (i <= mask && ep[i].me_value == NULL)
986 i++;
987 *ppos = i+1;
988 if (i > mask)
989 return 0;
990 *phash = (long)(ep[i].me_hash);
991 if (pkey)
992 *pkey = ep[i].me_key;
993 if (pvalue)
994 *pvalue = ep[i].me_value;
995 return 1;
996}
997
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000998/* Methods */
999
1000static void
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001001dict_dealloc(register PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001002{
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001003 register PyDictEntry *ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001004 Py_ssize_t fill = mp->ma_fill;
Guido van Rossumff413af2002-03-28 20:34:59 +00001005 PyObject_GC_UnTrack(mp);
Guido van Rossumd724b232000-03-13 16:01:29 +00001006 Py_TRASHCAN_SAFE_BEGIN(mp)
Tim Petersdea48ec2001-05-22 20:40:22 +00001007 for (ep = mp->ma_table; fill > 0; ep++) {
1008 if (ep->me_key) {
1009 --fill;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001010 Py_DECREF(ep->me_key);
Tim Petersdea48ec2001-05-22 20:40:22 +00001011 Py_XDECREF(ep->me_value);
Guido van Rossum255443b1998-04-10 22:47:14 +00001012 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001013 }
Tim Petersdea48ec2001-05-22 20:40:22 +00001014 if (mp->ma_table != mp->ma_smalltable)
Guido van Rossumb18618d2000-05-03 23:44:39 +00001015 PyMem_DEL(mp->ma_table);
Christian Heimes2202f872008-02-06 14:31:34 +00001016 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
1017 free_list[numfree++] = mp;
Tim Peters60b29962006-01-01 01:19:23 +00001018 else
Christian Heimes90aa7642007-12-19 02:45:37 +00001019 Py_TYPE(mp)->tp_free((PyObject *)mp);
Guido van Rossumd724b232000-03-13 16:01:29 +00001020 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001021}
1022
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001023static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001024dict_repr(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001025{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001026 Py_ssize_t i;
Tim Petersa7259592001-06-16 05:11:17 +00001027 PyObject *s, *temp, *colon = NULL;
1028 PyObject *pieces = NULL, *result = NULL;
1029 PyObject *key, *value;
Guido van Rossum255443b1998-04-10 22:47:14 +00001030
Tim Petersa7259592001-06-16 05:11:17 +00001031 i = Py_ReprEnter((PyObject *)mp);
Guido van Rossum255443b1998-04-10 22:47:14 +00001032 if (i != 0) {
Walter Dörwald1ab83302007-05-18 17:15:44 +00001033 return i > 0 ? PyUnicode_FromString("{...}") : NULL;
Guido van Rossum255443b1998-04-10 22:47:14 +00001034 }
1035
Tim Petersa7259592001-06-16 05:11:17 +00001036 if (mp->ma_used == 0) {
Walter Dörwald1ab83302007-05-18 17:15:44 +00001037 result = PyUnicode_FromString("{}");
Tim Petersa7259592001-06-16 05:11:17 +00001038 goto Done;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001039 }
Tim Petersa7259592001-06-16 05:11:17 +00001040
1041 pieces = PyList_New(0);
1042 if (pieces == NULL)
1043 goto Done;
1044
Walter Dörwald1ab83302007-05-18 17:15:44 +00001045 colon = PyUnicode_FromString(": ");
Tim Petersa7259592001-06-16 05:11:17 +00001046 if (colon == NULL)
1047 goto Done;
1048
1049 /* Do repr() on each key+value pair, and insert ": " between them.
1050 Note that repr may mutate the dict. */
Tim Petersc6057842001-06-16 07:52:53 +00001051 i = 0;
1052 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Tim Petersa7259592001-06-16 05:11:17 +00001053 int status;
1054 /* Prevent repr from deleting value during key format. */
1055 Py_INCREF(value);
1056 s = PyObject_Repr(key);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001057 PyUnicode_Append(&s, colon);
1058 PyUnicode_AppendAndDel(&s, PyObject_Repr(value));
Tim Petersa7259592001-06-16 05:11:17 +00001059 Py_DECREF(value);
1060 if (s == NULL)
1061 goto Done;
1062 status = PyList_Append(pieces, s);
1063 Py_DECREF(s); /* append created a new ref */
1064 if (status < 0)
1065 goto Done;
1066 }
1067
1068 /* Add "{}" decorations to the first and last items. */
1069 assert(PyList_GET_SIZE(pieces) > 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001070 s = PyUnicode_FromString("{");
Tim Petersa7259592001-06-16 05:11:17 +00001071 if (s == NULL)
1072 goto Done;
1073 temp = PyList_GET_ITEM(pieces, 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001074 PyUnicode_AppendAndDel(&s, temp);
Tim Petersa7259592001-06-16 05:11:17 +00001075 PyList_SET_ITEM(pieces, 0, s);
1076 if (s == NULL)
1077 goto Done;
1078
Walter Dörwald1ab83302007-05-18 17:15:44 +00001079 s = PyUnicode_FromString("}");
Tim Petersa7259592001-06-16 05:11:17 +00001080 if (s == NULL)
1081 goto Done;
1082 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001083 PyUnicode_AppendAndDel(&temp, s);
Tim Petersa7259592001-06-16 05:11:17 +00001084 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
1085 if (temp == NULL)
1086 goto Done;
1087
1088 /* Paste them all together with ", " between. */
Walter Dörwald1ab83302007-05-18 17:15:44 +00001089 s = PyUnicode_FromString(", ");
Tim Petersa7259592001-06-16 05:11:17 +00001090 if (s == NULL)
1091 goto Done;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001092 result = PyUnicode_Join(s, pieces);
Tim Peters0ab085c2001-09-14 00:25:33 +00001093 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +00001094
1095Done:
1096 Py_XDECREF(pieces);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001097 Py_XDECREF(colon);
Tim Petersa7259592001-06-16 05:11:17 +00001098 Py_ReprLeave((PyObject *)mp);
1099 return result;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001100}
1101
Martin v. Löwis18e16552006-02-15 17:27:45 +00001102static Py_ssize_t
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001103dict_length(PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001104{
1105 return mp->ma_used;
1106}
1107
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001108static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001109dict_subscript(PyDictObject *mp, register PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001110{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001111 PyObject *v;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +00001112 long hash;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001113 PyDictEntry *ep;
Tim Petersdea48ec2001-05-22 20:40:22 +00001114 assert(mp->ma_table != NULL);
Guido van Rossum89d8c602007-09-18 17:26:56 +00001115 if (!PyUnicode_CheckExact(key) ||
1116 (hash = ((PyUnicodeObject *) key)->hash) == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001117 hash = PyObject_Hash(key);
Guido van Rossumca756f21997-01-23 19:39:29 +00001118 if (hash == -1)
1119 return NULL;
1120 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001121 ep = (mp->ma_lookup)(mp, key, hash);
1122 if (ep == NULL)
1123 return NULL;
1124 v = ep->me_value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001125 if (v == NULL) {
1126 if (!PyDict_CheckExact(mp)) {
1127 /* Look up __missing__ method if we're a subclass. */
Guido van Rossum4b92a822006-02-25 23:32:30 +00001128 PyObject *missing;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001129 static PyObject *missing_str = NULL;
1130 if (missing_str == NULL)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001131 missing_str =
Martin v. Löwis5b222132007-06-10 09:51:05 +00001132 PyUnicode_InternFromString("__missing__");
Christian Heimes90aa7642007-12-19 02:45:37 +00001133 missing = _PyType_Lookup(Py_TYPE(mp), missing_str);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001134 if (missing != NULL)
1135 return PyObject_CallFunctionObjArgs(missing,
1136 (PyObject *)mp, key, NULL);
1137 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001138 set_key_error(key);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001139 return NULL;
1140 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001141 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001142 Py_INCREF(v);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001143 return v;
1144}
1145
1146static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001147dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001148{
1149 if (w == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001150 return PyDict_DelItem((PyObject *)mp, v);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001151 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001152 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001153}
1154
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001155static PyMappingMethods dict_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001156 (lenfunc)dict_length, /*mp_length*/
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001157 (binaryfunc)dict_subscript, /*mp_subscript*/
1158 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001159};
1160
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001161static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001162dict_keys(register PyDictObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001163{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001164 register PyObject *v;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001165 register Py_ssize_t i, j;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001166 PyDictEntry *ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001167 Py_ssize_t mask, n;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001168
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001169 again:
1170 n = mp->ma_used;
1171 v = PyList_New(n);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001172 if (v == NULL)
1173 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001174 if (n != mp->ma_used) {
1175 /* Durnit. The allocations caused the dict to resize.
1176 * Just start over, this shouldn't normally happen.
1177 */
1178 Py_DECREF(v);
1179 goto again;
1180 }
Raymond Hettinger43442782004-03-17 21:55:03 +00001181 ep = mp->ma_table;
1182 mask = mp->ma_mask;
1183 for (i = 0, j = 0; i <= mask; i++) {
1184 if (ep[i].me_value != NULL) {
1185 PyObject *key = ep[i].me_key;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001186 Py_INCREF(key);
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001187 PyList_SET_ITEM(v, j, key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001188 j++;
1189 }
1190 }
Raymond Hettinger43442782004-03-17 21:55:03 +00001191 assert(j == n);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001192 return v;
1193}
1194
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001195static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001196dict_values(register PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001197{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001198 register PyObject *v;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001199 register Py_ssize_t i, j;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001200 PyDictEntry *ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001201 Py_ssize_t mask, n;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001202
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001203 again:
1204 n = mp->ma_used;
1205 v = PyList_New(n);
Guido van Rossum25831651993-05-19 14:50:45 +00001206 if (v == NULL)
1207 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001208 if (n != mp->ma_used) {
1209 /* Durnit. The allocations caused the dict to resize.
1210 * Just start over, this shouldn't normally happen.
1211 */
1212 Py_DECREF(v);
1213 goto again;
1214 }
Raymond Hettinger43442782004-03-17 21:55:03 +00001215 ep = mp->ma_table;
1216 mask = mp->ma_mask;
1217 for (i = 0, j = 0; i <= mask; i++) {
1218 if (ep[i].me_value != NULL) {
1219 PyObject *value = ep[i].me_value;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001220 Py_INCREF(value);
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001221 PyList_SET_ITEM(v, j, value);
Guido van Rossum25831651993-05-19 14:50:45 +00001222 j++;
1223 }
1224 }
Raymond Hettinger43442782004-03-17 21:55:03 +00001225 assert(j == n);
Guido van Rossum25831651993-05-19 14:50:45 +00001226 return v;
1227}
1228
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001229static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001230dict_items(register PyDictObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001231{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001232 register PyObject *v;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001233 register Py_ssize_t i, j, n;
1234 Py_ssize_t mask;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001235 PyObject *item, *key, *value;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001236 PyDictEntry *ep;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001237
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001238 /* Preallocate the list of tuples, to avoid allocations during
1239 * the loop over the items, which could trigger GC, which
1240 * could resize the dict. :-(
1241 */
1242 again:
1243 n = mp->ma_used;
1244 v = PyList_New(n);
Guido van Rossum25831651993-05-19 14:50:45 +00001245 if (v == NULL)
1246 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001247 for (i = 0; i < n; i++) {
1248 item = PyTuple_New(2);
1249 if (item == NULL) {
1250 Py_DECREF(v);
1251 return NULL;
1252 }
1253 PyList_SET_ITEM(v, i, item);
1254 }
1255 if (n != mp->ma_used) {
1256 /* Durnit. The allocations caused the dict to resize.
1257 * Just start over, this shouldn't normally happen.
1258 */
1259 Py_DECREF(v);
1260 goto again;
1261 }
1262 /* Nothing we do below makes any function calls. */
Raymond Hettinger43442782004-03-17 21:55:03 +00001263 ep = mp->ma_table;
1264 mask = mp->ma_mask;
1265 for (i = 0, j = 0; i <= mask; i++) {
Raymond Hettinger06905122004-03-19 10:30:00 +00001266 if ((value=ep[i].me_value) != NULL) {
Raymond Hettinger43442782004-03-17 21:55:03 +00001267 key = ep[i].me_key;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001268 item = PyList_GET_ITEM(v, j);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001269 Py_INCREF(key);
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001270 PyTuple_SET_ITEM(item, 0, key);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001271 Py_INCREF(value);
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001272 PyTuple_SET_ITEM(item, 1, value);
Guido van Rossum25831651993-05-19 14:50:45 +00001273 j++;
1274 }
1275 }
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001276 assert(j == n);
Guido van Rossum25831651993-05-19 14:50:45 +00001277 return v;
1278}
1279
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001280static PyObject *
Tim Petersbca1cbc2002-12-09 22:56:13 +00001281dict_fromkeys(PyObject *cls, PyObject *args)
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001282{
1283 PyObject *seq;
1284 PyObject *value = Py_None;
1285 PyObject *it; /* iter(seq) */
1286 PyObject *key;
1287 PyObject *d;
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001288 int status;
1289
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001290 if (!PyArg_UnpackTuple(args, "fromkeys", 1, 2, &seq, &value))
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001291 return NULL;
1292
1293 d = PyObject_CallObject(cls, NULL);
1294 if (d == NULL)
1295 return NULL;
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001296
Guido van Rossum58da9312007-11-10 23:39:45 +00001297 if (PyDict_CheckExact(d) && PyDict_CheckExact(seq)) {
1298 PyDictObject *mp = (PyDictObject *)d;
1299 PyObject *oldvalue;
1300 Py_ssize_t pos = 0;
1301 PyObject *key;
1302 long hash;
1303
Benjamin Peterson41181742008-07-02 20:22:54 +00001304 if (dictresize(mp, Py_SIZE(seq)))
Guido van Rossum58da9312007-11-10 23:39:45 +00001305 return NULL;
1306
1307 while (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash)) {
1308 Py_INCREF(key);
1309 Py_INCREF(value);
1310 if (insertdict(mp, key, hash, value))
1311 return NULL;
1312 }
1313 return d;
1314 }
1315
Guido van Rossumd8faa362007-04-27 19:54:29 +00001316 if (PyDict_CheckExact(d) && PyAnySet_CheckExact(seq)) {
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001317 PyDictObject *mp = (PyDictObject *)d;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001318 Py_ssize_t pos = 0;
1319 PyObject *key;
1320 long hash;
1321
1322 if (dictresize(mp, PySet_GET_SIZE(seq)))
1323 return NULL;
1324
1325 while (_PySet_NextEntry(seq, &pos, &key, &hash)) {
1326 Py_INCREF(key);
1327 Py_INCREF(value);
1328 if (insertdict(mp, key, hash, value))
1329 return NULL;
1330 }
1331 return d;
1332 }
1333
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001334 it = PyObject_GetIter(seq);
1335 if (it == NULL){
1336 Py_DECREF(d);
1337 return NULL;
1338 }
1339
Guido van Rossum58da9312007-11-10 23:39:45 +00001340 if (PyDict_CheckExact(d)) {
1341 while ((key = PyIter_Next(it)) != NULL) {
1342 status = PyDict_SetItem(d, key, value);
1343 Py_DECREF(key);
1344 if (status < 0)
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001345 goto Fail;
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001346 }
Guido van Rossum58da9312007-11-10 23:39:45 +00001347 } else {
1348 while ((key = PyIter_Next(it)) != NULL) {
1349 status = PyObject_SetItem(d, key, value);
1350 Py_DECREF(key);
1351 if (status < 0)
1352 goto Fail;
1353 }
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001354 }
1355
Guido van Rossum58da9312007-11-10 23:39:45 +00001356 if (PyErr_Occurred())
1357 goto Fail;
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001358 Py_DECREF(it);
1359 return d;
1360
1361Fail:
1362 Py_DECREF(it);
1363 Py_DECREF(d);
1364 return NULL;
1365}
1366
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001367static int
1368dict_update_common(PyObject *self, PyObject *args, PyObject *kwds, char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001369{
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001370 PyObject *arg = NULL;
1371 int result = 0;
1372
1373 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
1374 result = -1;
1375
1376 else if (arg != NULL) {
1377 if (PyObject_HasAttrString(arg, "keys"))
1378 result = PyDict_Merge(self, arg, 1);
1379 else
1380 result = PyDict_MergeFromSeq2(self, arg, 1);
1381 }
1382 if (result == 0 && kwds != NULL)
1383 result = PyDict_Merge(self, kwds, 1);
1384 return result;
1385}
1386
1387static PyObject *
1388dict_update(PyObject *self, PyObject *args, PyObject *kwds)
1389{
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001390 if (dict_update_common(self, args, kwds, "update") != -1)
1391 Py_RETURN_NONE;
1392 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001393}
1394
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001395/* Update unconditionally replaces existing items.
1396 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00001397 otherwise it leaves existing items unchanged.
1398
1399 PyDict_{Update,Merge} update/merge from a mapping object.
1400
Tim Petersf582b822001-12-11 18:51:08 +00001401 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00001402 producing iterable objects of length 2.
1403*/
1404
Tim Petersf582b822001-12-11 18:51:08 +00001405int
Tim Peters1fc240e2001-10-26 05:06:50 +00001406PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
1407{
1408 PyObject *it; /* iter(seq2) */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001409 Py_ssize_t i; /* index into seq2 of current element */
Tim Peters1fc240e2001-10-26 05:06:50 +00001410 PyObject *item; /* seq2[i] */
1411 PyObject *fast; /* item as a 2-tuple or 2-list */
1412
1413 assert(d != NULL);
1414 assert(PyDict_Check(d));
1415 assert(seq2 != NULL);
1416
1417 it = PyObject_GetIter(seq2);
1418 if (it == NULL)
1419 return -1;
1420
1421 for (i = 0; ; ++i) {
1422 PyObject *key, *value;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001423 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00001424
1425 fast = NULL;
1426 item = PyIter_Next(it);
1427 if (item == NULL) {
1428 if (PyErr_Occurred())
1429 goto Fail;
1430 break;
1431 }
1432
1433 /* Convert item to sequence, and verify length 2. */
1434 fast = PySequence_Fast(item, "");
1435 if (fast == NULL) {
1436 if (PyErr_ExceptionMatches(PyExc_TypeError))
1437 PyErr_Format(PyExc_TypeError,
1438 "cannot convert dictionary update "
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001439 "sequence element #%zd to a sequence",
Tim Peters1fc240e2001-10-26 05:06:50 +00001440 i);
1441 goto Fail;
1442 }
1443 n = PySequence_Fast_GET_SIZE(fast);
1444 if (n != 2) {
1445 PyErr_Format(PyExc_ValueError,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001446 "dictionary update sequence element #%zd "
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00001447 "has length %zd; 2 is required",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00001448 i, n);
Tim Peters1fc240e2001-10-26 05:06:50 +00001449 goto Fail;
1450 }
1451
1452 /* Update/merge with this (key, value) pair. */
1453 key = PySequence_Fast_GET_ITEM(fast, 0);
1454 value = PySequence_Fast_GET_ITEM(fast, 1);
1455 if (override || PyDict_GetItem(d, key) == NULL) {
1456 int status = PyDict_SetItem(d, key, value);
1457 if (status < 0)
1458 goto Fail;
1459 }
1460 Py_DECREF(fast);
1461 Py_DECREF(item);
1462 }
1463
1464 i = 0;
1465 goto Return;
1466Fail:
1467 Py_XDECREF(item);
1468 Py_XDECREF(fast);
1469 i = -1;
1470Return:
1471 Py_DECREF(it);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001472 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00001473}
1474
Tim Peters6d6c1a32001-08-02 04:15:00 +00001475int
1476PyDict_Update(PyObject *a, PyObject *b)
1477{
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001478 return PyDict_Merge(a, b, 1);
1479}
1480
1481int
1482PyDict_Merge(PyObject *a, PyObject *b, int override)
1483{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001484 register PyDictObject *mp, *other;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001485 register Py_ssize_t i;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001486 PyDictEntry *entry;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001487
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001488 /* We accept for the argument either a concrete dictionary object,
1489 * or an abstract "mapping" object. For the former, we can do
1490 * things quite efficiently. For the latter, we only require that
1491 * PyMapping_Keys() and PyObject_GetItem() be supported.
1492 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001493 if (a == NULL || !PyDict_Check(a) || b == NULL) {
1494 PyErr_BadInternalCall();
1495 return -1;
1496 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001497 mp = (PyDictObject*)a;
Christian Heimesaf98da12008-01-27 15:18:18 +00001498 if (PyDict_Check(b)) {
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001499 other = (PyDictObject*)b;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001500 if (other == mp || other->ma_used == 0)
1501 /* a.update(a) or a.update({}); nothing to do */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001502 return 0;
Raymond Hettinger186e7392005-05-14 18:08:25 +00001503 if (mp->ma_used == 0)
1504 /* Since the target dict is empty, PyDict_GetItem()
1505 * always returns NULL. Setting override to 1
1506 * skips the unnecessary test.
1507 */
1508 override = 1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001509 /* Do one big resize at the start, rather than
1510 * incrementally resizing as we insert new items. Expect
1511 * that there will be no (or few) overlapping keys.
1512 */
1513 if ((mp->ma_fill + other->ma_used)*3 >= (mp->ma_mask+1)*2) {
Raymond Hettingerc8d22902003-05-07 00:49:40 +00001514 if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001515 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001516 }
1517 for (i = 0; i <= other->ma_mask; i++) {
1518 entry = &other->ma_table[i];
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001519 if (entry->me_value != NULL &&
1520 (override ||
1521 PyDict_GetItem(a, entry->me_key) == NULL)) {
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001522 Py_INCREF(entry->me_key);
1523 Py_INCREF(entry->me_value);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001524 if (insertdict(mp, entry->me_key,
1525 (long)entry->me_hash,
1526 entry->me_value) != 0)
1527 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001528 }
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001529 }
1530 }
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001531 else {
1532 /* Do it the generic, slower way */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001533 PyObject *keys = PyMapping_Keys(b);
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001534 PyObject *iter;
1535 PyObject *key, *value;
1536 int status;
1537
1538 if (keys == NULL)
1539 /* Docstring says this is equivalent to E.keys() so
1540 * if E doesn't have a .keys() method we want
1541 * AttributeError to percolate up. Might as well
1542 * do the same for any other error.
1543 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001544 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001545
1546 iter = PyObject_GetIter(keys);
1547 Py_DECREF(keys);
1548 if (iter == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001549 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001550
1551 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001552 if (!override && PyDict_GetItem(a, key) != NULL) {
1553 Py_DECREF(key);
1554 continue;
1555 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001556 value = PyObject_GetItem(b, key);
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001557 if (value == NULL) {
1558 Py_DECREF(iter);
1559 Py_DECREF(key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001560 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001561 }
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001562 status = PyDict_SetItem(a, key, value);
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001563 Py_DECREF(key);
1564 Py_DECREF(value);
1565 if (status < 0) {
1566 Py_DECREF(iter);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001567 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001568 }
1569 }
1570 Py_DECREF(iter);
1571 if (PyErr_Occurred())
1572 /* Iterator completed, via error */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001573 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001574 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001575 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001576}
1577
1578static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001579dict_copy(register PyDictObject *mp)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001580{
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001581 return PyDict_Copy((PyObject*)mp);
1582}
1583
1584PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001585PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001586{
Raymond Hettingerebedb2f2004-03-08 04:19:01 +00001587 PyObject *copy;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001588
1589 if (o == NULL || !PyDict_Check(o)) {
1590 PyErr_BadInternalCall();
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001591 return NULL;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001592 }
Raymond Hettingerebedb2f2004-03-08 04:19:01 +00001593 copy = PyDict_New();
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001594 if (copy == NULL)
1595 return NULL;
Raymond Hettingerebedb2f2004-03-08 04:19:01 +00001596 if (PyDict_Merge(copy, o, 1) == 0)
1597 return copy;
1598 Py_DECREF(copy);
Raymond Hettinger1356f782005-04-15 15:58:42 +00001599 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001600}
1601
Martin v. Löwis18e16552006-02-15 17:27:45 +00001602Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00001603PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00001604{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001605 if (mp == NULL || !PyDict_Check(mp)) {
1606 PyErr_BadInternalCall();
Jeremy Hylton7083bb72004-02-17 20:10:11 +00001607 return -1;
Guido van Rossum4199fac1993-11-05 10:18:44 +00001608 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001609 return ((PyDictObject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00001610}
1611
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001612PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001613PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001614{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001615 if (mp == NULL || !PyDict_Check(mp)) {
1616 PyErr_BadInternalCall();
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001617 return NULL;
1618 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001619 return dict_keys((PyDictObject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001620}
1621
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001622PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001623PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001624{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001625 if (mp == NULL || !PyDict_Check(mp)) {
1626 PyErr_BadInternalCall();
Guido van Rossum25831651993-05-19 14:50:45 +00001627 return NULL;
1628 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001629 return dict_values((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00001630}
1631
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001632PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001633PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001634{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001635 if (mp == NULL || !PyDict_Check(mp)) {
1636 PyErr_BadInternalCall();
Guido van Rossum25831651993-05-19 14:50:45 +00001637 return NULL;
1638 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001639 return dict_items((PyDictObject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00001640}
1641
Tim Peterse63415e2001-05-08 04:38:29 +00001642/* Return 1 if dicts equal, 0 if not, -1 if error.
1643 * Gets out as soon as any difference is detected.
1644 * Uses only Py_EQ comparison.
1645 */
1646static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001647dict_equal(PyDictObject *a, PyDictObject *b)
Tim Peterse63415e2001-05-08 04:38:29 +00001648{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001649 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00001650
1651 if (a->ma_used != b->ma_used)
1652 /* can't be equal if # of entries differ */
1653 return 0;
Tim Peterseb28ef22001-06-02 05:27:19 +00001654
Tim Peterse63415e2001-05-08 04:38:29 +00001655 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Tim Petersafb6ae82001-06-04 21:00:21 +00001656 for (i = 0; i <= a->ma_mask; i++) {
Tim Peterse63415e2001-05-08 04:38:29 +00001657 PyObject *aval = a->ma_table[i].me_value;
1658 if (aval != NULL) {
1659 int cmp;
1660 PyObject *bval;
1661 PyObject *key = a->ma_table[i].me_key;
1662 /* temporarily bump aval's refcount to ensure it stays
1663 alive until we're done with it */
1664 Py_INCREF(aval);
Guido van Rossumdc5f6b22006-08-24 21:29:26 +00001665 /* ditto for key */
1666 Py_INCREF(key);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001667 bval = PyDict_GetItemWithError((PyObject *)b, key);
Guido van Rossumdc5f6b22006-08-24 21:29:26 +00001668 Py_DECREF(key);
Tim Peterse63415e2001-05-08 04:38:29 +00001669 if (bval == NULL) {
1670 Py_DECREF(aval);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001671 if (PyErr_Occurred())
1672 return -1;
Tim Peterse63415e2001-05-08 04:38:29 +00001673 return 0;
1674 }
1675 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
1676 Py_DECREF(aval);
1677 if (cmp <= 0) /* error or not equal */
1678 return cmp;
1679 }
1680 }
1681 return 1;
1682 }
1683
1684static PyObject *
1685dict_richcompare(PyObject *v, PyObject *w, int op)
1686{
1687 int cmp;
1688 PyObject *res;
1689
1690 if (!PyDict_Check(v) || !PyDict_Check(w)) {
1691 res = Py_NotImplemented;
1692 }
1693 else if (op == Py_EQ || op == Py_NE) {
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001694 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
Tim Peterse63415e2001-05-08 04:38:29 +00001695 if (cmp < 0)
1696 return NULL;
1697 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
1698 }
Tim Peters4fa58bf2001-05-10 21:45:19 +00001699 else
1700 res = Py_NotImplemented;
Tim Peterse63415e2001-05-08 04:38:29 +00001701 Py_INCREF(res);
1702 return res;
1703 }
1704
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001705static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001706dict_contains(register PyDictObject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001707{
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001708 long hash;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001709 PyDictEntry *ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001710
Guido van Rossum89d8c602007-09-18 17:26:56 +00001711 if (!PyUnicode_CheckExact(key) ||
1712 (hash = ((PyUnicodeObject *) key)->hash) == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001713 hash = PyObject_Hash(key);
Guido van Rossumca756f21997-01-23 19:39:29 +00001714 if (hash == -1)
1715 return NULL;
1716 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001717 ep = (mp->ma_lookup)(mp, key, hash);
1718 if (ep == NULL)
1719 return NULL;
1720 return PyBool_FromLong(ep->me_value != NULL);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001721}
1722
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001723static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001724dict_get(register PyDictObject *mp, PyObject *args)
Barry Warsawc38c5da1997-10-06 17:49:20 +00001725{
1726 PyObject *key;
Barry Warsaw320ac331997-10-20 17:26:25 +00001727 PyObject *failobj = Py_None;
Barry Warsawc38c5da1997-10-06 17:49:20 +00001728 PyObject *val = NULL;
1729 long hash;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001730 PyDictEntry *ep;
Barry Warsawc38c5da1997-10-06 17:49:20 +00001731
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001732 if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
Barry Warsawc38c5da1997-10-06 17:49:20 +00001733 return NULL;
1734
Guido van Rossum89d8c602007-09-18 17:26:56 +00001735 if (!PyUnicode_CheckExact(key) ||
1736 (hash = ((PyUnicodeObject *) key)->hash) == -1) {
Barry Warsawc38c5da1997-10-06 17:49:20 +00001737 hash = PyObject_Hash(key);
1738 if (hash == -1)
1739 return NULL;
1740 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001741 ep = (mp->ma_lookup)(mp, key, hash);
1742 if (ep == NULL)
1743 return NULL;
1744 val = ep->me_value;
Barry Warsawc38c5da1997-10-06 17:49:20 +00001745 if (val == NULL)
1746 val = failobj;
1747 Py_INCREF(val);
1748 return val;
1749}
1750
1751
1752static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001753dict_setdefault(register PyDictObject *mp, PyObject *args)
Guido van Rossum164452c2000-08-08 16:12:54 +00001754{
1755 PyObject *key;
1756 PyObject *failobj = Py_None;
1757 PyObject *val = NULL;
1758 long hash;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001759 PyDictEntry *ep;
Guido van Rossum164452c2000-08-08 16:12:54 +00001760
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001761 if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &failobj))
Guido van Rossum164452c2000-08-08 16:12:54 +00001762 return NULL;
Guido van Rossum164452c2000-08-08 16:12:54 +00001763
Guido van Rossum89d8c602007-09-18 17:26:56 +00001764 if (!PyUnicode_CheckExact(key) ||
1765 (hash = ((PyUnicodeObject *) key)->hash) == -1) {
Guido van Rossum164452c2000-08-08 16:12:54 +00001766 hash = PyObject_Hash(key);
1767 if (hash == -1)
1768 return NULL;
1769 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001770 ep = (mp->ma_lookup)(mp, key, hash);
1771 if (ep == NULL)
1772 return NULL;
1773 val = ep->me_value;
Guido van Rossum164452c2000-08-08 16:12:54 +00001774 if (val == NULL) {
1775 val = failobj;
1776 if (PyDict_SetItem((PyObject*)mp, key, failobj))
1777 val = NULL;
1778 }
1779 Py_XINCREF(val);
1780 return val;
1781}
1782
1783
1784static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001785dict_clear(register PyDictObject *mp)
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00001786{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001787 PyDict_Clear((PyObject *)mp);
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001788 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00001789}
1790
Guido van Rossumba6ab842000-12-12 22:02:18 +00001791static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001792dict_pop(PyDictObject *mp, PyObject *args)
Guido van Rossume027d982002-04-12 15:11:59 +00001793{
1794 long hash;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001795 PyDictEntry *ep;
Guido van Rossume027d982002-04-12 15:11:59 +00001796 PyObject *old_value, *old_key;
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001797 PyObject *key, *deflt = NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00001798
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001799 if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
1800 return NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00001801 if (mp->ma_used == 0) {
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001802 if (deflt) {
1803 Py_INCREF(deflt);
1804 return deflt;
1805 }
Guido van Rossume027d982002-04-12 15:11:59 +00001806 PyErr_SetString(PyExc_KeyError,
1807 "pop(): dictionary is empty");
1808 return NULL;
1809 }
Guido van Rossum89d8c602007-09-18 17:26:56 +00001810 if (!PyUnicode_CheckExact(key) ||
1811 (hash = ((PyUnicodeObject *) key)->hash) == -1) {
Guido van Rossume027d982002-04-12 15:11:59 +00001812 hash = PyObject_Hash(key);
1813 if (hash == -1)
1814 return NULL;
1815 }
1816 ep = (mp->ma_lookup)(mp, key, hash);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001817 if (ep == NULL)
1818 return NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00001819 if (ep->me_value == NULL) {
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001820 if (deflt) {
1821 Py_INCREF(deflt);
1822 return deflt;
1823 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001824 set_key_error(key);
Guido van Rossume027d982002-04-12 15:11:59 +00001825 return NULL;
1826 }
1827 old_key = ep->me_key;
1828 Py_INCREF(dummy);
1829 ep->me_key = dummy;
1830 old_value = ep->me_value;
1831 ep->me_value = NULL;
1832 mp->ma_used--;
1833 Py_DECREF(old_key);
1834 return old_value;
1835}
1836
1837static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001838dict_popitem(PyDictObject *mp)
Guido van Rossumba6ab842000-12-12 22:02:18 +00001839{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001840 Py_ssize_t i = 0;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001841 PyDictEntry *ep;
Guido van Rossumba6ab842000-12-12 22:02:18 +00001842 PyObject *res;
1843
Tim Petersf4b33f62001-06-02 05:42:29 +00001844 /* Allocate the result tuple before checking the size. Believe it
1845 * or not, this allocation could trigger a garbage collection which
1846 * could empty the dict, so if we checked the size first and that
1847 * happened, the result would be an infinite loop (searching for an
1848 * entry that no longer exists). Note that the usual popitem()
1849 * idiom is "while d: k, v = d.popitem()". so needing to throw the
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001850 * tuple away if the dict *is* empty isn't a significant
Tim Petersf4b33f62001-06-02 05:42:29 +00001851 * inefficiency -- possible, but unlikely in practice.
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001852 */
1853 res = PyTuple_New(2);
1854 if (res == NULL)
1855 return NULL;
Guido van Rossume04eaec2001-04-16 00:02:32 +00001856 if (mp->ma_used == 0) {
1857 Py_DECREF(res);
1858 PyErr_SetString(PyExc_KeyError,
1859 "popitem(): dictionary is empty");
1860 return NULL;
1861 }
Guido van Rossumba6ab842000-12-12 22:02:18 +00001862 /* Set ep to "the first" dict entry with a value. We abuse the hash
1863 * field of slot 0 to hold a search finger:
1864 * If slot 0 has a value, use slot 0.
1865 * Else slot 0 is being used to hold a search finger,
1866 * and we use its hash value as the first index to look.
1867 */
1868 ep = &mp->ma_table[0];
1869 if (ep->me_value == NULL) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001870 i = ep->me_hash;
Tim Petersdea48ec2001-05-22 20:40:22 +00001871 /* The hash field may be a real hash value, or it may be a
1872 * legit search finger, or it may be a once-legit search
1873 * finger that's out of bounds now because it wrapped around
1874 * or the table shrunk -- simply make sure it's in bounds now.
Guido van Rossumba6ab842000-12-12 22:02:18 +00001875 */
Tim Petersafb6ae82001-06-04 21:00:21 +00001876 if (i > mp->ma_mask || i < 1)
Guido van Rossumba6ab842000-12-12 22:02:18 +00001877 i = 1; /* skip slot 0 */
1878 while ((ep = &mp->ma_table[i])->me_value == NULL) {
1879 i++;
Tim Petersafb6ae82001-06-04 21:00:21 +00001880 if (i > mp->ma_mask)
Guido van Rossumba6ab842000-12-12 22:02:18 +00001881 i = 1;
1882 }
1883 }
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001884 PyTuple_SET_ITEM(res, 0, ep->me_key);
1885 PyTuple_SET_ITEM(res, 1, ep->me_value);
1886 Py_INCREF(dummy);
1887 ep->me_key = dummy;
1888 ep->me_value = NULL;
1889 mp->ma_used--;
1890 assert(mp->ma_table[0].me_value == NULL);
1891 mp->ma_table[0].me_hash = i + 1; /* next place to start */
Guido van Rossumba6ab842000-12-12 22:02:18 +00001892 return res;
1893}
1894
Jeremy Hylton8caad492000-06-23 14:18:11 +00001895static int
1896dict_traverse(PyObject *op, visitproc visit, void *arg)
1897{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001898 Py_ssize_t i = 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00001899 PyObject *pk;
1900 PyObject *pv;
1901
1902 while (PyDict_Next(op, &i, &pk, &pv)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001903 Py_VISIT(pk);
1904 Py_VISIT(pv);
Jeremy Hylton8caad492000-06-23 14:18:11 +00001905 }
1906 return 0;
1907}
1908
1909static int
1910dict_tp_clear(PyObject *op)
1911{
1912 PyDict_Clear(op);
1913 return 0;
1914}
1915
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001916static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00001917
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001918static PyObject *
1919dict_sizeof(PyDictObject *mp)
1920{
1921 Py_ssize_t res;
1922
Robert Schuppenies4d45bfe2008-06-28 23:58:47 +00001923 res = sizeof(PyDictObject);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001924 if (mp->ma_table != mp->ma_smalltable)
1925 res = res + (mp->ma_mask + 1) * sizeof(PyDictEntry);
1926 return PyLong_FromSsize_t(res);
1927}
1928
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00001929PyDoc_STRVAR(contains__doc__,
1930"D.__contains__(k) -> True if D has a key k, else False");
1931
1932PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
1933
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001934PyDoc_STRVAR(sizeof__doc__,
1935"D.__sizeof__() -> size of D in memory, in bytes");
1936
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001937PyDoc_STRVAR(get__doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00001938"D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.");
Tim Petersf7f88b12000-12-13 23:18:45 +00001939
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001940PyDoc_STRVAR(setdefault_doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00001941"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 +00001942
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001943PyDoc_STRVAR(pop__doc__,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001944"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001945If key is not found, d is returned if given, otherwise KeyError is raised");
Guido van Rossume027d982002-04-12 15:11:59 +00001946
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001947PyDoc_STRVAR(popitem__doc__,
Tim Petersf7f88b12000-12-13 23:18:45 +00001948"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000019492-tuple; but raise KeyError if D is empty.");
Tim Petersf7f88b12000-12-13 23:18:45 +00001950
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001951PyDoc_STRVAR(update__doc__,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001952"D.update(E, **F) -> None. Update D from dict/iterable E and F.\n"
1953"If E has a .keys() method, does: for k in E: D[k] = E[k]\n\
1954If E lacks .keys() method, does: for (k, v) in E: D[k] = v\n\
1955In either case, this is followed by: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00001956
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001957PyDoc_STRVAR(fromkeys__doc__,
1958"dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.\n\
1959v defaults to None.");
1960
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001961PyDoc_STRVAR(clear__doc__,
1962"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00001963
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001964PyDoc_STRVAR(copy__doc__,
1965"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00001966
Guido van Rossumb90c8482007-02-10 01:11:45 +00001967/* Forward */
1968static PyObject *dictkeys_new(PyObject *);
1969static PyObject *dictitems_new(PyObject *);
1970static PyObject *dictvalues_new(PyObject *);
1971
Guido van Rossum45c85d12007-07-27 16:31:40 +00001972PyDoc_STRVAR(keys__doc__,
1973 "D.keys() -> a set-like object providing a view on D's keys");
1974PyDoc_STRVAR(items__doc__,
1975 "D.items() -> a set-like object providing a view on D's items");
1976PyDoc_STRVAR(values__doc__,
1977 "D.values() -> an object providing a view on D's values");
Guido van Rossumb90c8482007-02-10 01:11:45 +00001978
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001979static PyMethodDef mapp_methods[] = {
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001980 {"__contains__",(PyCFunction)dict_contains, METH_O | METH_COEXIST,
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00001981 contains__doc__},
Raymond Hettinger0c669672003-12-13 13:31:55 +00001982 {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00001983 getitem__doc__},
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001984 {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS,
1985 sizeof__doc__},
Tim Petersf7f88b12000-12-13 23:18:45 +00001986 {"get", (PyCFunction)dict_get, METH_VARARGS,
1987 get__doc__},
1988 {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS,
1989 setdefault_doc__},
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001990 {"pop", (PyCFunction)dict_pop, METH_VARARGS,
Just van Rossuma797d812002-11-23 09:45:04 +00001991 pop__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001992 {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
Tim Petersf7f88b12000-12-13 23:18:45 +00001993 popitem__doc__},
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001994 {"keys", (PyCFunction)dictkeys_new, METH_NOARGS,
Guido van Rossumeff072c2007-02-27 05:47:18 +00001995 keys__doc__},
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001996 {"items", (PyCFunction)dictitems_new, METH_NOARGS,
Guido van Rossumeff072c2007-02-27 05:47:18 +00001997 items__doc__},
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001998 {"values", (PyCFunction)dictvalues_new, METH_NOARGS,
Guido van Rossumeff072c2007-02-27 05:47:18 +00001999 values__doc__},
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002000 {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
Tim Petersf7f88b12000-12-13 23:18:45 +00002001 update__doc__},
Raymond Hettingere33d3df2002-11-27 07:29:33 +00002002 {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS,
2003 fromkeys__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002004 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
Tim Petersf7f88b12000-12-13 23:18:45 +00002005 clear__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002006 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
Tim Petersf7f88b12000-12-13 23:18:45 +00002007 copy__doc__},
2008 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002009};
2010
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002011/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00002012int
2013PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002014{
2015 long hash;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002016 PyDictObject *mp = (PyDictObject *)op;
2017 PyDictEntry *ep;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002018
Guido van Rossum89d8c602007-09-18 17:26:56 +00002019 if (!PyUnicode_CheckExact(key) ||
2020 (hash = ((PyUnicodeObject *) key)->hash) == -1) {
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002021 hash = PyObject_Hash(key);
2022 if (hash == -1)
2023 return -1;
2024 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002025 ep = (mp->ma_lookup)(mp, key, hash);
2026 return ep == NULL ? -1 : (ep->me_value != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002027}
2028
Thomas Wouterscf297e42007-02-23 15:07:44 +00002029/* Internal version of PyDict_Contains used when the hash value is already known */
2030int
2031_PyDict_Contains(PyObject *op, PyObject *key, long hash)
2032{
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002033 PyDictObject *mp = (PyDictObject *)op;
2034 PyDictEntry *ep;
Thomas Wouterscf297e42007-02-23 15:07:44 +00002035
2036 ep = (mp->ma_lookup)(mp, key, hash);
2037 return ep == NULL ? -1 : (ep->me_value != NULL);
2038}
2039
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002040/* Hack to implement "key in dict" */
2041static PySequenceMethods dict_as_sequence = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002042 0, /* sq_length */
2043 0, /* sq_concat */
2044 0, /* sq_repeat */
2045 0, /* sq_item */
2046 0, /* sq_slice */
2047 0, /* sq_ass_item */
2048 0, /* sq_ass_slice */
2049 PyDict_Contains, /* sq_contains */
2050 0, /* sq_inplace_concat */
2051 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002052};
2053
Guido van Rossum09e563a2001-05-01 12:10:21 +00002054static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002055dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2056{
2057 PyObject *self;
2058
2059 assert(type != NULL && type->tp_alloc != NULL);
2060 self = type->tp_alloc(type, 0);
2061 if (self != NULL) {
2062 PyDictObject *d = (PyDictObject *)self;
2063 /* It's guaranteed that tp->alloc zeroed out the struct. */
2064 assert(d->ma_table == NULL && d->ma_fill == 0 && d->ma_used == 0);
2065 INIT_NONZERO_DICT_SLOTS(d);
Guido van Rossum89d8c602007-09-18 17:26:56 +00002066 d->ma_lookup = lookdict_unicode;
Antoine Pitrou3a652b12009-03-23 18:52:06 +00002067 /* The object has been implicitely tracked by tp_alloc */
2068 if (type == &PyDict_Type)
2069 _PyObject_GC_UNTRACK(d);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002070#ifdef SHOW_CONVERSION_COUNTS
2071 ++created;
2072#endif
Antoine Pitrou3a652b12009-03-23 18:52:06 +00002073#ifdef SHOW_TRACK_COUNT
2074 if (_PyObject_GC_IS_TRACKED(d))
2075 count_tracked++;
2076 else
2077 count_untracked++;
2078#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00002079 }
2080 return self;
2081}
2082
Tim Peters25786c02001-09-02 08:22:48 +00002083static int
2084dict_init(PyObject *self, PyObject *args, PyObject *kwds)
2085{
Raymond Hettinger31017ae2004-03-04 08:25:44 +00002086 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00002087}
2088
Tim Peters6d6c1a32001-08-02 04:15:00 +00002089static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002090dict_iter(PyDictObject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00002091{
Raymond Hettinger019a1482004-03-18 02:41:19 +00002092 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00002093}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002094
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002095PyDoc_STRVAR(dictionary_doc,
Tim Petersa427a2b2001-10-29 22:25:45 +00002096"dict() -> new empty dictionary.\n"
2097"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Tim Peters1fc240e2001-10-26 05:06:50 +00002098" (key, value) pairs.\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00002099"dict(seq) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00002100" d = {}\n"
2101" for k, v in seq:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00002102" d[k] = v\n"
2103"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
2104" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00002105
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002106PyTypeObject PyDict_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002107 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Petersa427a2b2001-10-29 22:25:45 +00002108 "dict",
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002109 sizeof(PyDictObject),
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002110 0,
Guido van Rossumb9324202001-01-18 00:39:02 +00002111 (destructor)dict_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00002112 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002113 0, /* tp_getattr */
Guido van Rossumb9324202001-01-18 00:39:02 +00002114 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002115 0, /* tp_reserved */
Guido van Rossumb9324202001-01-18 00:39:02 +00002116 (reprfunc)dict_repr, /* tp_repr */
2117 0, /* tp_as_number */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002118 &dict_as_sequence, /* tp_as_sequence */
Guido van Rossumb9324202001-01-18 00:39:02 +00002119 &dict_as_mapping, /* tp_as_mapping */
Nick Coghland1abd252008-07-15 15:46:38 +00002120 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
Guido van Rossumb9324202001-01-18 00:39:02 +00002121 0, /* tp_call */
2122 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002123 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossumb9324202001-01-18 00:39:02 +00002124 0, /* tp_setattro */
2125 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002126 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002127 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
Tim Peters25786c02001-09-02 08:22:48 +00002128 dictionary_doc, /* tp_doc */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002129 dict_traverse, /* tp_traverse */
2130 dict_tp_clear, /* tp_clear */
Tim Peterse63415e2001-05-08 04:38:29 +00002131 dict_richcompare, /* tp_richcompare */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002132 0, /* tp_weaklistoffset */
Guido van Rossum09e563a2001-05-01 12:10:21 +00002133 (getiterfunc)dict_iter, /* tp_iter */
Guido van Rossum213c7a62001-04-23 14:08:49 +00002134 0, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002135 mapp_methods, /* tp_methods */
2136 0, /* tp_members */
2137 0, /* tp_getset */
2138 0, /* tp_base */
2139 0, /* tp_dict */
2140 0, /* tp_descr_get */
2141 0, /* tp_descr_set */
2142 0, /* tp_dictoffset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002143 dict_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002144 PyType_GenericAlloc, /* tp_alloc */
2145 dict_new, /* tp_new */
Neil Schemenauer6189b892002-04-12 02:43:00 +00002146 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002147};
2148
Guido van Rossum3cca2451997-05-16 14:23:33 +00002149/* For backward compatibility with old dictionary interface */
2150
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002151PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00002152PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002153{
Guido van Rossum3cca2451997-05-16 14:23:33 +00002154 PyObject *kv, *rv;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002155 kv = PyUnicode_FromString(key);
Guido van Rossum3cca2451997-05-16 14:23:33 +00002156 if (kv == NULL)
2157 return NULL;
Guido van Rossum3cca2451997-05-16 14:23:33 +00002158 rv = PyDict_GetItem(v, kv);
2159 Py_DECREF(kv);
2160 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002161}
2162
2163int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00002164PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002165{
Guido van Rossum3cca2451997-05-16 14:23:33 +00002166 PyObject *kv;
2167 int err;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002168 kv = PyUnicode_FromString(key);
Guido van Rossum3cca2451997-05-16 14:23:33 +00002169 if (kv == NULL)
Guido van Rossum037b2201997-05-20 18:35:19 +00002170 return -1;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002171 PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
Guido van Rossum3cca2451997-05-16 14:23:33 +00002172 err = PyDict_SetItem(v, kv, item);
2173 Py_DECREF(kv);
2174 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002175}
2176
2177int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00002178PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002179{
Guido van Rossum3cca2451997-05-16 14:23:33 +00002180 PyObject *kv;
2181 int err;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002182 kv = PyUnicode_FromString(key);
Guido van Rossum3cca2451997-05-16 14:23:33 +00002183 if (kv == NULL)
Guido van Rossum037b2201997-05-20 18:35:19 +00002184 return -1;
Guido van Rossum3cca2451997-05-16 14:23:33 +00002185 err = PyDict_DelItem(v, kv);
2186 Py_DECREF(kv);
2187 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002188}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002189
Raymond Hettinger019a1482004-03-18 02:41:19 +00002190/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002191
2192typedef struct {
2193 PyObject_HEAD
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002194 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002195 Py_ssize_t di_used;
2196 Py_ssize_t di_pos;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002197 PyObject* di_result; /* reusable result tuple for iteritems */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002198 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002199} dictiterobject;
2200
2201static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002202dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002203{
2204 dictiterobject *di;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002205 di = PyObject_GC_New(dictiterobject, itertype);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002206 if (di == NULL)
2207 return NULL;
2208 Py_INCREF(dict);
2209 di->di_dict = dict;
Guido van Rossumb1f35bf2001-05-02 15:13:44 +00002210 di->di_used = dict->ma_used;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002211 di->di_pos = 0;
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002212 di->len = dict->ma_used;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002213 if (itertype == &PyDictIterItem_Type) {
2214 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
2215 if (di->di_result == NULL) {
2216 Py_DECREF(di);
2217 return NULL;
2218 }
2219 }
2220 else
2221 di->di_result = NULL;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002222 _PyObject_GC_TRACK(di);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002223 return (PyObject *)di;
2224}
2225
2226static void
2227dictiter_dealloc(dictiterobject *di)
2228{
Guido van Rossum2147df72002-07-16 20:30:22 +00002229 Py_XDECREF(di->di_dict);
Raymond Hettinger019a1482004-03-18 02:41:19 +00002230 Py_XDECREF(di->di_result);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002231 PyObject_GC_Del(di);
2232}
2233
2234static int
2235dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
2236{
2237 Py_VISIT(di->di_dict);
2238 Py_VISIT(di->di_result);
2239 return 0;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002240}
2241
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002242static PyObject *
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002243dictiter_len(dictiterobject *di)
2244{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002245 Py_ssize_t len = 0;
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00002246 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002247 len = di->len;
Christian Heimes217cfd12007-12-02 14:31:20 +00002248 return PyLong_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002249}
2250
Guido van Rossumb90c8482007-02-10 01:11:45 +00002251PyDoc_STRVAR(length_hint_doc,
2252 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002253
2254static PyMethodDef dictiter_methods[] = {
Guido van Rossumb90c8482007-02-10 01:11:45 +00002255 {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS,
2256 length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002257 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002258};
2259
Raymond Hettinger019a1482004-03-18 02:41:19 +00002260static PyObject *dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00002261{
Raymond Hettinger019a1482004-03-18 02:41:19 +00002262 PyObject *key;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002263 register Py_ssize_t i, mask;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002264 register PyDictEntry *ep;
2265 PyDictObject *d = di->di_dict;
Guido van Rossum213c7a62001-04-23 14:08:49 +00002266
Raymond Hettinger019a1482004-03-18 02:41:19 +00002267 if (d == NULL)
Guido van Rossum2147df72002-07-16 20:30:22 +00002268 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002269 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00002270
Raymond Hettinger019a1482004-03-18 02:41:19 +00002271 if (di->di_used != d->ma_used) {
Guido van Rossum213c7a62001-04-23 14:08:49 +00002272 PyErr_SetString(PyExc_RuntimeError,
2273 "dictionary changed size during iteration");
Guido van Rossum2147df72002-07-16 20:30:22 +00002274 di->di_used = -1; /* Make this state sticky */
Guido van Rossum213c7a62001-04-23 14:08:49 +00002275 return NULL;
2276 }
Guido van Rossum2147df72002-07-16 20:30:22 +00002277
Raymond Hettinger019a1482004-03-18 02:41:19 +00002278 i = di->di_pos;
2279 if (i < 0)
2280 goto fail;
2281 ep = d->ma_table;
2282 mask = d->ma_mask;
2283 while (i <= mask && ep[i].me_value == NULL)
2284 i++;
2285 di->di_pos = i+1;
2286 if (i > mask)
2287 goto fail;
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002288 di->len--;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002289 key = ep[i].me_key;
2290 Py_INCREF(key);
2291 return key;
2292
2293fail:
2294 Py_DECREF(d);
Guido van Rossum2147df72002-07-16 20:30:22 +00002295 di->di_dict = NULL;
Guido van Rossum213c7a62001-04-23 14:08:49 +00002296 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002297}
2298
Raymond Hettinger019a1482004-03-18 02:41:19 +00002299PyTypeObject PyDictIterKey_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002300 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Christian Heimesf83be4e2007-11-28 09:44:38 +00002301 "dict_keyiterator", /* tp_name */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002302 sizeof(dictiterobject), /* tp_basicsize */
2303 0, /* tp_itemsize */
2304 /* methods */
2305 (destructor)dictiter_dealloc, /* tp_dealloc */
2306 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002307 0, /* tp_getattr */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002308 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002309 0, /* tp_reserved */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002310 0, /* tp_repr */
2311 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002312 0, /* tp_as_sequence */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002313 0, /* tp_as_mapping */
2314 0, /* tp_hash */
2315 0, /* tp_call */
2316 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002317 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002318 0, /* tp_setattro */
2319 0, /* tp_as_buffer */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002320 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002321 0, /* tp_doc */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002322 (traverseproc)dictiter_traverse, /* tp_traverse */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002323 0, /* tp_clear */
2324 0, /* tp_richcompare */
2325 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002326 PyObject_SelfIter, /* tp_iter */
Raymond Hettinger019a1482004-03-18 02:41:19 +00002327 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002328 dictiter_methods, /* tp_methods */
2329 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00002330};
2331
2332static PyObject *dictiter_iternextvalue(dictiterobject *di)
2333{
2334 PyObject *value;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002335 register Py_ssize_t i, mask;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002336 register PyDictEntry *ep;
2337 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002338
2339 if (d == NULL)
2340 return NULL;
2341 assert (PyDict_Check(d));
2342
2343 if (di->di_used != d->ma_used) {
2344 PyErr_SetString(PyExc_RuntimeError,
2345 "dictionary changed size during iteration");
2346 di->di_used = -1; /* Make this state sticky */
2347 return NULL;
2348 }
2349
2350 i = di->di_pos;
Guido van Rossum09240f62004-03-20 19:11:58 +00002351 mask = d->ma_mask;
2352 if (i < 0 || i > mask)
Raymond Hettinger019a1482004-03-18 02:41:19 +00002353 goto fail;
2354 ep = d->ma_table;
Guido van Rossum09240f62004-03-20 19:11:58 +00002355 while ((value=ep[i].me_value) == NULL) {
Raymond Hettinger019a1482004-03-18 02:41:19 +00002356 i++;
Guido van Rossum09240f62004-03-20 19:11:58 +00002357 if (i > mask)
2358 goto fail;
2359 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00002360 di->di_pos = i+1;
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002361 di->len--;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002362 Py_INCREF(value);
2363 return value;
2364
2365fail:
2366 Py_DECREF(d);
2367 di->di_dict = NULL;
2368 return NULL;
2369}
2370
2371PyTypeObject PyDictIterValue_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002372 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Christian Heimesf83be4e2007-11-28 09:44:38 +00002373 "dict_valueiterator", /* tp_name */
Raymond Hettinger019a1482004-03-18 02:41:19 +00002374 sizeof(dictiterobject), /* tp_basicsize */
2375 0, /* tp_itemsize */
2376 /* methods */
2377 (destructor)dictiter_dealloc, /* tp_dealloc */
2378 0, /* tp_print */
2379 0, /* tp_getattr */
2380 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002381 0, /* tp_reserved */
Raymond Hettinger019a1482004-03-18 02:41:19 +00002382 0, /* tp_repr */
2383 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002384 0, /* tp_as_sequence */
Raymond Hettinger019a1482004-03-18 02:41:19 +00002385 0, /* tp_as_mapping */
2386 0, /* tp_hash */
2387 0, /* tp_call */
2388 0, /* tp_str */
2389 PyObject_GenericGetAttr, /* tp_getattro */
2390 0, /* tp_setattro */
2391 0, /* tp_as_buffer */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002392 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Raymond Hettinger019a1482004-03-18 02:41:19 +00002393 0, /* tp_doc */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002394 (traverseproc)dictiter_traverse, /* tp_traverse */
Raymond Hettinger019a1482004-03-18 02:41:19 +00002395 0, /* tp_clear */
2396 0, /* tp_richcompare */
2397 0, /* tp_weaklistoffset */
2398 PyObject_SelfIter, /* tp_iter */
2399 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002400 dictiter_methods, /* tp_methods */
2401 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00002402};
2403
2404static PyObject *dictiter_iternextitem(dictiterobject *di)
2405{
2406 PyObject *key, *value, *result = di->di_result;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002407 register Py_ssize_t i, mask;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002408 register PyDictEntry *ep;
2409 PyDictObject *d = di->di_dict;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002410
2411 if (d == NULL)
2412 return NULL;
2413 assert (PyDict_Check(d));
2414
2415 if (di->di_used != d->ma_used) {
2416 PyErr_SetString(PyExc_RuntimeError,
2417 "dictionary changed size during iteration");
2418 di->di_used = -1; /* Make this state sticky */
2419 return NULL;
2420 }
2421
2422 i = di->di_pos;
2423 if (i < 0)
2424 goto fail;
2425 ep = d->ma_table;
2426 mask = d->ma_mask;
2427 while (i <= mask && ep[i].me_value == NULL)
2428 i++;
2429 di->di_pos = i+1;
2430 if (i > mask)
2431 goto fail;
2432
2433 if (result->ob_refcnt == 1) {
2434 Py_INCREF(result);
2435 Py_DECREF(PyTuple_GET_ITEM(result, 0));
2436 Py_DECREF(PyTuple_GET_ITEM(result, 1));
2437 } else {
2438 result = PyTuple_New(2);
Tim Peters60b29962006-01-01 01:19:23 +00002439 if (result == NULL)
Raymond Hettinger019a1482004-03-18 02:41:19 +00002440 return NULL;
2441 }
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002442 di->len--;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002443 key = ep[i].me_key;
2444 value = ep[i].me_value;
2445 Py_INCREF(key);
2446 Py_INCREF(value);
2447 PyTuple_SET_ITEM(result, 0, key);
2448 PyTuple_SET_ITEM(result, 1, value);
2449 return result;
2450
2451fail:
2452 Py_DECREF(d);
2453 di->di_dict = NULL;
2454 return NULL;
2455}
2456
2457PyTypeObject PyDictIterItem_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002458 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Christian Heimesf83be4e2007-11-28 09:44:38 +00002459 "dict_itemiterator", /* tp_name */
Raymond Hettinger019a1482004-03-18 02:41:19 +00002460 sizeof(dictiterobject), /* tp_basicsize */
2461 0, /* tp_itemsize */
2462 /* methods */
2463 (destructor)dictiter_dealloc, /* tp_dealloc */
2464 0, /* tp_print */
2465 0, /* tp_getattr */
2466 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002467 0, /* tp_reserved */
Raymond Hettinger019a1482004-03-18 02:41:19 +00002468 0, /* tp_repr */
2469 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002470 0, /* tp_as_sequence */
Raymond Hettinger019a1482004-03-18 02:41:19 +00002471 0, /* tp_as_mapping */
2472 0, /* tp_hash */
2473 0, /* tp_call */
2474 0, /* tp_str */
2475 PyObject_GenericGetAttr, /* tp_getattro */
2476 0, /* tp_setattro */
2477 0, /* tp_as_buffer */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002478 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Raymond Hettinger019a1482004-03-18 02:41:19 +00002479 0, /* tp_doc */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002480 (traverseproc)dictiter_traverse, /* tp_traverse */
Raymond Hettinger019a1482004-03-18 02:41:19 +00002481 0, /* tp_clear */
2482 0, /* tp_richcompare */
2483 0, /* tp_weaklistoffset */
2484 PyObject_SelfIter, /* tp_iter */
2485 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002486 dictiter_methods, /* tp_methods */
2487 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002488};
Guido van Rossumb90c8482007-02-10 01:11:45 +00002489
2490
Guido van Rossum3ac67412007-02-10 18:55:06 +00002491/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00002492/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00002493/***********************************************/
2494
Guido van Rossumb90c8482007-02-10 01:11:45 +00002495/* The instance lay-out is the same for all three; but the type differs. */
2496
2497typedef struct {
2498 PyObject_HEAD
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002499 PyDictObject *dv_dict;
Guido van Rossumb90c8482007-02-10 01:11:45 +00002500} dictviewobject;
2501
2502
2503static void
Guido van Rossum3ac67412007-02-10 18:55:06 +00002504dictview_dealloc(dictviewobject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00002505{
Guido van Rossum3ac67412007-02-10 18:55:06 +00002506 Py_XDECREF(dv->dv_dict);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002507 PyObject_GC_Del(dv);
2508}
2509
2510static int
2511dictview_traverse(dictviewobject *dv, visitproc visit, void *arg)
2512{
2513 Py_VISIT(dv->dv_dict);
2514 return 0;
Guido van Rossumb90c8482007-02-10 01:11:45 +00002515}
2516
Guido van Rossum83825ac2007-02-10 04:54:19 +00002517static Py_ssize_t
Guido van Rossum3ac67412007-02-10 18:55:06 +00002518dictview_len(dictviewobject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00002519{
2520 Py_ssize_t len = 0;
Guido van Rossum3ac67412007-02-10 18:55:06 +00002521 if (dv->dv_dict != NULL)
2522 len = dv->dv_dict->ma_used;
Guido van Rossum83825ac2007-02-10 04:54:19 +00002523 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00002524}
2525
2526static PyObject *
2527dictview_new(PyObject *dict, PyTypeObject *type)
2528{
Guido van Rossum3ac67412007-02-10 18:55:06 +00002529 dictviewobject *dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00002530 if (dict == NULL) {
2531 PyErr_BadInternalCall();
2532 return NULL;
2533 }
2534 if (!PyDict_Check(dict)) {
2535 /* XXX Get rid of this restriction later */
2536 PyErr_Format(PyExc_TypeError,
2537 "%s() requires a dict argument, not '%s'",
2538 type->tp_name, dict->ob_type->tp_name);
2539 return NULL;
2540 }
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002541 dv = PyObject_GC_New(dictviewobject, type);
Guido van Rossum3ac67412007-02-10 18:55:06 +00002542 if (dv == NULL)
Guido van Rossumb90c8482007-02-10 01:11:45 +00002543 return NULL;
2544 Py_INCREF(dict);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00002545 dv->dv_dict = (PyDictObject *)dict;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002546 _PyObject_GC_TRACK(dv);
Guido van Rossum3ac67412007-02-10 18:55:06 +00002547 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00002548}
2549
Neal Norwitze36f2ba2007-02-26 23:12:28 +00002550/* TODO(guido): The views objects are not complete:
2551
2552 * support more set operations
2553 * support arbitrary mappings?
2554 - either these should be static or exported in dictobject.h
2555 - if public then they should probably be in builtins
2556*/
2557
Guido van Rossumaac530c2007-08-24 22:33:45 +00002558/* Return 1 if self is a subset of other, iterating over self;
2559 0 if not; -1 if an error occurred. */
Guido van Rossumd9214d12007-02-12 02:23:40 +00002560static int
2561all_contained_in(PyObject *self, PyObject *other)
2562{
2563 PyObject *iter = PyObject_GetIter(self);
2564 int ok = 1;
2565
2566 if (iter == NULL)
2567 return -1;
2568 for (;;) {
2569 PyObject *next = PyIter_Next(iter);
2570 if (next == NULL) {
2571 if (PyErr_Occurred())
2572 ok = -1;
2573 break;
2574 }
2575 ok = PySequence_Contains(other, next);
2576 Py_DECREF(next);
2577 if (ok <= 0)
2578 break;
2579 }
2580 Py_DECREF(iter);
2581 return ok;
2582}
2583
2584static PyObject *
2585dictview_richcompare(PyObject *self, PyObject *other, int op)
2586{
Guido van Rossumaac530c2007-08-24 22:33:45 +00002587 Py_ssize_t len_self, len_other;
2588 int ok;
2589 PyObject *result;
2590
Guido van Rossumd9214d12007-02-12 02:23:40 +00002591 assert(self != NULL);
2592 assert(PyDictViewSet_Check(self));
2593 assert(other != NULL);
Guido van Rossumd9214d12007-02-12 02:23:40 +00002594
Guido van Rossumaac530c2007-08-24 22:33:45 +00002595 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other)) {
Guido van Rossumd9214d12007-02-12 02:23:40 +00002596 Py_INCREF(Py_NotImplemented);
2597 return Py_NotImplemented;
2598 }
Guido van Rossumaac530c2007-08-24 22:33:45 +00002599
2600 len_self = PyObject_Size(self);
2601 if (len_self < 0)
2602 return NULL;
2603 len_other = PyObject_Size(other);
2604 if (len_other < 0)
2605 return NULL;
2606
2607 ok = 0;
2608 switch(op) {
2609
2610 case Py_NE:
2611 case Py_EQ:
2612 if (len_self == len_other)
2613 ok = all_contained_in(self, other);
2614 if (op == Py_NE && ok >= 0)
2615 ok = !ok;
2616 break;
2617
2618 case Py_LT:
2619 if (len_self < len_other)
2620 ok = all_contained_in(self, other);
2621 break;
2622
2623 case Py_LE:
2624 if (len_self <= len_other)
2625 ok = all_contained_in(self, other);
2626 break;
2627
2628 case Py_GT:
2629 if (len_self > len_other)
2630 ok = all_contained_in(other, self);
2631 break;
2632
2633 case Py_GE:
2634 if (len_self >= len_other)
2635 ok = all_contained_in(other, self);
2636 break;
2637
2638 }
2639 if (ok < 0)
2640 return NULL;
2641 result = ok ? Py_True : Py_False;
2642 Py_INCREF(result);
2643 return result;
Guido van Rossumd9214d12007-02-12 02:23:40 +00002644}
2645
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00002646static PyObject *
2647dictview_repr(dictviewobject *dv)
2648{
2649 PyObject *seq;
2650 PyObject *result;
2651
2652 seq = PySequence_List((PyObject *)dv);
2653 if (seq == NULL)
2654 return NULL;
2655
2656 result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
2657 Py_DECREF(seq);
2658 return result;
2659}
2660
Guido van Rossum3ac67412007-02-10 18:55:06 +00002661/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00002662
2663static PyObject *
Guido van Rossum3ac67412007-02-10 18:55:06 +00002664dictkeys_iter(dictviewobject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00002665{
Guido van Rossum3ac67412007-02-10 18:55:06 +00002666 if (dv->dv_dict == NULL) {
Guido van Rossumb90c8482007-02-10 01:11:45 +00002667 Py_RETURN_NONE;
2668 }
Guido van Rossum3ac67412007-02-10 18:55:06 +00002669 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
2670}
2671
2672static int
2673dictkeys_contains(dictviewobject *dv, PyObject *obj)
2674{
2675 if (dv->dv_dict == NULL)
2676 return 0;
2677 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00002678}
2679
Guido van Rossum83825ac2007-02-10 04:54:19 +00002680static PySequenceMethods dictkeys_as_sequence = {
2681 (lenfunc)dictview_len, /* sq_length */
2682 0, /* sq_concat */
2683 0, /* sq_repeat */
2684 0, /* sq_item */
2685 0, /* sq_slice */
2686 0, /* sq_ass_item */
2687 0, /* sq_ass_slice */
Guido van Rossum3ac67412007-02-10 18:55:06 +00002688 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00002689};
2690
Guido van Rossum523259b2007-08-24 23:41:22 +00002691static PyObject*
2692dictviews_sub(PyObject* self, PyObject *other)
2693{
2694 PyObject *result = PySet_New(self);
2695 PyObject *tmp;
2696 if (result == NULL)
2697 return NULL;
2698
2699 tmp = PyObject_CallMethod(result, "difference_update", "O", other);
2700 if (tmp == NULL) {
2701 Py_DECREF(result);
2702 return NULL;
2703 }
2704
2705 Py_DECREF(tmp);
2706 return result;
2707}
2708
2709static PyObject*
2710dictviews_and(PyObject* self, PyObject *other)
2711{
2712 PyObject *result = PySet_New(self);
2713 PyObject *tmp;
2714 if (result == NULL)
2715 return NULL;
2716
2717 tmp = PyObject_CallMethod(result, "intersection_update", "O", other);
2718 if (tmp == NULL) {
2719 Py_DECREF(result);
2720 return NULL;
2721 }
2722
2723 Py_DECREF(tmp);
2724 return result;
2725}
2726
2727static PyObject*
2728dictviews_or(PyObject* self, PyObject *other)
2729{
2730 PyObject *result = PySet_New(self);
2731 PyObject *tmp;
2732 if (result == NULL)
2733 return NULL;
2734
2735 tmp = PyObject_CallMethod(result, "update", "O", other);
2736 if (tmp == NULL) {
2737 Py_DECREF(result);
2738 return NULL;
2739 }
2740
2741 Py_DECREF(tmp);
2742 return result;
2743}
2744
2745static PyObject*
2746dictviews_xor(PyObject* self, PyObject *other)
2747{
2748 PyObject *result = PySet_New(self);
2749 PyObject *tmp;
2750 if (result == NULL)
2751 return NULL;
2752
2753 tmp = PyObject_CallMethod(result, "symmetric_difference_update", "O",
2754 other);
2755 if (tmp == NULL) {
2756 Py_DECREF(result);
2757 return NULL;
2758 }
2759
2760 Py_DECREF(tmp);
2761 return result;
2762}
2763
2764static PyNumberMethods dictviews_as_number = {
2765 0, /*nb_add*/
2766 (binaryfunc)dictviews_sub, /*nb_subtract*/
2767 0, /*nb_multiply*/
2768 0, /*nb_remainder*/
2769 0, /*nb_divmod*/
2770 0, /*nb_power*/
2771 0, /*nb_negative*/
2772 0, /*nb_positive*/
2773 0, /*nb_absolute*/
2774 0, /*nb_bool*/
2775 0, /*nb_invert*/
2776 0, /*nb_lshift*/
2777 0, /*nb_rshift*/
2778 (binaryfunc)dictviews_and, /*nb_and*/
2779 (binaryfunc)dictviews_xor, /*nb_xor*/
2780 (binaryfunc)dictviews_or, /*nb_or*/
2781};
2782
Guido van Rossumb90c8482007-02-10 01:11:45 +00002783static PyMethodDef dictkeys_methods[] = {
Guido van Rossumb90c8482007-02-10 01:11:45 +00002784 {NULL, NULL} /* sentinel */
2785};
2786
2787PyTypeObject PyDictKeys_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002788 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumb90c8482007-02-10 01:11:45 +00002789 "dict_keys", /* tp_name */
2790 sizeof(dictviewobject), /* tp_basicsize */
2791 0, /* tp_itemsize */
2792 /* methods */
2793 (destructor)dictview_dealloc, /* tp_dealloc */
2794 0, /* tp_print */
2795 0, /* tp_getattr */
2796 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002797 0, /* tp_reserved */
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00002798 (reprfunc)dictview_repr, /* tp_repr */
Guido van Rossum523259b2007-08-24 23:41:22 +00002799 &dictviews_as_number, /* tp_as_number */
Guido van Rossum83825ac2007-02-10 04:54:19 +00002800 &dictkeys_as_sequence, /* tp_as_sequence */
Guido van Rossumb90c8482007-02-10 01:11:45 +00002801 0, /* tp_as_mapping */
2802 0, /* tp_hash */
2803 0, /* tp_call */
2804 0, /* tp_str */
2805 PyObject_GenericGetAttr, /* tp_getattro */
2806 0, /* tp_setattro */
2807 0, /* tp_as_buffer */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002808 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Guido van Rossumb90c8482007-02-10 01:11:45 +00002809 0, /* tp_doc */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002810 (traverseproc)dictview_traverse, /* tp_traverse */
Guido van Rossumb90c8482007-02-10 01:11:45 +00002811 0, /* tp_clear */
Guido van Rossumd9214d12007-02-12 02:23:40 +00002812 dictview_richcompare, /* tp_richcompare */
Guido van Rossumb90c8482007-02-10 01:11:45 +00002813 0, /* tp_weaklistoffset */
2814 (getiterfunc)dictkeys_iter, /* tp_iter */
2815 0, /* tp_iternext */
2816 dictkeys_methods, /* tp_methods */
2817 0,
2818};
2819
2820static PyObject *
2821dictkeys_new(PyObject *dict)
2822{
2823 return dictview_new(dict, &PyDictKeys_Type);
2824}
2825
Guido van Rossum3ac67412007-02-10 18:55:06 +00002826/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00002827
2828static PyObject *
Guido van Rossum3ac67412007-02-10 18:55:06 +00002829dictitems_iter(dictviewobject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00002830{
Guido van Rossum3ac67412007-02-10 18:55:06 +00002831 if (dv->dv_dict == NULL) {
Guido van Rossumb90c8482007-02-10 01:11:45 +00002832 Py_RETURN_NONE;
2833 }
Guido van Rossum3ac67412007-02-10 18:55:06 +00002834 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
2835}
2836
2837static int
2838dictitems_contains(dictviewobject *dv, PyObject *obj)
2839{
2840 PyObject *key, *value, *found;
2841 if (dv->dv_dict == NULL)
2842 return 0;
2843 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
2844 return 0;
2845 key = PyTuple_GET_ITEM(obj, 0);
2846 value = PyTuple_GET_ITEM(obj, 1);
2847 found = PyDict_GetItem((PyObject *)dv->dv_dict, key);
2848 if (found == NULL) {
2849 if (PyErr_Occurred())
2850 return -1;
2851 return 0;
2852 }
2853 return PyObject_RichCompareBool(value, found, Py_EQ);
Guido van Rossumb90c8482007-02-10 01:11:45 +00002854}
2855
Guido van Rossum83825ac2007-02-10 04:54:19 +00002856static PySequenceMethods dictitems_as_sequence = {
2857 (lenfunc)dictview_len, /* sq_length */
2858 0, /* sq_concat */
2859 0, /* sq_repeat */
2860 0, /* sq_item */
2861 0, /* sq_slice */
2862 0, /* sq_ass_item */
2863 0, /* sq_ass_slice */
Guido van Rossum3ac67412007-02-10 18:55:06 +00002864 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00002865};
2866
Guido van Rossumb90c8482007-02-10 01:11:45 +00002867static PyMethodDef dictitems_methods[] = {
Guido van Rossumb90c8482007-02-10 01:11:45 +00002868 {NULL, NULL} /* sentinel */
2869};
2870
2871PyTypeObject PyDictItems_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002872 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumb90c8482007-02-10 01:11:45 +00002873 "dict_items", /* tp_name */
2874 sizeof(dictviewobject), /* tp_basicsize */
2875 0, /* tp_itemsize */
2876 /* methods */
2877 (destructor)dictview_dealloc, /* tp_dealloc */
2878 0, /* tp_print */
2879 0, /* tp_getattr */
2880 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002881 0, /* tp_reserved */
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00002882 (reprfunc)dictview_repr, /* tp_repr */
Guido van Rossum523259b2007-08-24 23:41:22 +00002883 &dictviews_as_number, /* tp_as_number */
Guido van Rossum83825ac2007-02-10 04:54:19 +00002884 &dictitems_as_sequence, /* tp_as_sequence */
Guido van Rossumb90c8482007-02-10 01:11:45 +00002885 0, /* tp_as_mapping */
2886 0, /* tp_hash */
2887 0, /* tp_call */
2888 0, /* tp_str */
2889 PyObject_GenericGetAttr, /* tp_getattro */
2890 0, /* tp_setattro */
2891 0, /* tp_as_buffer */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002892 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Guido van Rossumb90c8482007-02-10 01:11:45 +00002893 0, /* tp_doc */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002894 (traverseproc)dictview_traverse, /* tp_traverse */
Guido van Rossumb90c8482007-02-10 01:11:45 +00002895 0, /* tp_clear */
Guido van Rossumd9214d12007-02-12 02:23:40 +00002896 dictview_richcompare, /* tp_richcompare */
Guido van Rossumb90c8482007-02-10 01:11:45 +00002897 0, /* tp_weaklistoffset */
2898 (getiterfunc)dictitems_iter, /* tp_iter */
2899 0, /* tp_iternext */
2900 dictitems_methods, /* tp_methods */
2901 0,
2902};
2903
2904static PyObject *
2905dictitems_new(PyObject *dict)
2906{
2907 return dictview_new(dict, &PyDictItems_Type);
2908}
2909
Guido van Rossum3ac67412007-02-10 18:55:06 +00002910/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00002911
2912static PyObject *
Guido van Rossum3ac67412007-02-10 18:55:06 +00002913dictvalues_iter(dictviewobject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00002914{
Guido van Rossum3ac67412007-02-10 18:55:06 +00002915 if (dv->dv_dict == NULL) {
Guido van Rossumb90c8482007-02-10 01:11:45 +00002916 Py_RETURN_NONE;
2917 }
Guido van Rossum3ac67412007-02-10 18:55:06 +00002918 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00002919}
2920
Guido van Rossum83825ac2007-02-10 04:54:19 +00002921static PySequenceMethods dictvalues_as_sequence = {
2922 (lenfunc)dictview_len, /* sq_length */
2923 0, /* sq_concat */
2924 0, /* sq_repeat */
2925 0, /* sq_item */
2926 0, /* sq_slice */
2927 0, /* sq_ass_item */
2928 0, /* sq_ass_slice */
2929 (objobjproc)0, /* sq_contains */
2930};
2931
Guido van Rossumb90c8482007-02-10 01:11:45 +00002932static PyMethodDef dictvalues_methods[] = {
Guido van Rossumb90c8482007-02-10 01:11:45 +00002933 {NULL, NULL} /* sentinel */
2934};
2935
2936PyTypeObject PyDictValues_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002937 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumb90c8482007-02-10 01:11:45 +00002938 "dict_values", /* tp_name */
2939 sizeof(dictviewobject), /* tp_basicsize */
2940 0, /* tp_itemsize */
2941 /* methods */
2942 (destructor)dictview_dealloc, /* tp_dealloc */
2943 0, /* tp_print */
2944 0, /* tp_getattr */
2945 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002946 0, /* tp_reserved */
Raymond Hettingerb0d56af2009-03-03 10:52:49 +00002947 (reprfunc)dictview_repr, /* tp_repr */
Guido van Rossumb90c8482007-02-10 01:11:45 +00002948 0, /* tp_as_number */
Guido van Rossum83825ac2007-02-10 04:54:19 +00002949 &dictvalues_as_sequence, /* tp_as_sequence */
Guido van Rossumb90c8482007-02-10 01:11:45 +00002950 0, /* tp_as_mapping */
2951 0, /* tp_hash */
2952 0, /* tp_call */
2953 0, /* tp_str */
2954 PyObject_GenericGetAttr, /* tp_getattro */
2955 0, /* tp_setattro */
2956 0, /* tp_as_buffer */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002957 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Guido van Rossumb90c8482007-02-10 01:11:45 +00002958 0, /* tp_doc */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00002959 (traverseproc)dictview_traverse, /* tp_traverse */
Guido van Rossumb90c8482007-02-10 01:11:45 +00002960 0, /* tp_clear */
2961 0, /* tp_richcompare */
2962 0, /* tp_weaklistoffset */
2963 (getiterfunc)dictvalues_iter, /* tp_iter */
2964 0, /* tp_iternext */
2965 dictvalues_methods, /* tp_methods */
2966 0,
2967};
2968
2969static PyObject *
2970dictvalues_new(PyObject *dict)
2971{
2972 return dictview_new(dict, &PyDictValues_Type);
2973}