blob: ffa7a86fb3322fb2049176e24563f6f809ca61af [file] [log] [blame]
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001
Guido van Rossum2bc13791999-03-24 19:06:42 +00002/* Dictionary object implementation using a hash table */
Guido van Rossum9bfef441993-03-29 10:43:31 +00003
Raymond Hettinger930427b2003-05-03 06:51:59 +00004/* The distribution includes a separate file, Objects/dictnotes.txt,
Tim Peters60b29962006-01-01 01:19:23 +00005 describing explorations into dictionary design and optimization.
Raymond Hettinger930427b2003-05-03 06:51:59 +00006 It covers typical dictionary use patterns, the parameters for
7 tuning dictionaries, and several ideas for possible optimizations.
8*/
9
Guido van Rossumc0b618a1997-05-02 03:12:38 +000010#include "Python.h"
Guido van Rossum4b1302b1993-03-27 18:11:32 +000011
Tim Peters6d6c1a32001-08-02 04:15:00 +000012typedef PyDictEntry dictentry;
13typedef PyDictObject dictobject;
Guido van Rossum16e93a81997-01-28 00:00:11 +000014
Thomas Wouters89f507f2006-12-13 04:49:30 +000015/* Set a key error with the specified argument, wrapping it in a
16 * tuple automatically so that tuple keys are not unpacked as the
17 * exception arguments. */
18static void
19set_key_error(PyObject *arg)
20{
21 PyObject *tup;
22 tup = PyTuple_Pack(1, arg);
23 if (!tup)
24 return; /* caller will expect error to be set anyway */
25 PyErr_SetObject(PyExc_KeyError, tup);
26 Py_DECREF(tup);
27}
28
Tim Peterseb28ef22001-06-02 05:27:19 +000029/* Define this out if you don't want conversion statistics on exit. */
Fred Drake1bff34a2000-08-31 19:31:38 +000030#undef SHOW_CONVERSION_COUNTS
31
Tim Peterseb28ef22001-06-02 05:27:19 +000032/* See large comment block below. This must be >= 1. */
33#define PERTURB_SHIFT 5
34
Guido van Rossum16e93a81997-01-28 00:00:11 +000035/*
Tim Peterseb28ef22001-06-02 05:27:19 +000036Major subtleties ahead: Most hash schemes depend on having a "good" hash
37function, in the sense of simulating randomness. Python doesn't: its most
38important hash functions (for strings and ints) are very regular in common
39cases:
Tim Peters15d49292001-05-27 07:39:22 +000040
Guido van Rossumdc5f6b22006-08-24 21:29:26 +000041 >>> map(hash, (0, 1, 2, 3))
42 [0, 1, 2, 3]
43 >>> map(hash, ("namea", "nameb", "namec", "named"))
44 [-1658398457, -1658398460, -1658398459, -1658398462]
45 >>>
Tim Peters15d49292001-05-27 07:39:22 +000046
Tim Peterseb28ef22001-06-02 05:27:19 +000047This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
48the low-order i bits as the initial table index is extremely fast, and there
49are no collisions at all for dicts indexed by a contiguous range of ints.
50The same is approximately true when keys are "consecutive" strings. So this
51gives better-than-random behavior in common cases, and that's very desirable.
Tim Peters15d49292001-05-27 07:39:22 +000052
Tim Peterseb28ef22001-06-02 05:27:19 +000053OTOH, when collisions occur, the tendency to fill contiguous slices of the
54hash table makes a good collision resolution strategy crucial. Taking only
55the last i bits of the hash code is also vulnerable: for example, consider
Guido van Rossumdc5f6b22006-08-24 21:29:26 +000056the list [i << 16 for i in range(20000)] as a set of keys. Since ints are
57their own hash codes, and this fits in a dict of size 2**15, the last 15 bits
58 of every hash code are all 0: they *all* map to the same table index.
Tim Peters15d49292001-05-27 07:39:22 +000059
Tim Peterseb28ef22001-06-02 05:27:19 +000060But catering to unusual cases should not slow the usual ones, so we just take
61the last i bits anyway. It's up to collision resolution to do the rest. If
62we *usually* find the key we're looking for on the first try (and, it turns
63out, we usually do -- the table load factor is kept under 2/3, so the odds
64are solidly in our favor), then it makes best sense to keep the initial index
65computation dirt cheap.
Tim Peters15d49292001-05-27 07:39:22 +000066
Tim Peterseb28ef22001-06-02 05:27:19 +000067The first half of collision resolution is to visit table indices via this
68recurrence:
Tim Peters15d49292001-05-27 07:39:22 +000069
Tim Peterseb28ef22001-06-02 05:27:19 +000070 j = ((5*j) + 1) mod 2**i
Tim Peters15d49292001-05-27 07:39:22 +000071
Tim Peterseb28ef22001-06-02 05:27:19 +000072For any initial j in range(2**i), repeating that 2**i times generates each
73int in range(2**i) exactly once (see any text on random-number generation for
74proof). By itself, this doesn't help much: like linear probing (setting
75j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
76order. This would be bad, except that's not the only thing we do, and it's
77actually *good* in the common cases where hash keys are consecutive. In an
78example that's really too small to make this entirely clear, for a table of
79size 2**3 the order of indices is:
Tim Peters15d49292001-05-27 07:39:22 +000080
Tim Peterseb28ef22001-06-02 05:27:19 +000081 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
82
83If two things come in at index 5, the first place we look after is index 2,
84not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
85Linear probing is deadly in this case because there the fixed probe order
86is the *same* as the order consecutive keys are likely to arrive. But it's
87extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
88and certain that consecutive hash codes do not.
89
90The other half of the strategy is to get the other bits of the hash code
91into play. This is done by initializing a (unsigned) vrbl "perturb" to the
92full hash code, and changing the recurrence to:
93
94 j = (5*j) + 1 + perturb;
95 perturb >>= PERTURB_SHIFT;
96 use j % 2**i as the next table index;
97
98Now the probe sequence depends (eventually) on every bit in the hash code,
99and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
100because it quickly magnifies small differences in the bits that didn't affect
101the initial index. Note that because perturb is unsigned, if the recurrence
102is executed often enough perturb eventually becomes and remains 0. At that
103point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
104that's certain to find an empty slot eventually (since it generates every int
105in range(2**i), and we make sure there's always at least one empty slot).
106
107Selecting a good value for PERTURB_SHIFT is a balancing act. You want it
108small so that the high bits of the hash code continue to affect the probe
109sequence across iterations; but you want it large so that in really bad cases
110the high-order hash bits have an effect on early iterations. 5 was "the
111best" in minimizing total collisions across experiments Tim Peters ran (on
112both normal and pathological cases), but 4 and 6 weren't significantly worse.
113
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000114Historical: Reimer Behrends contributed the idea of using a polynomial-based
Tim Peterseb28ef22001-06-02 05:27:19 +0000115approach, using repeated multiplication by x in GF(2**n) where an irreducible
116polynomial for each table size was chosen such that x was a primitive root.
117Christian Tismer later extended that to use division by x instead, as an
118efficient way to get the high bits of the hash code into play. This scheme
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000119also gave excellent collision statistics, but was more expensive: two if-tests
120were required inside the loop; computing "the next" index took about the same
121number of operations but without as much potential parallelism (e.g.,
122computing 5*j can go on at the same time as computing 1+perturb in the above,
123and then shifting perturb can be done while the table index is being masked);
124and the dictobject struct required a member to hold the table's polynomial.
125In Tim's experiments the current scheme ran faster, produced equally good
126collision statistics, needed less code & used less memory.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000127
128Theoretical Python 2.5 headache: hash codes are only C "long", but
129sizeof(Py_ssize_t) > sizeof(long) may be possible. In that case, and if a
130dict is genuinely huge, then only the slots directly reachable via indexing
131by a C long can be the first slot in a probe sequence. The probe sequence
132will still eventually reach every slot in the table, but the collision rate
133on initial probes may be much higher than this scheme was designed for.
134Getting a hash code as fat as Py_ssize_t is the only real cure. But in
135practice, this probably won't make a lick of difference for many years (at
136which point everyone will have terabytes of RAM on 64-bit boxes).
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000137*/
Tim Petersdea48ec2001-05-22 20:40:22 +0000138
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000139/* Object used as dummy key to fill deleted entries */
Raymond Hettingerf81e4502005-08-17 02:19:36 +0000140static PyObject *dummy = NULL; /* Initialized by first call to newdictobject() */
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000141
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000142#ifdef Py_REF_DEBUG
143PyObject *
144_PyDict_Dummy(void)
145{
146 return dummy;
147}
148#endif
149
Fred Drake1bff34a2000-08-31 19:31:38 +0000150/* forward declarations */
151static dictentry *
152lookdict_string(dictobject *mp, PyObject *key, long hash);
153
154#ifdef SHOW_CONVERSION_COUNTS
155static long created = 0L;
156static long converted = 0L;
157
158static void
159show_counts(void)
160{
161 fprintf(stderr, "created %ld string dicts\n", created);
162 fprintf(stderr, "converted %ld to normal dicts\n", converted);
163 fprintf(stderr, "%.2f%% conversion rate\n", (100.0*converted)/created);
164}
165#endif
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000166
Tim Peters6d6c1a32001-08-02 04:15:00 +0000167/* Initialization macros.
168 There are two ways to create a dict: PyDict_New() is the main C API
169 function, and the tp_new slot maps to dict_new(). In the latter case we
170 can save a little time over what PyDict_New does because it's guaranteed
171 that the PyDictObject struct is already zeroed out.
172 Everyone except dict_new() should use EMPTY_TO_MINSIZE (unless they have
173 an excellent reason not to).
174*/
175
176#define INIT_NONZERO_DICT_SLOTS(mp) do { \
Tim Petersdea48ec2001-05-22 20:40:22 +0000177 (mp)->ma_table = (mp)->ma_smalltable; \
Tim Peters6d6c1a32001-08-02 04:15:00 +0000178 (mp)->ma_mask = PyDict_MINSIZE - 1; \
179 } while(0)
180
181#define EMPTY_TO_MINSIZE(mp) do { \
182 memset((mp)->ma_smalltable, 0, sizeof((mp)->ma_smalltable)); \
Tim Petersdea48ec2001-05-22 20:40:22 +0000183 (mp)->ma_used = (mp)->ma_fill = 0; \
Tim Peters6d6c1a32001-08-02 04:15:00 +0000184 INIT_NONZERO_DICT_SLOTS(mp); \
Tim Petersdea48ec2001-05-22 20:40:22 +0000185 } while(0)
186
Raymond Hettinger43442782004-03-17 21:55:03 +0000187/* Dictionary reuse scheme to save calls to malloc, free, and memset */
188#define MAXFREEDICTS 80
189static PyDictObject *free_dicts[MAXFREEDICTS];
190static int num_free_dicts = 0;
191
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000192PyObject *
Thomas Wouters78890102000-07-22 19:25:51 +0000193PyDict_New(void)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000194{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000195 register dictobject *mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000196 if (dummy == NULL) { /* Auto-initialize dummy */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000197 dummy = PyString_FromString("<dummy key>");
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000198 if (dummy == NULL)
199 return NULL;
Fred Drake1bff34a2000-08-31 19:31:38 +0000200#ifdef SHOW_CONVERSION_COUNTS
201 Py_AtExit(show_counts);
202#endif
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000203 }
Raymond Hettinger43442782004-03-17 21:55:03 +0000204 if (num_free_dicts) {
205 mp = free_dicts[--num_free_dicts];
206 assert (mp != NULL);
207 assert (mp->ob_type == &PyDict_Type);
208 _Py_NewReference((PyObject *)mp);
209 if (mp->ma_fill) {
210 EMPTY_TO_MINSIZE(mp);
211 }
212 assert (mp->ma_used == 0);
213 assert (mp->ma_table == mp->ma_smalltable);
214 assert (mp->ma_mask == PyDict_MINSIZE - 1);
215 } else {
216 mp = PyObject_GC_New(dictobject, &PyDict_Type);
217 if (mp == NULL)
218 return NULL;
219 EMPTY_TO_MINSIZE(mp);
220 }
Fred Drake1bff34a2000-08-31 19:31:38 +0000221 mp->ma_lookup = lookdict_string;
222#ifdef SHOW_CONVERSION_COUNTS
223 ++created;
224#endif
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000225 _PyObject_GC_TRACK(mp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000226 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000227}
228
229/*
230The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000231This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000232Open addressing is preferred over chaining since the link overhead for
233chaining would be substantial (100% with typical malloc overhead).
234
Tim Peterseb28ef22001-06-02 05:27:19 +0000235The initial probe index is computed as hash mod the table size. Subsequent
236probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000237
238All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000239
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000240The details in this version are due to Tim Peters, building on many past
Tim Peterseb28ef22001-06-02 05:27:19 +0000241contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Guido van Rossumdc5f6b22006-08-24 21:29:26 +0000242Christian Tismer.
Fred Drake1bff34a2000-08-31 19:31:38 +0000243
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000244lookdict() is general-purpose, and may return NULL if (and only if) a
245comparison raises an exception (this was new in Python 2.5).
246lookdict_string() below is specialized to string keys, comparison of which can
247never raise an exception; that function can never return NULL. For both, when
248the key isn't found a dictentry* is returned for which the me_value field is
249NULL; this is the slot in the dict at which the key would have been found, and
250the caller can (if it wishes) add the <key, value> pair to the returned
251dictentry*.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000252*/
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000253static dictentry *
Tim Peters1f5871e2000-07-04 17:44:48 +0000254lookdict(dictobject *mp, PyObject *key, register long hash)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000255{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000256 register size_t i;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000257 register size_t perturb;
Guido van Rossumfd7a0b81997-08-18 21:52:47 +0000258 register dictentry *freeslot;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000259 register size_t mask = (size_t)mp->ma_mask;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000260 dictentry *ep0 = mp->ma_table;
261 register dictentry *ep;
Fred Drakec88b99c2000-08-31 19:04:07 +0000262 register int cmp;
Tim Peters453163d2001-06-03 04:54:32 +0000263 PyObject *startkey;
Tim Peterseb28ef22001-06-02 05:27:19 +0000264
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000265 i = (size_t)hash & mask;
Guido van Rossumefb46091997-01-29 15:53:56 +0000266 ep = &ep0[i];
Guido van Rossumc1c7b1a1998-10-06 16:01:14 +0000267 if (ep->me_key == NULL || ep->me_key == key)
Guido van Rossum7d181591997-01-16 21:06:45 +0000268 return ep;
Tim Peters7b5d0af2001-06-03 04:14:43 +0000269
Guido van Rossum16e93a81997-01-28 00:00:11 +0000270 if (ep->me_key == dummy)
Guido van Rossum7d181591997-01-16 21:06:45 +0000271 freeslot = ep;
Guido van Rossumfd7a0b81997-08-18 21:52:47 +0000272 else {
Fred Drakec88b99c2000-08-31 19:04:07 +0000273 if (ep->me_hash == hash) {
Tim Peters453163d2001-06-03 04:54:32 +0000274 startkey = ep->me_key;
275 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
Tim Peters7b5d0af2001-06-03 04:14:43 +0000276 if (cmp < 0)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000277 return NULL;
Tim Peters453163d2001-06-03 04:54:32 +0000278 if (ep0 == mp->ma_table && ep->me_key == startkey) {
279 if (cmp > 0)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000280 return ep;
Tim Peters453163d2001-06-03 04:54:32 +0000281 }
282 else {
283 /* The compare did major nasty stuff to the
284 * dict: start over.
285 * XXX A clever adversary could prevent this
286 * XXX from terminating.
287 */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000288 return lookdict(mp, key, hash);
Tim Peters453163d2001-06-03 04:54:32 +0000289 }
Guido van Rossumfd7a0b81997-08-18 21:52:47 +0000290 }
291 freeslot = NULL;
Guido van Rossum2a61e741997-01-18 07:55:05 +0000292 }
Tim Peters15d49292001-05-27 07:39:22 +0000293
Tim Peters342c65e2001-05-13 06:43:53 +0000294 /* In the loop, me_key == dummy is by far (factor of 100s) the
295 least likely outcome, so test for that last. */
Tim Peterseb28ef22001-06-02 05:27:19 +0000296 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
297 i = (i << 2) + i + perturb + 1;
298 ep = &ep0[i & mask];
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000299 if (ep->me_key == NULL)
300 return freeslot == NULL ? ep : freeslot;
Tim Peters7b5d0af2001-06-03 04:14:43 +0000301 if (ep->me_key == key)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000302 return ep;
Tim Peters7b5d0af2001-06-03 04:14:43 +0000303 if (ep->me_hash == hash && ep->me_key != dummy) {
Tim Peters453163d2001-06-03 04:54:32 +0000304 startkey = ep->me_key;
305 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
Tim Peters7b5d0af2001-06-03 04:14:43 +0000306 if (cmp < 0)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000307 return NULL;
Tim Peters453163d2001-06-03 04:54:32 +0000308 if (ep0 == mp->ma_table && ep->me_key == startkey) {
309 if (cmp > 0)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000310 return ep;
Tim Peters453163d2001-06-03 04:54:32 +0000311 }
312 else {
313 /* The compare did major nasty stuff to the
314 * dict: start over.
315 * XXX A clever adversary could prevent this
316 * XXX from terminating.
317 */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000318 return lookdict(mp, key, hash);
Tim Peters453163d2001-06-03 04:54:32 +0000319 }
Guido van Rossum16e93a81997-01-28 00:00:11 +0000320 }
Tim Peters342c65e2001-05-13 06:43:53 +0000321 else if (ep->me_key == dummy && freeslot == NULL)
322 freeslot = ep;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000323 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000324 assert(0); /* NOT REACHED */
325 return 0;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000326}
327
328/*
Fred Drake1bff34a2000-08-31 19:31:38 +0000329 * Hacked up version of lookdict which can assume keys are always strings;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000330 * this assumption allows testing for errors during PyObject_RichCompareBool()
331 * to be dropped; string-string comparisons never raise exceptions. This also
332 * means we don't need to go through PyObject_RichCompareBool(); we can always
333 * use _PyString_Eq() directly.
Fred Drake1bff34a2000-08-31 19:31:38 +0000334 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000335 * This is valuable because dicts with only string keys are very common.
Fred Drake1bff34a2000-08-31 19:31:38 +0000336 */
337static dictentry *
338lookdict_string(dictobject *mp, PyObject *key, register long hash)
339{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000340 register size_t i;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000341 register size_t perturb;
Fred Drake1bff34a2000-08-31 19:31:38 +0000342 register dictentry *freeslot;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000343 register size_t mask = (size_t)mp->ma_mask;
Fred Drake1bff34a2000-08-31 19:31:38 +0000344 dictentry *ep0 = mp->ma_table;
345 register dictentry *ep;
Fred Drake1bff34a2000-08-31 19:31:38 +0000346
Tim Peters0ab085c2001-09-14 00:25:33 +0000347 /* Make sure this function doesn't have to handle non-string keys,
348 including subclasses of str; e.g., one reason to subclass
349 strings is to override __eq__, and for speed we don't cater to
350 that here. */
351 if (!PyString_CheckExact(key)) {
Fred Drake1bff34a2000-08-31 19:31:38 +0000352#ifdef SHOW_CONVERSION_COUNTS
353 ++converted;
354#endif
355 mp->ma_lookup = lookdict;
356 return lookdict(mp, key, hash);
357 }
Tim Peters2f228e72001-05-13 00:19:31 +0000358 i = hash & mask;
Fred Drake1bff34a2000-08-31 19:31:38 +0000359 ep = &ep0[i];
360 if (ep->me_key == NULL || ep->me_key == key)
361 return ep;
362 if (ep->me_key == dummy)
363 freeslot = ep;
364 else {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000365 if (ep->me_hash == hash && _PyString_Eq(ep->me_key, key))
Fred Drake1bff34a2000-08-31 19:31:38 +0000366 return ep;
Fred Drake1bff34a2000-08-31 19:31:38 +0000367 freeslot = NULL;
368 }
Tim Peters15d49292001-05-27 07:39:22 +0000369
Tim Peters342c65e2001-05-13 06:43:53 +0000370 /* In the loop, me_key == dummy is by far (factor of 100s) the
371 least likely outcome, so test for that last. */
Tim Peterseb28ef22001-06-02 05:27:19 +0000372 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
373 i = (i << 2) + i + perturb + 1;
374 ep = &ep0[i & mask];
Tim Peters342c65e2001-05-13 06:43:53 +0000375 if (ep->me_key == NULL)
376 return freeslot == NULL ? ep : freeslot;
377 if (ep->me_key == key
378 || (ep->me_hash == hash
379 && ep->me_key != dummy
Martin v. Löwiscd353062001-05-24 16:56:35 +0000380 && _PyString_Eq(ep->me_key, key)))
Fred Drake1bff34a2000-08-31 19:31:38 +0000381 return ep;
Tim Petersdea48ec2001-05-22 20:40:22 +0000382 if (ep->me_key == dummy && freeslot == NULL)
Tim Peters342c65e2001-05-13 06:43:53 +0000383 freeslot = ep;
Fred Drake1bff34a2000-08-31 19:31:38 +0000384 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000385 assert(0); /* NOT REACHED */
386 return 0;
Fred Drake1bff34a2000-08-31 19:31:38 +0000387}
388
389/*
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000390Internal routine to insert a new item into the table.
391Used both by the internal resize routine and by the public insert routine.
392Eats a reference to key and one to value.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000393Returns -1 if an error occurred, or 0 on success.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000394*/
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000395static int
Tim Peters1f5871e2000-07-04 17:44:48 +0000396insertdict(register dictobject *mp, PyObject *key, long hash, PyObject *value)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000397{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000398 PyObject *old_value;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000399 register dictentry *ep;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000400 typedef PyDictEntry *(*lookupfunc)(PyDictObject *, PyObject *, long);
401
402 assert(mp->ma_lookup != NULL);
403 ep = mp->ma_lookup(mp, key, hash);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000404 if (ep == NULL) {
405 Py_DECREF(key);
406 Py_DECREF(value);
407 return -1;
408 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000409 if (ep->me_value != NULL) {
Guido van Rossumd7047b31995-01-02 19:07:15 +0000410 old_value = ep->me_value;
411 ep->me_value = value;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000412 Py_DECREF(old_value); /* which **CAN** re-enter */
413 Py_DECREF(key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000414 }
415 else {
416 if (ep->me_key == NULL)
417 mp->ma_fill++;
Raymond Hettinger07ead172005-02-05 23:42:57 +0000418 else {
419 assert(ep->me_key == dummy);
420 Py_DECREF(dummy);
421 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000422 ep->me_key = key;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000423 ep->me_hash = (Py_ssize_t)hash;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000424 ep->me_value = value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000425 mp->ma_used++;
426 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000427 return 0;
428}
429
430/*
431Internal routine used by dictresize() to insert an item which is
432known to be absent from the dict. This routine also assumes that
433the dict contains no deleted entries. Besides the performance benefit,
434using insertdict() in dictresize() is dangerous (SF bug #1456209).
435Note that no refcounts are changed by this routine; if needed, the caller
436is responsible for incref'ing `key` and `value`.
437*/
438static void
439insertdict_clean(register dictobject *mp, PyObject *key, long hash,
440 PyObject *value)
441{
442 register size_t i;
443 register size_t perturb;
444 register size_t mask = (size_t)mp->ma_mask;
445 dictentry *ep0 = mp->ma_table;
446 register dictentry *ep;
447
448 i = hash & mask;
449 ep = &ep0[i];
450 for (perturb = hash; ep->me_key != NULL; perturb >>= PERTURB_SHIFT) {
451 i = (i << 2) + i + perturb + 1;
452 ep = &ep0[i & mask];
453 }
454 assert(ep->me_value == NULL);
455 mp->ma_fill++;
456 ep->me_key = key;
457 ep->me_hash = (Py_ssize_t)hash;
458 ep->me_value = value;
459 mp->ma_used++;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000460}
461
462/*
463Restructure the table by allocating a new table and reinserting all
464items again. When entries have been deleted, the new table may
465actually be smaller than the old one.
466*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000467static int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000468dictresize(dictobject *mp, Py_ssize_t minused)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000469{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000470 Py_ssize_t newsize;
Tim Peters0c6010b2001-05-23 23:33:57 +0000471 dictentry *oldtable, *newtable, *ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000472 Py_ssize_t i;
Tim Peters0c6010b2001-05-23 23:33:57 +0000473 int is_oldtable_malloced;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000474 dictentry small_copy[PyDict_MINSIZE];
Tim Peters91a364d2001-05-19 07:04:38 +0000475
476 assert(minused >= 0);
Tim Peters0c6010b2001-05-23 23:33:57 +0000477
Tim Peterseb28ef22001-06-02 05:27:19 +0000478 /* Find the smallest table size > minused. */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000479 for (newsize = PyDict_MINSIZE;
Tim Peterseb28ef22001-06-02 05:27:19 +0000480 newsize <= minused && newsize > 0;
481 newsize <<= 1)
482 ;
483 if (newsize <= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000484 PyErr_NoMemory();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000485 return -1;
486 }
Tim Peters0c6010b2001-05-23 23:33:57 +0000487
488 /* Get space for a new table. */
489 oldtable = mp->ma_table;
490 assert(oldtable != NULL);
491 is_oldtable_malloced = oldtable != mp->ma_smalltable;
492
Tim Peters6d6c1a32001-08-02 04:15:00 +0000493 if (newsize == PyDict_MINSIZE) {
Tim Petersf8a548c2001-05-24 16:26:40 +0000494 /* A large table is shrinking, or we can't get any smaller. */
Tim Petersdea48ec2001-05-22 20:40:22 +0000495 newtable = mp->ma_smalltable;
Tim Peters0c6010b2001-05-23 23:33:57 +0000496 if (newtable == oldtable) {
Tim Petersf8a548c2001-05-24 16:26:40 +0000497 if (mp->ma_fill == mp->ma_used) {
498 /* No dummies, so no point doing anything. */
Tim Peters0c6010b2001-05-23 23:33:57 +0000499 return 0;
Tim Petersf8a548c2001-05-24 16:26:40 +0000500 }
501 /* We're not going to resize it, but rebuild the
502 table anyway to purge old dummy entries.
503 Subtle: This is *necessary* if fill==size,
504 as lookdict needs at least one virgin slot to
505 terminate failing searches. If fill < size, it's
506 merely desirable, as dummies slow searches. */
507 assert(mp->ma_fill > mp->ma_used);
Tim Peters0c6010b2001-05-23 23:33:57 +0000508 memcpy(small_copy, oldtable, sizeof(small_copy));
509 oldtable = small_copy;
510 }
Tim Petersdea48ec2001-05-22 20:40:22 +0000511 }
512 else {
513 newtable = PyMem_NEW(dictentry, newsize);
514 if (newtable == NULL) {
515 PyErr_NoMemory();
516 return -1;
517 }
518 }
Tim Peters0c6010b2001-05-23 23:33:57 +0000519
520 /* Make the dict empty, using the new table. */
Tim Petersdea48ec2001-05-22 20:40:22 +0000521 assert(newtable != oldtable);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000522 mp->ma_table = newtable;
Tim Petersafb6ae82001-06-04 21:00:21 +0000523 mp->ma_mask = newsize - 1;
Tim Petersdea48ec2001-05-22 20:40:22 +0000524 memset(newtable, 0, sizeof(dictentry) * newsize);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000525 mp->ma_used = 0;
Tim Petersdea48ec2001-05-22 20:40:22 +0000526 i = mp->ma_fill;
527 mp->ma_fill = 0;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000528
Tim Peters19283142001-05-17 22:25:34 +0000529 /* Copy the data over; this is refcount-neutral for active entries;
530 dummy entries aren't copied over, of course */
Tim Petersdea48ec2001-05-22 20:40:22 +0000531 for (ep = oldtable; i > 0; ep++) {
532 if (ep->me_value != NULL) { /* active entry */
533 --i;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000534 insertdict_clean(mp, ep->me_key, (long)ep->me_hash,
535 ep->me_value);
Tim Petersdea48ec2001-05-22 20:40:22 +0000536 }
Tim Peters19283142001-05-17 22:25:34 +0000537 else if (ep->me_key != NULL) { /* dummy entry */
Tim Petersdea48ec2001-05-22 20:40:22 +0000538 --i;
Tim Peters19283142001-05-17 22:25:34 +0000539 assert(ep->me_key == dummy);
540 Py_DECREF(ep->me_key);
Guido van Rossum255443b1998-04-10 22:47:14 +0000541 }
Tim Peters19283142001-05-17 22:25:34 +0000542 /* else key == value == NULL: nothing to do */
Guido van Rossumd7047b31995-01-02 19:07:15 +0000543 }
544
Tim Peters0c6010b2001-05-23 23:33:57 +0000545 if (is_oldtable_malloced)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000546 PyMem_DEL(oldtable);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000547 return 0;
548}
549
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000550/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
551 * that may occur (originally dicts supported only string keys, and exceptions
552 * weren't possible). So, while the original intent was that a NULL return
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000553 * meant the key wasn't present, in reality it can mean that, or that an error
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000554 * (suppressed) occurred while computing the key's hash, or that some error
555 * (suppressed) occurred when comparing keys in the dict's internal probe
556 * sequence. A nasty example of the latter is when a Python-coded comparison
557 * function hits a stack-depth error, which can cause this to return NULL
558 * even if the key is present.
559 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000560PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000561PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000562{
563 long hash;
Fred Drake1bff34a2000-08-31 19:31:38 +0000564 dictobject *mp = (dictobject *)op;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000565 dictentry *ep;
566 PyThreadState *tstate;
567 if (!PyDict_Check(op))
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000568 return NULL;
Tim Peters0ab085c2001-09-14 00:25:33 +0000569 if (!PyString_CheckExact(key) ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000570 (hash = ((PyStringObject *) key)->ob_shash) == -1)
Guido van Rossumca756f21997-01-23 19:39:29 +0000571 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000572 hash = PyObject_Hash(key);
Guido van Rossum474b19e1998-05-14 01:00:51 +0000573 if (hash == -1) {
574 PyErr_Clear();
Guido van Rossumca756f21997-01-23 19:39:29 +0000575 return NULL;
Guido van Rossum474b19e1998-05-14 01:00:51 +0000576 }
Guido van Rossumca756f21997-01-23 19:39:29 +0000577 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000578
579 /* We can arrive here with a NULL tstate during initialization:
580 try running "python -Wi" for an example related to string
581 interning. Let's just hope that no exception occurs then... */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000582 tstate = _PyThreadState_Current;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000583 if (tstate != NULL && tstate->curexc_type != NULL) {
584 /* preserve the existing exception */
585 PyObject *err_type, *err_value, *err_tb;
586 PyErr_Fetch(&err_type, &err_value, &err_tb);
587 ep = (mp->ma_lookup)(mp, key, hash);
588 /* ignore errors */
589 PyErr_Restore(err_type, err_value, err_tb);
590 if (ep == NULL)
591 return NULL;
592 }
593 else {
594 ep = (mp->ma_lookup)(mp, key, hash);
595 if (ep == NULL) {
596 PyErr_Clear();
597 return NULL;
598 }
599 }
600 return ep->me_value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000601}
602
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000603/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
604 This returns NULL *with* an exception set if an exception occurred.
605 It returns NULL *without* an exception set if the key wasn't present.
606*/
607PyObject *
608PyDict_GetItemWithError(PyObject *op, PyObject *key)
609{
610 long hash;
611 dictobject *mp = (dictobject *)op;
612 dictentry *ep;
613
614 if (!PyDict_Check(op)) {
615 PyErr_BadInternalCall();
616 return NULL;
617 }
618 if (!PyString_CheckExact(key) ||
619 (hash = ((PyStringObject *) key)->ob_shash) == -1)
620 {
621 hash = PyObject_Hash(key);
622 if (hash == -1) {
623 return NULL;
624 }
625 }
626
627 ep = (mp->ma_lookup)(mp, key, hash);
628 if (ep == NULL)
629 return NULL;
630 return ep->me_value;
631}
632
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000633/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
Tim Peters60b29962006-01-01 01:19:23 +0000634 * dictionary if it's merely replacing the value for an existing key.
635 * This means that it's safe to loop over a dictionary with PyDict_Next()
636 * and occasionally replace a value -- but you can't insert new keys or
637 * remove them.
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000638 */
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000639int
Tim Peters1f5871e2000-07-04 17:44:48 +0000640PyDict_SetItem(register PyObject *op, PyObject *key, PyObject *value)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000641{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000642 register dictobject *mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000643 register long hash;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000644 register Py_ssize_t n_used;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000645
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000646 if (!PyDict_Check(op)) {
647 PyErr_BadInternalCall();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000648 return -1;
649 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000650 assert(key);
651 assert(value);
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000652 mp = (dictobject *)op;
Tim Peters0ab085c2001-09-14 00:25:33 +0000653 if (PyString_CheckExact(key)) {
Guido van Rossum45ec02a2002-08-19 21:43:18 +0000654 hash = ((PyStringObject *)key)->ob_shash;
655 if (hash == -1)
656 hash = PyObject_Hash(key);
Guido van Rossum2a61e741997-01-18 07:55:05 +0000657 }
Tim Peters1f7df352002-03-29 03:29:08 +0000658 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000659 hash = PyObject_Hash(key);
Guido van Rossum2a61e741997-01-18 07:55:05 +0000660 if (hash == -1)
661 return -1;
Guido van Rossum2a61e741997-01-18 07:55:05 +0000662 }
Tim Petersafb6ae82001-06-04 21:00:21 +0000663 assert(mp->ma_fill <= mp->ma_mask); /* at least one empty slot */
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000664 n_used = mp->ma_used;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000665 Py_INCREF(value);
666 Py_INCREF(key);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000667 if (insertdict(mp, key, hash, value) != 0)
668 return -1;
Raymond Hettinger3539f6b2003-05-05 22:22:10 +0000669 /* If we added a key, we can safely resize. Otherwise just return!
670 * If fill >= 2/3 size, adjust size. Normally, this doubles or
671 * quaduples the size, but it's also possible for the dict to shrink
Tim Peters60b29962006-01-01 01:19:23 +0000672 * (if ma_fill is much larger than ma_used, meaning a lot of dict
Raymond Hettinger3539f6b2003-05-05 22:22:10 +0000673 * keys have been * deleted).
Tim Peters60b29962006-01-01 01:19:23 +0000674 *
Raymond Hettinger3539f6b2003-05-05 22:22:10 +0000675 * Quadrupling the size improves average dictionary sparseness
676 * (reducing collisions) at the cost of some memory and iteration
677 * speed (which loops over every possible entry). It also halves
678 * the number of expensive resize operations in a growing dictionary.
Tim Peters60b29962006-01-01 01:19:23 +0000679 *
680 * Very large dictionaries (over 50K items) use doubling instead.
Raymond Hettinger3539f6b2003-05-05 22:22:10 +0000681 * This may help applications with severe memory constraints.
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000682 */
Raymond Hettinger3539f6b2003-05-05 22:22:10 +0000683 if (!(mp->ma_used > n_used && mp->ma_fill*3 >= (mp->ma_mask+1)*2))
684 return 0;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000685 return dictresize(mp, (mp->ma_used > 50000 ? 2 : 4) * mp->ma_used);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000686}
687
688int
Tim Peters1f5871e2000-07-04 17:44:48 +0000689PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000690{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000691 register dictobject *mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000692 register long hash;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000693 register dictentry *ep;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000694 PyObject *old_value, *old_key;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000695
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000696 if (!PyDict_Check(op)) {
697 PyErr_BadInternalCall();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000698 return -1;
699 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000700 assert(key);
Tim Peters0ab085c2001-09-14 00:25:33 +0000701 if (!PyString_CheckExact(key) ||
Tim Peters1f7df352002-03-29 03:29:08 +0000702 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000703 hash = PyObject_Hash(key);
Guido van Rossumca756f21997-01-23 19:39:29 +0000704 if (hash == -1)
705 return -1;
706 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000707 mp = (dictobject *)op;
Fred Drake1bff34a2000-08-31 19:31:38 +0000708 ep = (mp->ma_lookup)(mp, key, hash);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000709 if (ep == NULL)
710 return -1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000711 if (ep->me_value == NULL) {
Thomas Wouters89f507f2006-12-13 04:49:30 +0000712 set_key_error(key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000713 return -1;
714 }
Guido van Rossumd7047b31995-01-02 19:07:15 +0000715 old_key = ep->me_key;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000716 Py_INCREF(dummy);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000717 ep->me_key = dummy;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000718 old_value = ep->me_value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000719 ep->me_value = NULL;
720 mp->ma_used--;
Tim Petersea8f2bf2000-12-13 01:02:46 +0000721 Py_DECREF(old_value);
722 Py_DECREF(old_key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000723 return 0;
724}
725
Guido van Rossum25831651993-05-19 14:50:45 +0000726void
Tim Peters1f5871e2000-07-04 17:44:48 +0000727PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000728{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000729 dictobject *mp;
Tim Petersdea48ec2001-05-22 20:40:22 +0000730 dictentry *ep, *table;
731 int table_is_malloced;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000732 Py_ssize_t fill;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000733 dictentry small_copy[PyDict_MINSIZE];
Tim Petersdea48ec2001-05-22 20:40:22 +0000734#ifdef Py_DEBUG
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000735 Py_ssize_t i, n;
Tim Petersdea48ec2001-05-22 20:40:22 +0000736#endif
737
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000738 if (!PyDict_Check(op))
Guido van Rossum25831651993-05-19 14:50:45 +0000739 return;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000740 mp = (dictobject *)op;
Tim Petersdea48ec2001-05-22 20:40:22 +0000741#ifdef Py_DEBUG
Tim Petersafb6ae82001-06-04 21:00:21 +0000742 n = mp->ma_mask + 1;
Tim Petersdea48ec2001-05-22 20:40:22 +0000743 i = 0;
744#endif
745
746 table = mp->ma_table;
747 assert(table != NULL);
748 table_is_malloced = table != mp->ma_smalltable;
749
750 /* This is delicate. During the process of clearing the dict,
751 * decrefs can cause the dict to mutate. To avoid fatal confusion
752 * (voice of experience), we have to make the dict empty before
753 * clearing the slots, and never refer to anything via mp->xxx while
754 * clearing.
755 */
756 fill = mp->ma_fill;
757 if (table_is_malloced)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000758 EMPTY_TO_MINSIZE(mp);
Tim Petersdea48ec2001-05-22 20:40:22 +0000759
760 else if (fill > 0) {
761 /* It's a small table with something that needs to be cleared.
762 * Afraid the only safe way is to copy the dict entries into
763 * another small table first.
764 */
765 memcpy(small_copy, table, sizeof(small_copy));
766 table = small_copy;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000767 EMPTY_TO_MINSIZE(mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000768 }
Tim Petersdea48ec2001-05-22 20:40:22 +0000769 /* else it's a small table that's already empty */
770
771 /* Now we can finally clear things. If C had refcounts, we could
772 * assert that the refcount on table is 1 now, i.e. that this function
773 * has unique access to it, so decref side-effects can't alter it.
774 */
775 for (ep = table; fill > 0; ++ep) {
776#ifdef Py_DEBUG
777 assert(i < n);
778 ++i;
779#endif
780 if (ep->me_key) {
781 --fill;
782 Py_DECREF(ep->me_key);
783 Py_XDECREF(ep->me_value);
784 }
785#ifdef Py_DEBUG
786 else
787 assert(ep->me_value == NULL);
788#endif
789 }
790
791 if (table_is_malloced)
792 PyMem_DEL(table);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000793}
794
Tim Peters080c88b2003-02-15 03:01:11 +0000795/*
796 * Iterate over a dict. Use like so:
797 *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000798 * Py_ssize_t i;
Tim Peters080c88b2003-02-15 03:01:11 +0000799 * PyObject *key, *value;
800 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +0000801 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Tim Peters080c88b2003-02-15 03:01:11 +0000802 * Refer to borrowed references in key and value.
803 * }
804 *
805 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +0000806 * mutates the dict. One exception: it is safe if the loop merely changes
807 * the values associated with the keys (but doesn't insert new keys or
808 * delete keys), via PyDict_SetItem().
809 */
Guido van Rossum25831651993-05-19 14:50:45 +0000810int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000811PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000812{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000813 register Py_ssize_t i;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000814 register Py_ssize_t mask;
Raymond Hettinger43442782004-03-17 21:55:03 +0000815 register dictentry *ep;
816
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000817 if (!PyDict_Check(op))
Guido van Rossum25831651993-05-19 14:50:45 +0000818 return 0;
Guido van Rossum25831651993-05-19 14:50:45 +0000819 i = *ppos;
820 if (i < 0)
821 return 0;
Raymond Hettinger43442782004-03-17 21:55:03 +0000822 ep = ((dictobject *)op)->ma_table;
823 mask = ((dictobject *)op)->ma_mask;
824 while (i <= mask && ep[i].me_value == NULL)
Guido van Rossum25831651993-05-19 14:50:45 +0000825 i++;
826 *ppos = i+1;
Raymond Hettinger43442782004-03-17 21:55:03 +0000827 if (i > mask)
Guido van Rossum25831651993-05-19 14:50:45 +0000828 return 0;
829 if (pkey)
Raymond Hettinger43442782004-03-17 21:55:03 +0000830 *pkey = ep[i].me_key;
Guido van Rossum25831651993-05-19 14:50:45 +0000831 if (pvalue)
Raymond Hettinger43442782004-03-17 21:55:03 +0000832 *pvalue = ep[i].me_value;
Guido van Rossum25831651993-05-19 14:50:45 +0000833 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000834}
835
Thomas Wouterscf297e42007-02-23 15:07:44 +0000836/* Internal version of PyDict_Next that returns a hash value in addition to the key and value.*/
837int
838_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue, long *phash)
839{
840 register Py_ssize_t i;
841 register Py_ssize_t mask;
842 register dictentry *ep;
843
844 if (!PyDict_Check(op))
845 return 0;
846 i = *ppos;
847 if (i < 0)
848 return 0;
849 ep = ((dictobject *)op)->ma_table;
850 mask = ((dictobject *)op)->ma_mask;
851 while (i <= mask && ep[i].me_value == NULL)
852 i++;
853 *ppos = i+1;
854 if (i > mask)
855 return 0;
856 *phash = (long)(ep[i].me_hash);
857 if (pkey)
858 *pkey = ep[i].me_key;
859 if (pvalue)
860 *pvalue = ep[i].me_value;
861 return 1;
862}
863
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000864/* Methods */
865
866static void
Tim Peters1f5871e2000-07-04 17:44:48 +0000867dict_dealloc(register dictobject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000868{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000869 register dictentry *ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000870 Py_ssize_t fill = mp->ma_fill;
Guido van Rossumff413af2002-03-28 20:34:59 +0000871 PyObject_GC_UnTrack(mp);
Guido van Rossumd724b232000-03-13 16:01:29 +0000872 Py_TRASHCAN_SAFE_BEGIN(mp)
Tim Petersdea48ec2001-05-22 20:40:22 +0000873 for (ep = mp->ma_table; fill > 0; ep++) {
874 if (ep->me_key) {
875 --fill;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000876 Py_DECREF(ep->me_key);
Tim Petersdea48ec2001-05-22 20:40:22 +0000877 Py_XDECREF(ep->me_value);
Guido van Rossum255443b1998-04-10 22:47:14 +0000878 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000879 }
Tim Petersdea48ec2001-05-22 20:40:22 +0000880 if (mp->ma_table != mp->ma_smalltable)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000881 PyMem_DEL(mp->ma_table);
Raymond Hettinger43442782004-03-17 21:55:03 +0000882 if (num_free_dicts < MAXFREEDICTS && mp->ob_type == &PyDict_Type)
883 free_dicts[num_free_dicts++] = mp;
Tim Peters60b29962006-01-01 01:19:23 +0000884 else
Raymond Hettinger43442782004-03-17 21:55:03 +0000885 mp->ob_type->tp_free((PyObject *)mp);
Guido van Rossumd724b232000-03-13 16:01:29 +0000886 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000887}
888
889static int
Tim Peters1f5871e2000-07-04 17:44:48 +0000890dict_print(register dictobject *mp, register FILE *fp, register int flags)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000891{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000892 register Py_ssize_t i;
893 register Py_ssize_t any;
894 int status;
Guido van Rossum255443b1998-04-10 22:47:14 +0000895
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000896 status = Py_ReprEnter((PyObject*)mp);
897 if (status != 0) {
898 if (status < 0)
899 return status;
Guido van Rossum255443b1998-04-10 22:47:14 +0000900 fprintf(fp, "{...}");
901 return 0;
902 }
903
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000904 fprintf(fp, "{");
905 any = 0;
Tim Petersafb6ae82001-06-04 21:00:21 +0000906 for (i = 0; i <= mp->ma_mask; i++) {
Tim Peters23cf6be2001-06-02 08:02:56 +0000907 dictentry *ep = mp->ma_table + i;
908 PyObject *pvalue = ep->me_value;
909 if (pvalue != NULL) {
910 /* Prevent PyObject_Repr from deleting value during
911 key format */
912 Py_INCREF(pvalue);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000913 if (any++ > 0)
914 fprintf(fp, ", ");
Guido van Rossum255443b1998-04-10 22:47:14 +0000915 if (PyObject_Print((PyObject *)ep->me_key, fp, 0)!=0) {
Tim Peters23cf6be2001-06-02 08:02:56 +0000916 Py_DECREF(pvalue);
Guido van Rossum255443b1998-04-10 22:47:14 +0000917 Py_ReprLeave((PyObject*)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000918 return -1;
Guido van Rossum255443b1998-04-10 22:47:14 +0000919 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000920 fprintf(fp, ": ");
Tim Peters19b77cf2001-06-02 08:27:39 +0000921 if (PyObject_Print(pvalue, fp, 0) != 0) {
Tim Peters23cf6be2001-06-02 08:02:56 +0000922 Py_DECREF(pvalue);
Guido van Rossum255443b1998-04-10 22:47:14 +0000923 Py_ReprLeave((PyObject*)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000924 return -1;
Guido van Rossum255443b1998-04-10 22:47:14 +0000925 }
Tim Peters23cf6be2001-06-02 08:02:56 +0000926 Py_DECREF(pvalue);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000927 }
928 }
929 fprintf(fp, "}");
Guido van Rossum255443b1998-04-10 22:47:14 +0000930 Py_ReprLeave((PyObject*)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000931 return 0;
932}
933
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000934static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000935dict_repr(dictobject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000936{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000937 Py_ssize_t i;
Tim Petersa7259592001-06-16 05:11:17 +0000938 PyObject *s, *temp, *colon = NULL;
939 PyObject *pieces = NULL, *result = NULL;
940 PyObject *key, *value;
Guido van Rossum255443b1998-04-10 22:47:14 +0000941
Tim Petersa7259592001-06-16 05:11:17 +0000942 i = Py_ReprEnter((PyObject *)mp);
Guido van Rossum255443b1998-04-10 22:47:14 +0000943 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000944 return i > 0 ? PyString_FromString("{...}") : NULL;
Guido van Rossum255443b1998-04-10 22:47:14 +0000945 }
946
Tim Petersa7259592001-06-16 05:11:17 +0000947 if (mp->ma_used == 0) {
948 result = PyString_FromString("{}");
949 goto Done;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000950 }
Tim Petersa7259592001-06-16 05:11:17 +0000951
952 pieces = PyList_New(0);
953 if (pieces == NULL)
954 goto Done;
955
956 colon = PyString_FromString(": ");
957 if (colon == NULL)
958 goto Done;
959
960 /* Do repr() on each key+value pair, and insert ": " between them.
961 Note that repr may mutate the dict. */
Tim Petersc6057842001-06-16 07:52:53 +0000962 i = 0;
963 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Tim Petersa7259592001-06-16 05:11:17 +0000964 int status;
965 /* Prevent repr from deleting value during key format. */
966 Py_INCREF(value);
967 s = PyObject_Repr(key);
968 PyString_Concat(&s, colon);
969 PyString_ConcatAndDel(&s, PyObject_Repr(value));
970 Py_DECREF(value);
971 if (s == NULL)
972 goto Done;
973 status = PyList_Append(pieces, s);
974 Py_DECREF(s); /* append created a new ref */
975 if (status < 0)
976 goto Done;
977 }
978
979 /* Add "{}" decorations to the first and last items. */
980 assert(PyList_GET_SIZE(pieces) > 0);
981 s = PyString_FromString("{");
982 if (s == NULL)
983 goto Done;
984 temp = PyList_GET_ITEM(pieces, 0);
985 PyString_ConcatAndDel(&s, temp);
986 PyList_SET_ITEM(pieces, 0, s);
987 if (s == NULL)
988 goto Done;
989
990 s = PyString_FromString("}");
991 if (s == NULL)
992 goto Done;
993 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
994 PyString_ConcatAndDel(&temp, s);
995 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
996 if (temp == NULL)
997 goto Done;
998
999 /* Paste them all together with ", " between. */
1000 s = PyString_FromString(", ");
1001 if (s == NULL)
1002 goto Done;
1003 result = _PyString_Join(s, pieces);
Tim Peters0ab085c2001-09-14 00:25:33 +00001004 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +00001005
1006Done:
1007 Py_XDECREF(pieces);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001008 Py_XDECREF(colon);
Tim Petersa7259592001-06-16 05:11:17 +00001009 Py_ReprLeave((PyObject *)mp);
1010 return result;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001011}
1012
Martin v. Löwis18e16552006-02-15 17:27:45 +00001013static Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00001014dict_length(dictobject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001015{
1016 return mp->ma_used;
1017}
1018
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001019static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001020dict_subscript(dictobject *mp, register PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001021{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001022 PyObject *v;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +00001023 long hash;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001024 dictentry *ep;
Tim Petersdea48ec2001-05-22 20:40:22 +00001025 assert(mp->ma_table != NULL);
Tim Peters0ab085c2001-09-14 00:25:33 +00001026 if (!PyString_CheckExact(key) ||
Tim Peters1f7df352002-03-29 03:29:08 +00001027 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001028 hash = PyObject_Hash(key);
Guido van Rossumca756f21997-01-23 19:39:29 +00001029 if (hash == -1)
1030 return NULL;
1031 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001032 ep = (mp->ma_lookup)(mp, key, hash);
1033 if (ep == NULL)
1034 return NULL;
1035 v = ep->me_value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001036 if (v == NULL) {
1037 if (!PyDict_CheckExact(mp)) {
1038 /* Look up __missing__ method if we're a subclass. */
Guido van Rossum4b92a822006-02-25 23:32:30 +00001039 PyObject *missing;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001040 static PyObject *missing_str = NULL;
1041 if (missing_str == NULL)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001042 missing_str =
Guido van Rossum1968ad32006-02-25 22:38:04 +00001043 PyString_InternFromString("__missing__");
Guido van Rossum4b92a822006-02-25 23:32:30 +00001044 missing = _PyType_Lookup(mp->ob_type, missing_str);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001045 if (missing != NULL)
1046 return PyObject_CallFunctionObjArgs(missing,
1047 (PyObject *)mp, key, NULL);
1048 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001049 set_key_error(key);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001050 return NULL;
1051 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001052 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001053 Py_INCREF(v);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001054 return v;
1055}
1056
1057static int
Tim Peters1f5871e2000-07-04 17:44:48 +00001058dict_ass_sub(dictobject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001059{
1060 if (w == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001061 return PyDict_DelItem((PyObject *)mp, v);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001062 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001063 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001064}
1065
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001066static PyMappingMethods dict_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001067 (lenfunc)dict_length, /*mp_length*/
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001068 (binaryfunc)dict_subscript, /*mp_subscript*/
1069 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001070};
1071
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001072static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001073dict_keys(register dictobject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001074{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001075 register PyObject *v;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001076 register Py_ssize_t i, j;
Raymond Hettinger43442782004-03-17 21:55:03 +00001077 dictentry *ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001078 Py_ssize_t mask, n;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001079
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001080 again:
1081 n = mp->ma_used;
1082 v = PyList_New(n);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001083 if (v == NULL)
1084 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001085 if (n != mp->ma_used) {
1086 /* Durnit. The allocations caused the dict to resize.
1087 * Just start over, this shouldn't normally happen.
1088 */
1089 Py_DECREF(v);
1090 goto again;
1091 }
Raymond Hettinger43442782004-03-17 21:55:03 +00001092 ep = mp->ma_table;
1093 mask = mp->ma_mask;
1094 for (i = 0, j = 0; i <= mask; i++) {
1095 if (ep[i].me_value != NULL) {
1096 PyObject *key = ep[i].me_key;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001097 Py_INCREF(key);
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001098 PyList_SET_ITEM(v, j, key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001099 j++;
1100 }
1101 }
Raymond Hettinger43442782004-03-17 21:55:03 +00001102 assert(j == n);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001103 return v;
1104}
1105
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001106static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001107dict_values(register dictobject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001108{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001109 register PyObject *v;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001110 register Py_ssize_t i, j;
Raymond Hettinger43442782004-03-17 21:55:03 +00001111 dictentry *ep;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001112 Py_ssize_t mask, n;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001113
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001114 again:
1115 n = mp->ma_used;
1116 v = PyList_New(n);
Guido van Rossum25831651993-05-19 14:50:45 +00001117 if (v == NULL)
1118 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001119 if (n != mp->ma_used) {
1120 /* Durnit. The allocations caused the dict to resize.
1121 * Just start over, this shouldn't normally happen.
1122 */
1123 Py_DECREF(v);
1124 goto again;
1125 }
Raymond Hettinger43442782004-03-17 21:55:03 +00001126 ep = mp->ma_table;
1127 mask = mp->ma_mask;
1128 for (i = 0, j = 0; i <= mask; i++) {
1129 if (ep[i].me_value != NULL) {
1130 PyObject *value = ep[i].me_value;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001131 Py_INCREF(value);
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001132 PyList_SET_ITEM(v, j, value);
Guido van Rossum25831651993-05-19 14:50:45 +00001133 j++;
1134 }
1135 }
Raymond Hettinger43442782004-03-17 21:55:03 +00001136 assert(j == n);
Guido van Rossum25831651993-05-19 14:50:45 +00001137 return v;
1138}
1139
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001140static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001141dict_items(register dictobject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001142{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001143 register PyObject *v;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001144 register Py_ssize_t i, j, n;
1145 Py_ssize_t mask;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001146 PyObject *item, *key, *value;
Raymond Hettinger43442782004-03-17 21:55:03 +00001147 dictentry *ep;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001148
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001149 /* Preallocate the list of tuples, to avoid allocations during
1150 * the loop over the items, which could trigger GC, which
1151 * could resize the dict. :-(
1152 */
1153 again:
1154 n = mp->ma_used;
1155 v = PyList_New(n);
Guido van Rossum25831651993-05-19 14:50:45 +00001156 if (v == NULL)
1157 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001158 for (i = 0; i < n; i++) {
1159 item = PyTuple_New(2);
1160 if (item == NULL) {
1161 Py_DECREF(v);
1162 return NULL;
1163 }
1164 PyList_SET_ITEM(v, i, item);
1165 }
1166 if (n != mp->ma_used) {
1167 /* Durnit. The allocations caused the dict to resize.
1168 * Just start over, this shouldn't normally happen.
1169 */
1170 Py_DECREF(v);
1171 goto again;
1172 }
1173 /* Nothing we do below makes any function calls. */
Raymond Hettinger43442782004-03-17 21:55:03 +00001174 ep = mp->ma_table;
1175 mask = mp->ma_mask;
1176 for (i = 0, j = 0; i <= mask; i++) {
Raymond Hettinger06905122004-03-19 10:30:00 +00001177 if ((value=ep[i].me_value) != NULL) {
Raymond Hettinger43442782004-03-17 21:55:03 +00001178 key = ep[i].me_key;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001179 item = PyList_GET_ITEM(v, j);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001180 Py_INCREF(key);
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001181 PyTuple_SET_ITEM(item, 0, key);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001182 Py_INCREF(value);
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001183 PyTuple_SET_ITEM(item, 1, value);
Guido van Rossum25831651993-05-19 14:50:45 +00001184 j++;
1185 }
1186 }
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001187 assert(j == n);
Guido van Rossum25831651993-05-19 14:50:45 +00001188 return v;
1189}
1190
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001191static PyObject *
Tim Petersbca1cbc2002-12-09 22:56:13 +00001192dict_fromkeys(PyObject *cls, PyObject *args)
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001193{
1194 PyObject *seq;
1195 PyObject *value = Py_None;
1196 PyObject *it; /* iter(seq) */
1197 PyObject *key;
1198 PyObject *d;
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001199 int status;
1200
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001201 if (!PyArg_UnpackTuple(args, "fromkeys", 1, 2, &seq, &value))
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001202 return NULL;
1203
1204 d = PyObject_CallObject(cls, NULL);
1205 if (d == NULL)
1206 return NULL;
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001207
1208 it = PyObject_GetIter(seq);
1209 if (it == NULL){
1210 Py_DECREF(d);
1211 return NULL;
1212 }
1213
1214 for (;;) {
1215 key = PyIter_Next(it);
1216 if (key == NULL) {
1217 if (PyErr_Occurred())
1218 goto Fail;
1219 break;
1220 }
Raymond Hettingere03e5b12002-12-07 08:10:51 +00001221 status = PyObject_SetItem(d, key, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001222 Py_DECREF(key);
1223 if (status < 0)
1224 goto Fail;
1225 }
1226
1227 Py_DECREF(it);
1228 return d;
1229
1230Fail:
1231 Py_DECREF(it);
1232 Py_DECREF(d);
1233 return NULL;
1234}
1235
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001236static int
1237dict_update_common(PyObject *self, PyObject *args, PyObject *kwds, char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001238{
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001239 PyObject *arg = NULL;
1240 int result = 0;
1241
1242 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
1243 result = -1;
1244
1245 else if (arg != NULL) {
1246 if (PyObject_HasAttrString(arg, "keys"))
1247 result = PyDict_Merge(self, arg, 1);
1248 else
1249 result = PyDict_MergeFromSeq2(self, arg, 1);
1250 }
1251 if (result == 0 && kwds != NULL)
1252 result = PyDict_Merge(self, kwds, 1);
1253 return result;
1254}
1255
1256static PyObject *
1257dict_update(PyObject *self, PyObject *args, PyObject *kwds)
1258{
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001259 if (dict_update_common(self, args, kwds, "update") != -1)
1260 Py_RETURN_NONE;
1261 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001262}
1263
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001264/* Update unconditionally replaces existing items.
1265 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00001266 otherwise it leaves existing items unchanged.
1267
1268 PyDict_{Update,Merge} update/merge from a mapping object.
1269
Tim Petersf582b822001-12-11 18:51:08 +00001270 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00001271 producing iterable objects of length 2.
1272*/
1273
Tim Petersf582b822001-12-11 18:51:08 +00001274int
Tim Peters1fc240e2001-10-26 05:06:50 +00001275PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
1276{
1277 PyObject *it; /* iter(seq2) */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001278 Py_ssize_t i; /* index into seq2 of current element */
Tim Peters1fc240e2001-10-26 05:06:50 +00001279 PyObject *item; /* seq2[i] */
1280 PyObject *fast; /* item as a 2-tuple or 2-list */
1281
1282 assert(d != NULL);
1283 assert(PyDict_Check(d));
1284 assert(seq2 != NULL);
1285
1286 it = PyObject_GetIter(seq2);
1287 if (it == NULL)
1288 return -1;
1289
1290 for (i = 0; ; ++i) {
1291 PyObject *key, *value;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001292 Py_ssize_t n;
Tim Peters1fc240e2001-10-26 05:06:50 +00001293
1294 fast = NULL;
1295 item = PyIter_Next(it);
1296 if (item == NULL) {
1297 if (PyErr_Occurred())
1298 goto Fail;
1299 break;
1300 }
1301
1302 /* Convert item to sequence, and verify length 2. */
1303 fast = PySequence_Fast(item, "");
1304 if (fast == NULL) {
1305 if (PyErr_ExceptionMatches(PyExc_TypeError))
1306 PyErr_Format(PyExc_TypeError,
1307 "cannot convert dictionary update "
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001308 "sequence element #%zd to a sequence",
Tim Peters1fc240e2001-10-26 05:06:50 +00001309 i);
1310 goto Fail;
1311 }
1312 n = PySequence_Fast_GET_SIZE(fast);
1313 if (n != 2) {
1314 PyErr_Format(PyExc_ValueError,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001315 "dictionary update sequence element #%zd "
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00001316 "has length %zd; 2 is required",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00001317 i, n);
Tim Peters1fc240e2001-10-26 05:06:50 +00001318 goto Fail;
1319 }
1320
1321 /* Update/merge with this (key, value) pair. */
1322 key = PySequence_Fast_GET_ITEM(fast, 0);
1323 value = PySequence_Fast_GET_ITEM(fast, 1);
1324 if (override || PyDict_GetItem(d, key) == NULL) {
1325 int status = PyDict_SetItem(d, key, value);
1326 if (status < 0)
1327 goto Fail;
1328 }
1329 Py_DECREF(fast);
1330 Py_DECREF(item);
1331 }
1332
1333 i = 0;
1334 goto Return;
1335Fail:
1336 Py_XDECREF(item);
1337 Py_XDECREF(fast);
1338 i = -1;
1339Return:
1340 Py_DECREF(it);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001341 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
Tim Peters1fc240e2001-10-26 05:06:50 +00001342}
1343
Tim Peters6d6c1a32001-08-02 04:15:00 +00001344int
1345PyDict_Update(PyObject *a, PyObject *b)
1346{
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001347 return PyDict_Merge(a, b, 1);
1348}
1349
1350int
1351PyDict_Merge(PyObject *a, PyObject *b, int override)
1352{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001353 register PyDictObject *mp, *other;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001354 register Py_ssize_t i;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001355 dictentry *entry;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001356
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001357 /* We accept for the argument either a concrete dictionary object,
1358 * or an abstract "mapping" object. For the former, we can do
1359 * things quite efficiently. For the latter, we only require that
1360 * PyMapping_Keys() and PyObject_GetItem() be supported.
1361 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001362 if (a == NULL || !PyDict_Check(a) || b == NULL) {
1363 PyErr_BadInternalCall();
1364 return -1;
1365 }
1366 mp = (dictobject*)a;
Thomas Wouterscf297e42007-02-23 15:07:44 +00001367 if (PyDict_CheckExact(b)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001368 other = (dictobject*)b;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001369 if (other == mp || other->ma_used == 0)
1370 /* a.update(a) or a.update({}); nothing to do */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001371 return 0;
Raymond Hettinger186e7392005-05-14 18:08:25 +00001372 if (mp->ma_used == 0)
1373 /* Since the target dict is empty, PyDict_GetItem()
1374 * always returns NULL. Setting override to 1
1375 * skips the unnecessary test.
1376 */
1377 override = 1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001378 /* Do one big resize at the start, rather than
1379 * incrementally resizing as we insert new items. Expect
1380 * that there will be no (or few) overlapping keys.
1381 */
1382 if ((mp->ma_fill + other->ma_used)*3 >= (mp->ma_mask+1)*2) {
Raymond Hettingerc8d22902003-05-07 00:49:40 +00001383 if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001384 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001385 }
1386 for (i = 0; i <= other->ma_mask; i++) {
1387 entry = &other->ma_table[i];
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001388 if (entry->me_value != NULL &&
1389 (override ||
1390 PyDict_GetItem(a, entry->me_key) == NULL)) {
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001391 Py_INCREF(entry->me_key);
1392 Py_INCREF(entry->me_value);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001393 if (insertdict(mp, entry->me_key,
1394 (long)entry->me_hash,
1395 entry->me_value) != 0)
1396 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001397 }
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001398 }
1399 }
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001400 else {
1401 /* Do it the generic, slower way */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001402 PyObject *keys = PyMapping_Keys(b);
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001403 PyObject *iter;
1404 PyObject *key, *value;
1405 int status;
1406
1407 if (keys == NULL)
1408 /* Docstring says this is equivalent to E.keys() so
1409 * if E doesn't have a .keys() method we want
1410 * AttributeError to percolate up. Might as well
1411 * do the same for any other error.
1412 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001413 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001414
1415 iter = PyObject_GetIter(keys);
1416 Py_DECREF(keys);
1417 if (iter == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001418 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001419
1420 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001421 if (!override && PyDict_GetItem(a, key) != NULL) {
1422 Py_DECREF(key);
1423 continue;
1424 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001425 value = PyObject_GetItem(b, key);
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001426 if (value == NULL) {
1427 Py_DECREF(iter);
1428 Py_DECREF(key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001429 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001430 }
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001431 status = PyDict_SetItem(a, key, value);
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001432 Py_DECREF(key);
1433 Py_DECREF(value);
1434 if (status < 0) {
1435 Py_DECREF(iter);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001436 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001437 }
1438 }
1439 Py_DECREF(iter);
1440 if (PyErr_Occurred())
1441 /* Iterator completed, via error */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001442 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001443 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001444 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001445}
1446
1447static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001448dict_copy(register dictobject *mp)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001449{
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001450 return PyDict_Copy((PyObject*)mp);
1451}
1452
1453PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001454PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001455{
Raymond Hettingerebedb2f2004-03-08 04:19:01 +00001456 PyObject *copy;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001457
1458 if (o == NULL || !PyDict_Check(o)) {
1459 PyErr_BadInternalCall();
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001460 return NULL;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001461 }
Raymond Hettingerebedb2f2004-03-08 04:19:01 +00001462 copy = PyDict_New();
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001463 if (copy == NULL)
1464 return NULL;
Raymond Hettingerebedb2f2004-03-08 04:19:01 +00001465 if (PyDict_Merge(copy, o, 1) == 0)
1466 return copy;
1467 Py_DECREF(copy);
Raymond Hettinger1356f782005-04-15 15:58:42 +00001468 return NULL;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001469}
1470
Martin v. Löwis18e16552006-02-15 17:27:45 +00001471Py_ssize_t
Tim Peters1f5871e2000-07-04 17:44:48 +00001472PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00001473{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001474 if (mp == NULL || !PyDict_Check(mp)) {
1475 PyErr_BadInternalCall();
Jeremy Hylton7083bb72004-02-17 20:10:11 +00001476 return -1;
Guido van Rossum4199fac1993-11-05 10:18:44 +00001477 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001478 return ((dictobject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00001479}
1480
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001481PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001482PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001483{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001484 if (mp == NULL || !PyDict_Check(mp)) {
1485 PyErr_BadInternalCall();
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001486 return NULL;
1487 }
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001488 return dict_keys((dictobject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001489}
1490
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001491PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001492PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001493{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001494 if (mp == NULL || !PyDict_Check(mp)) {
1495 PyErr_BadInternalCall();
Guido van Rossum25831651993-05-19 14:50:45 +00001496 return NULL;
1497 }
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001498 return dict_values((dictobject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00001499}
1500
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001501PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001502PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001503{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001504 if (mp == NULL || !PyDict_Check(mp)) {
1505 PyErr_BadInternalCall();
Guido van Rossum25831651993-05-19 14:50:45 +00001506 return NULL;
1507 }
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001508 return dict_items((dictobject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00001509}
1510
Tim Peterse63415e2001-05-08 04:38:29 +00001511/* Return 1 if dicts equal, 0 if not, -1 if error.
1512 * Gets out as soon as any difference is detected.
1513 * Uses only Py_EQ comparison.
1514 */
1515static int
1516dict_equal(dictobject *a, dictobject *b)
1517{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001518 Py_ssize_t i;
Tim Peterse63415e2001-05-08 04:38:29 +00001519
1520 if (a->ma_used != b->ma_used)
1521 /* can't be equal if # of entries differ */
1522 return 0;
Tim Peterseb28ef22001-06-02 05:27:19 +00001523
Tim Peterse63415e2001-05-08 04:38:29 +00001524 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Tim Petersafb6ae82001-06-04 21:00:21 +00001525 for (i = 0; i <= a->ma_mask; i++) {
Tim Peterse63415e2001-05-08 04:38:29 +00001526 PyObject *aval = a->ma_table[i].me_value;
1527 if (aval != NULL) {
1528 int cmp;
1529 PyObject *bval;
1530 PyObject *key = a->ma_table[i].me_key;
1531 /* temporarily bump aval's refcount to ensure it stays
1532 alive until we're done with it */
1533 Py_INCREF(aval);
Guido van Rossumdc5f6b22006-08-24 21:29:26 +00001534 /* ditto for key */
1535 Py_INCREF(key);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001536 bval = PyDict_GetItemWithError((PyObject *)b, key);
Guido van Rossumdc5f6b22006-08-24 21:29:26 +00001537 Py_DECREF(key);
Tim Peterse63415e2001-05-08 04:38:29 +00001538 if (bval == NULL) {
1539 Py_DECREF(aval);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001540 if (PyErr_Occurred())
1541 return -1;
Tim Peterse63415e2001-05-08 04:38:29 +00001542 return 0;
1543 }
1544 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
1545 Py_DECREF(aval);
1546 if (cmp <= 0) /* error or not equal */
1547 return cmp;
1548 }
1549 }
1550 return 1;
1551 }
1552
1553static PyObject *
1554dict_richcompare(PyObject *v, PyObject *w, int op)
1555{
1556 int cmp;
1557 PyObject *res;
1558
1559 if (!PyDict_Check(v) || !PyDict_Check(w)) {
1560 res = Py_NotImplemented;
1561 }
1562 else if (op == Py_EQ || op == Py_NE) {
1563 cmp = dict_equal((dictobject *)v, (dictobject *)w);
1564 if (cmp < 0)
1565 return NULL;
1566 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
1567 }
Tim Peters4fa58bf2001-05-10 21:45:19 +00001568 else
1569 res = Py_NotImplemented;
Tim Peterse63415e2001-05-08 04:38:29 +00001570 Py_INCREF(res);
1571 return res;
1572 }
1573
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001574static PyObject *
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001575dict_contains(register dictobject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001576{
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001577 long hash;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001578 dictentry *ep;
1579
Tim Peters0ab085c2001-09-14 00:25:33 +00001580 if (!PyString_CheckExact(key) ||
Tim Peters1f7df352002-03-29 03:29:08 +00001581 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001582 hash = PyObject_Hash(key);
Guido van Rossumca756f21997-01-23 19:39:29 +00001583 if (hash == -1)
1584 return NULL;
1585 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001586 ep = (mp->ma_lookup)(mp, key, hash);
1587 if (ep == NULL)
1588 return NULL;
1589 return PyBool_FromLong(ep->me_value != NULL);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001590}
1591
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001592static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001593dict_get(register dictobject *mp, PyObject *args)
Barry Warsawc38c5da1997-10-06 17:49:20 +00001594{
1595 PyObject *key;
Barry Warsaw320ac331997-10-20 17:26:25 +00001596 PyObject *failobj = Py_None;
Barry Warsawc38c5da1997-10-06 17:49:20 +00001597 PyObject *val = NULL;
1598 long hash;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001599 dictentry *ep;
Barry Warsawc38c5da1997-10-06 17:49:20 +00001600
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001601 if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
Barry Warsawc38c5da1997-10-06 17:49:20 +00001602 return NULL;
1603
Tim Peters0ab085c2001-09-14 00:25:33 +00001604 if (!PyString_CheckExact(key) ||
Tim Peters1f7df352002-03-29 03:29:08 +00001605 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
Barry Warsawc38c5da1997-10-06 17:49:20 +00001606 hash = PyObject_Hash(key);
1607 if (hash == -1)
1608 return NULL;
1609 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001610 ep = (mp->ma_lookup)(mp, key, hash);
1611 if (ep == NULL)
1612 return NULL;
1613 val = ep->me_value;
Barry Warsawc38c5da1997-10-06 17:49:20 +00001614 if (val == NULL)
1615 val = failobj;
1616 Py_INCREF(val);
1617 return val;
1618}
1619
1620
1621static PyObject *
Guido van Rossum164452c2000-08-08 16:12:54 +00001622dict_setdefault(register dictobject *mp, PyObject *args)
1623{
1624 PyObject *key;
1625 PyObject *failobj = Py_None;
1626 PyObject *val = NULL;
1627 long hash;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001628 dictentry *ep;
Guido van Rossum164452c2000-08-08 16:12:54 +00001629
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001630 if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &failobj))
Guido van Rossum164452c2000-08-08 16:12:54 +00001631 return NULL;
Guido van Rossum164452c2000-08-08 16:12:54 +00001632
Tim Peters0ab085c2001-09-14 00:25:33 +00001633 if (!PyString_CheckExact(key) ||
Tim Peters1f7df352002-03-29 03:29:08 +00001634 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
Guido van Rossum164452c2000-08-08 16:12:54 +00001635 hash = PyObject_Hash(key);
1636 if (hash == -1)
1637 return NULL;
1638 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001639 ep = (mp->ma_lookup)(mp, key, hash);
1640 if (ep == NULL)
1641 return NULL;
1642 val = ep->me_value;
Guido van Rossum164452c2000-08-08 16:12:54 +00001643 if (val == NULL) {
1644 val = failobj;
1645 if (PyDict_SetItem((PyObject*)mp, key, failobj))
1646 val = NULL;
1647 }
1648 Py_XINCREF(val);
1649 return val;
1650}
1651
1652
1653static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001654dict_clear(register dictobject *mp)
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00001655{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001656 PyDict_Clear((PyObject *)mp);
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001657 Py_RETURN_NONE;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00001658}
1659
Guido van Rossumba6ab842000-12-12 22:02:18 +00001660static PyObject *
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001661dict_pop(dictobject *mp, PyObject *args)
Guido van Rossume027d982002-04-12 15:11:59 +00001662{
1663 long hash;
1664 dictentry *ep;
1665 PyObject *old_value, *old_key;
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001666 PyObject *key, *deflt = NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00001667
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001668 if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
1669 return NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00001670 if (mp->ma_used == 0) {
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001671 if (deflt) {
1672 Py_INCREF(deflt);
1673 return deflt;
1674 }
Guido van Rossume027d982002-04-12 15:11:59 +00001675 PyErr_SetString(PyExc_KeyError,
1676 "pop(): dictionary is empty");
1677 return NULL;
1678 }
1679 if (!PyString_CheckExact(key) ||
1680 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
1681 hash = PyObject_Hash(key);
1682 if (hash == -1)
1683 return NULL;
1684 }
1685 ep = (mp->ma_lookup)(mp, key, hash);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001686 if (ep == NULL)
1687 return NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00001688 if (ep->me_value == NULL) {
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001689 if (deflt) {
1690 Py_INCREF(deflt);
1691 return deflt;
1692 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001693 set_key_error(key);
Guido van Rossume027d982002-04-12 15:11:59 +00001694 return NULL;
1695 }
1696 old_key = ep->me_key;
1697 Py_INCREF(dummy);
1698 ep->me_key = dummy;
1699 old_value = ep->me_value;
1700 ep->me_value = NULL;
1701 mp->ma_used--;
1702 Py_DECREF(old_key);
1703 return old_value;
1704}
1705
1706static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001707dict_popitem(dictobject *mp)
Guido van Rossumba6ab842000-12-12 22:02:18 +00001708{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001709 Py_ssize_t i = 0;
Guido van Rossumba6ab842000-12-12 22:02:18 +00001710 dictentry *ep;
1711 PyObject *res;
1712
Tim Petersf4b33f62001-06-02 05:42:29 +00001713 /* Allocate the result tuple before checking the size. Believe it
1714 * or not, this allocation could trigger a garbage collection which
1715 * could empty the dict, so if we checked the size first and that
1716 * happened, the result would be an infinite loop (searching for an
1717 * entry that no longer exists). Note that the usual popitem()
1718 * idiom is "while d: k, v = d.popitem()". so needing to throw the
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001719 * tuple away if the dict *is* empty isn't a significant
Tim Petersf4b33f62001-06-02 05:42:29 +00001720 * inefficiency -- possible, but unlikely in practice.
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001721 */
1722 res = PyTuple_New(2);
1723 if (res == NULL)
1724 return NULL;
Guido van Rossume04eaec2001-04-16 00:02:32 +00001725 if (mp->ma_used == 0) {
1726 Py_DECREF(res);
1727 PyErr_SetString(PyExc_KeyError,
1728 "popitem(): dictionary is empty");
1729 return NULL;
1730 }
Guido van Rossumba6ab842000-12-12 22:02:18 +00001731 /* Set ep to "the first" dict entry with a value. We abuse the hash
1732 * field of slot 0 to hold a search finger:
1733 * If slot 0 has a value, use slot 0.
1734 * Else slot 0 is being used to hold a search finger,
1735 * and we use its hash value as the first index to look.
1736 */
1737 ep = &mp->ma_table[0];
1738 if (ep->me_value == NULL) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001739 i = ep->me_hash;
Tim Petersdea48ec2001-05-22 20:40:22 +00001740 /* The hash field may be a real hash value, or it may be a
1741 * legit search finger, or it may be a once-legit search
1742 * finger that's out of bounds now because it wrapped around
1743 * or the table shrunk -- simply make sure it's in bounds now.
Guido van Rossumba6ab842000-12-12 22:02:18 +00001744 */
Tim Petersafb6ae82001-06-04 21:00:21 +00001745 if (i > mp->ma_mask || i < 1)
Guido van Rossumba6ab842000-12-12 22:02:18 +00001746 i = 1; /* skip slot 0 */
1747 while ((ep = &mp->ma_table[i])->me_value == NULL) {
1748 i++;
Tim Petersafb6ae82001-06-04 21:00:21 +00001749 if (i > mp->ma_mask)
Guido van Rossumba6ab842000-12-12 22:02:18 +00001750 i = 1;
1751 }
1752 }
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001753 PyTuple_SET_ITEM(res, 0, ep->me_key);
1754 PyTuple_SET_ITEM(res, 1, ep->me_value);
1755 Py_INCREF(dummy);
1756 ep->me_key = dummy;
1757 ep->me_value = NULL;
1758 mp->ma_used--;
1759 assert(mp->ma_table[0].me_value == NULL);
1760 mp->ma_table[0].me_hash = i + 1; /* next place to start */
Guido van Rossumba6ab842000-12-12 22:02:18 +00001761 return res;
1762}
1763
Jeremy Hylton8caad492000-06-23 14:18:11 +00001764static int
1765dict_traverse(PyObject *op, visitproc visit, void *arg)
1766{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001767 Py_ssize_t i = 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00001768 PyObject *pk;
1769 PyObject *pv;
1770
1771 while (PyDict_Next(op, &i, &pk, &pv)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001772 Py_VISIT(pk);
1773 Py_VISIT(pv);
Jeremy Hylton8caad492000-06-23 14:18:11 +00001774 }
1775 return 0;
1776}
1777
1778static int
1779dict_tp_clear(PyObject *op)
1780{
1781 PyDict_Clear(op);
1782 return 0;
1783}
1784
Tim Petersf7f88b12000-12-13 23:18:45 +00001785
Raymond Hettinger019a1482004-03-18 02:41:19 +00001786extern PyTypeObject PyDictIterKey_Type; /* Forward */
1787extern PyTypeObject PyDictIterValue_Type; /* Forward */
1788extern PyTypeObject PyDictIterItem_Type; /* Forward */
1789static PyObject *dictiter_new(dictobject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00001790
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001791#if 0
Guido van Rossum09e563a2001-05-01 12:10:21 +00001792static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001793dict_iterkeys(dictobject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00001794{
Raymond Hettinger019a1482004-03-18 02:41:19 +00001795 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00001796}
1797
1798static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001799dict_itervalues(dictobject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00001800{
Raymond Hettinger019a1482004-03-18 02:41:19 +00001801 return dictiter_new(dict, &PyDictIterValue_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00001802}
1803
1804static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001805dict_iteritems(dictobject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00001806{
Raymond Hettinger019a1482004-03-18 02:41:19 +00001807 return dictiter_new(dict, &PyDictIterItem_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00001808}
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001809#endif
Guido van Rossum09e563a2001-05-01 12:10:21 +00001810
1811
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00001812PyDoc_STRVAR(contains__doc__,
1813"D.__contains__(k) -> True if D has a key k, else False");
1814
1815PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
1816
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001817PyDoc_STRVAR(get__doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00001818"D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.");
Tim Petersf7f88b12000-12-13 23:18:45 +00001819
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001820PyDoc_STRVAR(setdefault_doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00001821"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 +00001822
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001823PyDoc_STRVAR(pop__doc__,
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001824"D.pop(k[,d]) -> v, remove specified key and return the corresponding value\n\
1825If key is not found, d is returned if given, otherwise KeyError is raised");
Guido van Rossume027d982002-04-12 15:11:59 +00001826
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001827PyDoc_STRVAR(popitem__doc__,
Tim Petersf7f88b12000-12-13 23:18:45 +00001828"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000018292-tuple; but raise KeyError if D is empty");
Tim Petersf7f88b12000-12-13 23:18:45 +00001830
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001831#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001832PyDoc_STRVAR(keys__doc__,
1833"D.keys() -> list of D's keys");
Tim Petersf7f88b12000-12-13 23:18:45 +00001834
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001835PyDoc_STRVAR(items__doc__,
1836"D.items() -> list of D's (key, value) pairs, as 2-tuples");
Tim Petersf7f88b12000-12-13 23:18:45 +00001837
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001838PyDoc_STRVAR(values__doc__,
1839"D.values() -> list of D's values");
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001840#endif
Tim Petersf7f88b12000-12-13 23:18:45 +00001841
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001842PyDoc_STRVAR(update__doc__,
Guido van Rossumb90c8482007-02-10 01:11:45 +00001843"D.update(E, **F) -> None. Update D from E and F: for k in E: D[k] = E[k]\
1844\n(if E has keys else: for (k, v) in E: D[k] = v) then: for k in F: D[k] = F[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00001845
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001846PyDoc_STRVAR(fromkeys__doc__,
1847"dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.\n\
1848v defaults to None.");
1849
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001850PyDoc_STRVAR(clear__doc__,
1851"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00001852
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001853PyDoc_STRVAR(copy__doc__,
1854"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00001855
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001856#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001857PyDoc_STRVAR(iterkeys__doc__,
1858"D.iterkeys() -> an iterator over the keys of D");
Guido van Rossum09e563a2001-05-01 12:10:21 +00001859
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001860PyDoc_STRVAR(itervalues__doc__,
1861"D.itervalues() -> an iterator over the values of D");
Guido van Rossum09e563a2001-05-01 12:10:21 +00001862
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001863PyDoc_STRVAR(iteritems__doc__,
1864"D.iteritems() -> an iterator over the (key, value) items of D");
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001865#endif
Guido van Rossum09e563a2001-05-01 12:10:21 +00001866
Guido van Rossumb90c8482007-02-10 01:11:45 +00001867/* Forward */
1868static PyObject *dictkeys_new(PyObject *);
1869static PyObject *dictitems_new(PyObject *);
1870static PyObject *dictvalues_new(PyObject *);
1871
1872PyDoc_STRVAR(KEYS__doc__, "D.KEYS() -> a set-like object for D's keys");
1873PyDoc_STRVAR(ITEMS__doc__, "D.ITEMS() -> a set-like object for D's items");
1874PyDoc_STRVAR(VALUES__doc__, "D.VALUES() -> a set-like object for D's values");
1875
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001876static PyMethodDef mapp_methods[] = {
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001877 {"__contains__",(PyCFunction)dict_contains, METH_O | METH_COEXIST,
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00001878 contains__doc__},
Raymond Hettinger0c669672003-12-13 13:31:55 +00001879 {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00001880 getitem__doc__},
Tim Petersf7f88b12000-12-13 23:18:45 +00001881 {"get", (PyCFunction)dict_get, METH_VARARGS,
1882 get__doc__},
1883 {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS,
1884 setdefault_doc__},
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001885 {"pop", (PyCFunction)dict_pop, METH_VARARGS,
Just van Rossuma797d812002-11-23 09:45:04 +00001886 pop__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001887 {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
Tim Petersf7f88b12000-12-13 23:18:45 +00001888 popitem__doc__},
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001889#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001890 {"keys", (PyCFunction)dict_keys, METH_NOARGS,
Tim Petersf7f88b12000-12-13 23:18:45 +00001891 keys__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001892 {"items", (PyCFunction)dict_items, METH_NOARGS,
Tim Petersf7f88b12000-12-13 23:18:45 +00001893 items__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001894 {"values", (PyCFunction)dict_values, METH_NOARGS,
Tim Petersf7f88b12000-12-13 23:18:45 +00001895 values__doc__},
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001896#endif
1897 {"keys", (PyCFunction)dictkeys_new, METH_NOARGS,
1898 KEYS__doc__},
1899 {"items", (PyCFunction)dictitems_new, METH_NOARGS,
1900 ITEMS__doc__},
1901 {"values", (PyCFunction)dictvalues_new, METH_NOARGS,
1902 VALUES__doc__},
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001903 {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
Tim Petersf7f88b12000-12-13 23:18:45 +00001904 update__doc__},
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001905 {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS,
1906 fromkeys__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001907 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
Tim Petersf7f88b12000-12-13 23:18:45 +00001908 clear__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001909 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
Tim Petersf7f88b12000-12-13 23:18:45 +00001910 copy__doc__},
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001911#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001912 {"iterkeys", (PyCFunction)dict_iterkeys, METH_NOARGS,
Guido van Rossum09e563a2001-05-01 12:10:21 +00001913 iterkeys__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001914 {"itervalues", (PyCFunction)dict_itervalues, METH_NOARGS,
Guido van Rossum09e563a2001-05-01 12:10:21 +00001915 itervalues__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001916 {"iteritems", (PyCFunction)dict_iteritems, METH_NOARGS,
Guido van Rossum09e563a2001-05-01 12:10:21 +00001917 iteritems__doc__},
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001918#endif
Tim Petersf7f88b12000-12-13 23:18:45 +00001919 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001920};
1921
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001922/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00001923int
1924PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001925{
1926 long hash;
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00001927 dictobject *mp = (dictobject *)op;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001928 dictentry *ep;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001929
Tim Peters0ab085c2001-09-14 00:25:33 +00001930 if (!PyString_CheckExact(key) ||
Tim Peters1f7df352002-03-29 03:29:08 +00001931 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001932 hash = PyObject_Hash(key);
1933 if (hash == -1)
1934 return -1;
1935 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001936 ep = (mp->ma_lookup)(mp, key, hash);
1937 return ep == NULL ? -1 : (ep->me_value != NULL);
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001938}
1939
Thomas Wouterscf297e42007-02-23 15:07:44 +00001940/* Internal version of PyDict_Contains used when the hash value is already known */
1941int
1942_PyDict_Contains(PyObject *op, PyObject *key, long hash)
1943{
1944 dictobject *mp = (dictobject *)op;
1945 dictentry *ep;
1946
1947 ep = (mp->ma_lookup)(mp, key, hash);
1948 return ep == NULL ? -1 : (ep->me_value != NULL);
1949}
1950
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001951/* Hack to implement "key in dict" */
1952static PySequenceMethods dict_as_sequence = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001953 0, /* sq_length */
1954 0, /* sq_concat */
1955 0, /* sq_repeat */
1956 0, /* sq_item */
1957 0, /* sq_slice */
1958 0, /* sq_ass_item */
1959 0, /* sq_ass_slice */
1960 PyDict_Contains, /* sq_contains */
1961 0, /* sq_inplace_concat */
1962 0, /* sq_inplace_repeat */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001963};
1964
Guido van Rossum09e563a2001-05-01 12:10:21 +00001965static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001966dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1967{
1968 PyObject *self;
1969
1970 assert(type != NULL && type->tp_alloc != NULL);
1971 self = type->tp_alloc(type, 0);
1972 if (self != NULL) {
1973 PyDictObject *d = (PyDictObject *)self;
1974 /* It's guaranteed that tp->alloc zeroed out the struct. */
1975 assert(d->ma_table == NULL && d->ma_fill == 0 && d->ma_used == 0);
1976 INIT_NONZERO_DICT_SLOTS(d);
1977 d->ma_lookup = lookdict_string;
1978#ifdef SHOW_CONVERSION_COUNTS
1979 ++created;
1980#endif
1981 }
1982 return self;
1983}
1984
Tim Peters25786c02001-09-02 08:22:48 +00001985static int
1986dict_init(PyObject *self, PyObject *args, PyObject *kwds)
1987{
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001988 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00001989}
1990
Tim Peters6d6c1a32001-08-02 04:15:00 +00001991static PyObject *
Guido van Rossum09e563a2001-05-01 12:10:21 +00001992dict_iter(dictobject *dict)
1993{
Raymond Hettinger019a1482004-03-18 02:41:19 +00001994 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00001995}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001996
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001997PyDoc_STRVAR(dictionary_doc,
Tim Petersa427a2b2001-10-29 22:25:45 +00001998"dict() -> new empty dictionary.\n"
1999"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Tim Peters1fc240e2001-10-26 05:06:50 +00002000" (key, value) pairs.\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00002001"dict(seq) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00002002" d = {}\n"
2003" for k, v in seq:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00002004" d[k] = v\n"
2005"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
2006" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00002007
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002008PyTypeObject PyDict_Type = {
2009 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002010 0,
Tim Petersa427a2b2001-10-29 22:25:45 +00002011 "dict",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002012 sizeof(dictobject),
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002013 0,
Guido van Rossumb9324202001-01-18 00:39:02 +00002014 (destructor)dict_dealloc, /* tp_dealloc */
2015 (printfunc)dict_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002016 0, /* tp_getattr */
Guido van Rossumb9324202001-01-18 00:39:02 +00002017 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002018 0, /* tp_compare */
Guido van Rossumb9324202001-01-18 00:39:02 +00002019 (reprfunc)dict_repr, /* tp_repr */
2020 0, /* tp_as_number */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00002021 &dict_as_sequence, /* tp_as_sequence */
Guido van Rossumb9324202001-01-18 00:39:02 +00002022 &dict_as_mapping, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002023 0, /* tp_hash */
Guido van Rossumb9324202001-01-18 00:39:02 +00002024 0, /* tp_call */
2025 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002026 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossumb9324202001-01-18 00:39:02 +00002027 0, /* tp_setattro */
2028 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002029 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00002030 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters25786c02001-09-02 08:22:48 +00002031 dictionary_doc, /* tp_doc */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002032 dict_traverse, /* tp_traverse */
2033 dict_tp_clear, /* tp_clear */
Tim Peterse63415e2001-05-08 04:38:29 +00002034 dict_richcompare, /* tp_richcompare */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002035 0, /* tp_weaklistoffset */
Guido van Rossum09e563a2001-05-01 12:10:21 +00002036 (getiterfunc)dict_iter, /* tp_iter */
Guido van Rossum213c7a62001-04-23 14:08:49 +00002037 0, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002038 mapp_methods, /* tp_methods */
2039 0, /* tp_members */
2040 0, /* tp_getset */
2041 0, /* tp_base */
2042 0, /* tp_dict */
2043 0, /* tp_descr_get */
2044 0, /* tp_descr_set */
2045 0, /* tp_dictoffset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002046 dict_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002047 PyType_GenericAlloc, /* tp_alloc */
2048 dict_new, /* tp_new */
Neil Schemenauer6189b892002-04-12 02:43:00 +00002049 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002050};
2051
Guido van Rossum3cca2451997-05-16 14:23:33 +00002052/* For backward compatibility with old dictionary interface */
2053
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002054PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00002055PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002056{
Guido van Rossum3cca2451997-05-16 14:23:33 +00002057 PyObject *kv, *rv;
2058 kv = PyString_FromString(key);
2059 if (kv == NULL)
2060 return NULL;
Guido van Rossum3cca2451997-05-16 14:23:33 +00002061 rv = PyDict_GetItem(v, kv);
2062 Py_DECREF(kv);
2063 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002064}
2065
2066int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00002067PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002068{
Guido van Rossum3cca2451997-05-16 14:23:33 +00002069 PyObject *kv;
2070 int err;
2071 kv = PyString_FromString(key);
2072 if (kv == NULL)
Guido van Rossum037b2201997-05-20 18:35:19 +00002073 return -1;
Guido van Rossum4f3bf1e1997-09-29 23:31:11 +00002074 PyString_InternInPlace(&kv); /* XXX Should we really? */
Guido van Rossum3cca2451997-05-16 14:23:33 +00002075 err = PyDict_SetItem(v, kv, item);
2076 Py_DECREF(kv);
2077 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002078}
2079
2080int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00002081PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002082{
Guido van Rossum3cca2451997-05-16 14:23:33 +00002083 PyObject *kv;
2084 int err;
2085 kv = PyString_FromString(key);
2086 if (kv == NULL)
Guido van Rossum037b2201997-05-20 18:35:19 +00002087 return -1;
Guido van Rossum3cca2451997-05-16 14:23:33 +00002088 err = PyDict_DelItem(v, kv);
2089 Py_DECREF(kv);
2090 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002091}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002092
Raymond Hettinger019a1482004-03-18 02:41:19 +00002093/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002094
2095typedef struct {
2096 PyObject_HEAD
Guido van Rossum2147df72002-07-16 20:30:22 +00002097 dictobject *di_dict; /* Set to NULL when iterator is exhausted */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002098 Py_ssize_t di_used;
2099 Py_ssize_t di_pos;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002100 PyObject* di_result; /* reusable result tuple for iteritems */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002101 Py_ssize_t len;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002102} dictiterobject;
2103
2104static PyObject *
Raymond Hettinger019a1482004-03-18 02:41:19 +00002105dictiter_new(dictobject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002106{
2107 dictiterobject *di;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002108 di = PyObject_New(dictiterobject, itertype);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002109 if (di == NULL)
2110 return NULL;
2111 Py_INCREF(dict);
2112 di->di_dict = dict;
Guido van Rossumb1f35bf2001-05-02 15:13:44 +00002113 di->di_used = dict->ma_used;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002114 di->di_pos = 0;
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002115 di->len = dict->ma_used;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002116 if (itertype == &PyDictIterItem_Type) {
2117 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
2118 if (di->di_result == NULL) {
2119 Py_DECREF(di);
2120 return NULL;
2121 }
2122 }
2123 else
2124 di->di_result = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002125 return (PyObject *)di;
2126}
2127
2128static void
2129dictiter_dealloc(dictiterobject *di)
2130{
Guido van Rossum2147df72002-07-16 20:30:22 +00002131 Py_XDECREF(di->di_dict);
Raymond Hettinger019a1482004-03-18 02:41:19 +00002132 Py_XDECREF(di->di_result);
Neil Schemenauer6189b892002-04-12 02:43:00 +00002133 PyObject_Del(di);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002134}
2135
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002136static PyObject *
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002137dictiter_len(dictiterobject *di)
2138{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002139 Py_ssize_t len = 0;
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00002140 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002141 len = di->len;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002142 return PyInt_FromSize_t(len);
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002143}
2144
Guido van Rossumb90c8482007-02-10 01:11:45 +00002145PyDoc_STRVAR(length_hint_doc,
2146 "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002147
2148static PyMethodDef dictiter_methods[] = {
Guido van Rossumb90c8482007-02-10 01:11:45 +00002149 {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS,
2150 length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002151 {NULL, NULL} /* sentinel */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002152};
2153
Raymond Hettinger019a1482004-03-18 02:41:19 +00002154static PyObject *dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00002155{
Raymond Hettinger019a1482004-03-18 02:41:19 +00002156 PyObject *key;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002157 register Py_ssize_t i, mask;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002158 register dictentry *ep;
2159 dictobject *d = di->di_dict;
Guido van Rossum213c7a62001-04-23 14:08:49 +00002160
Raymond Hettinger019a1482004-03-18 02:41:19 +00002161 if (d == NULL)
Guido van Rossum2147df72002-07-16 20:30:22 +00002162 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002163 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00002164
Raymond Hettinger019a1482004-03-18 02:41:19 +00002165 if (di->di_used != d->ma_used) {
Guido van Rossum213c7a62001-04-23 14:08:49 +00002166 PyErr_SetString(PyExc_RuntimeError,
2167 "dictionary changed size during iteration");
Guido van Rossum2147df72002-07-16 20:30:22 +00002168 di->di_used = -1; /* Make this state sticky */
Guido van Rossum213c7a62001-04-23 14:08:49 +00002169 return NULL;
2170 }
Guido van Rossum2147df72002-07-16 20:30:22 +00002171
Raymond Hettinger019a1482004-03-18 02:41:19 +00002172 i = di->di_pos;
2173 if (i < 0)
2174 goto fail;
2175 ep = d->ma_table;
2176 mask = d->ma_mask;
2177 while (i <= mask && ep[i].me_value == NULL)
2178 i++;
2179 di->di_pos = i+1;
2180 if (i > mask)
2181 goto fail;
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002182 di->len--;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002183 key = ep[i].me_key;
2184 Py_INCREF(key);
2185 return key;
2186
2187fail:
2188 Py_DECREF(d);
Guido van Rossum2147df72002-07-16 20:30:22 +00002189 di->di_dict = NULL;
Guido van Rossum213c7a62001-04-23 14:08:49 +00002190 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002191}
2192
Raymond Hettinger019a1482004-03-18 02:41:19 +00002193PyTypeObject PyDictIterKey_Type = {
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002194 PyObject_HEAD_INIT(&PyType_Type)
2195 0, /* ob_size */
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002196 "dictionary-keyiterator", /* tp_name */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002197 sizeof(dictiterobject), /* tp_basicsize */
2198 0, /* tp_itemsize */
2199 /* methods */
2200 (destructor)dictiter_dealloc, /* tp_dealloc */
2201 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002202 0, /* tp_getattr */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002203 0, /* tp_setattr */
2204 0, /* tp_compare */
2205 0, /* tp_repr */
2206 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002207 0, /* tp_as_sequence */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002208 0, /* tp_as_mapping */
2209 0, /* tp_hash */
2210 0, /* tp_call */
2211 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002212 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002213 0, /* tp_setattro */
2214 0, /* tp_as_buffer */
2215 Py_TPFLAGS_DEFAULT, /* tp_flags */
2216 0, /* tp_doc */
2217 0, /* tp_traverse */
2218 0, /* tp_clear */
2219 0, /* tp_richcompare */
2220 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002221 PyObject_SelfIter, /* tp_iter */
Raymond Hettinger019a1482004-03-18 02:41:19 +00002222 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002223 dictiter_methods, /* tp_methods */
2224 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00002225};
2226
2227static PyObject *dictiter_iternextvalue(dictiterobject *di)
2228{
2229 PyObject *value;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002230 register Py_ssize_t i, mask;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002231 register dictentry *ep;
2232 dictobject *d = di->di_dict;
2233
2234 if (d == NULL)
2235 return NULL;
2236 assert (PyDict_Check(d));
2237
2238 if (di->di_used != d->ma_used) {
2239 PyErr_SetString(PyExc_RuntimeError,
2240 "dictionary changed size during iteration");
2241 di->di_used = -1; /* Make this state sticky */
2242 return NULL;
2243 }
2244
2245 i = di->di_pos;
Guido van Rossum09240f62004-03-20 19:11:58 +00002246 mask = d->ma_mask;
2247 if (i < 0 || i > mask)
Raymond Hettinger019a1482004-03-18 02:41:19 +00002248 goto fail;
2249 ep = d->ma_table;
Guido van Rossum09240f62004-03-20 19:11:58 +00002250 while ((value=ep[i].me_value) == NULL) {
Raymond Hettinger019a1482004-03-18 02:41:19 +00002251 i++;
Guido van Rossum09240f62004-03-20 19:11:58 +00002252 if (i > mask)
2253 goto fail;
2254 }
Raymond Hettinger019a1482004-03-18 02:41:19 +00002255 di->di_pos = i+1;
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002256 di->len--;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002257 Py_INCREF(value);
2258 return value;
2259
2260fail:
2261 Py_DECREF(d);
2262 di->di_dict = NULL;
2263 return NULL;
2264}
2265
2266PyTypeObject PyDictIterValue_Type = {
2267 PyObject_HEAD_INIT(&PyType_Type)
2268 0, /* ob_size */
2269 "dictionary-valueiterator", /* tp_name */
2270 sizeof(dictiterobject), /* tp_basicsize */
2271 0, /* tp_itemsize */
2272 /* methods */
2273 (destructor)dictiter_dealloc, /* tp_dealloc */
2274 0, /* tp_print */
2275 0, /* tp_getattr */
2276 0, /* tp_setattr */
2277 0, /* tp_compare */
2278 0, /* tp_repr */
2279 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002280 0, /* tp_as_sequence */
Raymond Hettinger019a1482004-03-18 02:41:19 +00002281 0, /* tp_as_mapping */
2282 0, /* tp_hash */
2283 0, /* tp_call */
2284 0, /* tp_str */
2285 PyObject_GenericGetAttr, /* tp_getattro */
2286 0, /* tp_setattro */
2287 0, /* tp_as_buffer */
2288 Py_TPFLAGS_DEFAULT, /* tp_flags */
2289 0, /* tp_doc */
2290 0, /* tp_traverse */
2291 0, /* tp_clear */
2292 0, /* tp_richcompare */
2293 0, /* tp_weaklistoffset */
2294 PyObject_SelfIter, /* tp_iter */
2295 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002296 dictiter_methods, /* tp_methods */
2297 0,
Raymond Hettinger019a1482004-03-18 02:41:19 +00002298};
2299
2300static PyObject *dictiter_iternextitem(dictiterobject *di)
2301{
2302 PyObject *key, *value, *result = di->di_result;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002303 register Py_ssize_t i, mask;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002304 register dictentry *ep;
2305 dictobject *d = di->di_dict;
2306
2307 if (d == NULL)
2308 return NULL;
2309 assert (PyDict_Check(d));
2310
2311 if (di->di_used != d->ma_used) {
2312 PyErr_SetString(PyExc_RuntimeError,
2313 "dictionary changed size during iteration");
2314 di->di_used = -1; /* Make this state sticky */
2315 return NULL;
2316 }
2317
2318 i = di->di_pos;
2319 if (i < 0)
2320 goto fail;
2321 ep = d->ma_table;
2322 mask = d->ma_mask;
2323 while (i <= mask && ep[i].me_value == NULL)
2324 i++;
2325 di->di_pos = i+1;
2326 if (i > mask)
2327 goto fail;
2328
2329 if (result->ob_refcnt == 1) {
2330 Py_INCREF(result);
2331 Py_DECREF(PyTuple_GET_ITEM(result, 0));
2332 Py_DECREF(PyTuple_GET_ITEM(result, 1));
2333 } else {
2334 result = PyTuple_New(2);
Tim Peters60b29962006-01-01 01:19:23 +00002335 if (result == NULL)
Raymond Hettinger019a1482004-03-18 02:41:19 +00002336 return NULL;
2337 }
Raymond Hettinger0ce6dc82004-03-18 08:38:00 +00002338 di->len--;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002339 key = ep[i].me_key;
2340 value = ep[i].me_value;
2341 Py_INCREF(key);
2342 Py_INCREF(value);
2343 PyTuple_SET_ITEM(result, 0, key);
2344 PyTuple_SET_ITEM(result, 1, value);
2345 return result;
2346
2347fail:
2348 Py_DECREF(d);
2349 di->di_dict = NULL;
2350 return NULL;
2351}
2352
2353PyTypeObject PyDictIterItem_Type = {
2354 PyObject_HEAD_INIT(&PyType_Type)
2355 0, /* ob_size */
2356 "dictionary-itemiterator", /* tp_name */
2357 sizeof(dictiterobject), /* tp_basicsize */
2358 0, /* tp_itemsize */
2359 /* methods */
2360 (destructor)dictiter_dealloc, /* tp_dealloc */
2361 0, /* tp_print */
2362 0, /* tp_getattr */
2363 0, /* tp_setattr */
2364 0, /* tp_compare */
2365 0, /* tp_repr */
2366 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002367 0, /* tp_as_sequence */
Raymond Hettinger019a1482004-03-18 02:41:19 +00002368 0, /* tp_as_mapping */
2369 0, /* tp_hash */
2370 0, /* tp_call */
2371 0, /* tp_str */
2372 PyObject_GenericGetAttr, /* tp_getattro */
2373 0, /* tp_setattro */
2374 0, /* tp_as_buffer */
2375 Py_TPFLAGS_DEFAULT, /* tp_flags */
2376 0, /* tp_doc */
2377 0, /* tp_traverse */
2378 0, /* tp_clear */
2379 0, /* tp_richcompare */
2380 0, /* tp_weaklistoffset */
2381 PyObject_SelfIter, /* tp_iter */
2382 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002383 dictiter_methods, /* tp_methods */
2384 0,
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002385};
Guido van Rossumb90c8482007-02-10 01:11:45 +00002386
2387
Guido van Rossum3ac67412007-02-10 18:55:06 +00002388/***********************************************/
Guido van Rossumb90c8482007-02-10 01:11:45 +00002389/* View objects for keys(), items(), values(). */
Guido van Rossum3ac67412007-02-10 18:55:06 +00002390/***********************************************/
2391
Guido van Rossumb90c8482007-02-10 01:11:45 +00002392/* While this is incomplete, we use KEYS(), ITEMS(), VALUES(). */
2393
2394/* The instance lay-out is the same for all three; but the type differs. */
2395
2396typedef struct {
2397 PyObject_HEAD
Guido van Rossum3ac67412007-02-10 18:55:06 +00002398 dictobject *dv_dict;
Guido van Rossumb90c8482007-02-10 01:11:45 +00002399} dictviewobject;
2400
2401
2402static void
Guido van Rossum3ac67412007-02-10 18:55:06 +00002403dictview_dealloc(dictviewobject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00002404{
Guido van Rossum3ac67412007-02-10 18:55:06 +00002405 Py_XDECREF(dv->dv_dict);
2406 PyObject_Del(dv);
Guido van Rossumb90c8482007-02-10 01:11:45 +00002407}
2408
Guido van Rossum83825ac2007-02-10 04:54:19 +00002409static Py_ssize_t
Guido van Rossum3ac67412007-02-10 18:55:06 +00002410dictview_len(dictviewobject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00002411{
2412 Py_ssize_t len = 0;
Guido van Rossum3ac67412007-02-10 18:55:06 +00002413 if (dv->dv_dict != NULL)
2414 len = dv->dv_dict->ma_used;
Guido van Rossum83825ac2007-02-10 04:54:19 +00002415 return len;
Guido van Rossumb90c8482007-02-10 01:11:45 +00002416}
2417
2418static PyObject *
2419dictview_new(PyObject *dict, PyTypeObject *type)
2420{
Guido van Rossum3ac67412007-02-10 18:55:06 +00002421 dictviewobject *dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00002422 if (dict == NULL) {
2423 PyErr_BadInternalCall();
2424 return NULL;
2425 }
2426 if (!PyDict_Check(dict)) {
2427 /* XXX Get rid of this restriction later */
2428 PyErr_Format(PyExc_TypeError,
2429 "%s() requires a dict argument, not '%s'",
2430 type->tp_name, dict->ob_type->tp_name);
2431 return NULL;
2432 }
Guido van Rossum3ac67412007-02-10 18:55:06 +00002433 dv = PyObject_New(dictviewobject, type);
2434 if (dv == NULL)
Guido van Rossumb90c8482007-02-10 01:11:45 +00002435 return NULL;
2436 Py_INCREF(dict);
Guido van Rossum3ac67412007-02-10 18:55:06 +00002437 dv->dv_dict = (dictobject *)dict;
2438 return (PyObject *)dv;
Guido van Rossumb90c8482007-02-10 01:11:45 +00002439}
2440
Guido van Rossumd9214d12007-02-12 02:23:40 +00002441/* Forward */
2442PyTypeObject PyDictKeys_Type;
2443PyTypeObject PyDictItems_Type;
2444PyTypeObject PyDictValues_Type;
2445
2446#define PyDictKeys_Check(obj) ((obj)->ob_type == &PyDictKeys_Type)
2447#define PyDictItems_Check(obj) ((obj)->ob_type == &PyDictItems_Type)
2448#define PyDictValues_Check(obj) ((obj)->ob_type == &PyDictValues_Type)
2449
2450/* This excludes Values, since they are not sets. */
2451# define PyDictViewSet_Check(obj) \
2452 (PyDictKeys_Check(obj) || PyDictItems_Check(obj))
2453
2454static int
2455all_contained_in(PyObject *self, PyObject *other)
2456{
2457 PyObject *iter = PyObject_GetIter(self);
2458 int ok = 1;
2459
2460 if (iter == NULL)
2461 return -1;
2462 for (;;) {
2463 PyObject *next = PyIter_Next(iter);
2464 if (next == NULL) {
2465 if (PyErr_Occurred())
2466 ok = -1;
2467 break;
2468 }
2469 ok = PySequence_Contains(other, next);
2470 Py_DECREF(next);
2471 if (ok <= 0)
2472 break;
2473 }
2474 Py_DECREF(iter);
2475 return ok;
2476}
2477
2478static PyObject *
2479dictview_richcompare(PyObject *self, PyObject *other, int op)
2480{
2481 assert(self != NULL);
2482 assert(PyDictViewSet_Check(self));
2483 assert(other != NULL);
2484 if ((op == Py_EQ || op == Py_NE) &&
2485 (PyAnySet_Check(other) || PyDictViewSet_Check(other)))
2486 {
2487 Py_ssize_t len_self, len_other;
2488 int ok;
2489 PyObject *result;
2490
2491 len_self = PyObject_Size(self);
2492 if (len_self < 0)
2493 return NULL;
2494 len_other = PyObject_Size(other);
2495 if (len_other < 0)
2496 return NULL;
2497 if (len_self != len_other)
2498 ok = 0;
2499 else if (len_self == 0)
2500 ok = 1;
2501 else
2502 ok = all_contained_in(self, other);
2503 if (ok < 0)
2504 return NULL;
2505 if (ok == (op == Py_EQ))
2506 result = Py_True;
2507 else
2508 result = Py_False;
2509 Py_INCREF(result);
2510 return result;
2511 }
2512 else {
2513 Py_INCREF(Py_NotImplemented);
2514 return Py_NotImplemented;
2515 }
2516}
2517
Guido van Rossum3ac67412007-02-10 18:55:06 +00002518/*** dict_keys ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00002519
2520static PyObject *
Guido van Rossum3ac67412007-02-10 18:55:06 +00002521dictkeys_iter(dictviewobject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00002522{
Guido van Rossum3ac67412007-02-10 18:55:06 +00002523 if (dv->dv_dict == NULL) {
Guido van Rossumb90c8482007-02-10 01:11:45 +00002524 Py_RETURN_NONE;
2525 }
Guido van Rossum3ac67412007-02-10 18:55:06 +00002526 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
2527}
2528
2529static int
2530dictkeys_contains(dictviewobject *dv, PyObject *obj)
2531{
2532 if (dv->dv_dict == NULL)
2533 return 0;
2534 return PyDict_Contains((PyObject *)dv->dv_dict, obj);
Guido van Rossumb90c8482007-02-10 01:11:45 +00002535}
2536
Guido van Rossum83825ac2007-02-10 04:54:19 +00002537static PySequenceMethods dictkeys_as_sequence = {
2538 (lenfunc)dictview_len, /* sq_length */
2539 0, /* sq_concat */
2540 0, /* sq_repeat */
2541 0, /* sq_item */
2542 0, /* sq_slice */
2543 0, /* sq_ass_item */
2544 0, /* sq_ass_slice */
Guido van Rossum3ac67412007-02-10 18:55:06 +00002545 (objobjproc)dictkeys_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00002546};
2547
Guido van Rossumb90c8482007-02-10 01:11:45 +00002548static PyMethodDef dictkeys_methods[] = {
Guido van Rossumb90c8482007-02-10 01:11:45 +00002549 {NULL, NULL} /* sentinel */
2550};
2551
2552PyTypeObject PyDictKeys_Type = {
2553 PyObject_HEAD_INIT(&PyType_Type)
2554 0, /* ob_size */
2555 "dict_keys", /* tp_name */
2556 sizeof(dictviewobject), /* tp_basicsize */
2557 0, /* tp_itemsize */
2558 /* methods */
2559 (destructor)dictview_dealloc, /* tp_dealloc */
2560 0, /* tp_print */
2561 0, /* tp_getattr */
2562 0, /* tp_setattr */
2563 0, /* tp_compare */
2564 0, /* tp_repr */
2565 0, /* tp_as_number */
Guido van Rossum83825ac2007-02-10 04:54:19 +00002566 &dictkeys_as_sequence, /* tp_as_sequence */
Guido van Rossumb90c8482007-02-10 01:11:45 +00002567 0, /* tp_as_mapping */
2568 0, /* tp_hash */
2569 0, /* tp_call */
2570 0, /* tp_str */
2571 PyObject_GenericGetAttr, /* tp_getattro */
2572 0, /* tp_setattro */
2573 0, /* tp_as_buffer */
2574 Py_TPFLAGS_DEFAULT, /* tp_flags */
2575 0, /* tp_doc */
2576 0, /* tp_traverse */
2577 0, /* tp_clear */
Guido van Rossumd9214d12007-02-12 02:23:40 +00002578 dictview_richcompare, /* tp_richcompare */
Guido van Rossumb90c8482007-02-10 01:11:45 +00002579 0, /* tp_weaklistoffset */
2580 (getiterfunc)dictkeys_iter, /* tp_iter */
2581 0, /* tp_iternext */
2582 dictkeys_methods, /* tp_methods */
2583 0,
2584};
2585
2586static PyObject *
2587dictkeys_new(PyObject *dict)
2588{
2589 return dictview_new(dict, &PyDictKeys_Type);
2590}
2591
Guido van Rossum3ac67412007-02-10 18:55:06 +00002592/*** dict_items ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00002593
2594static PyObject *
Guido van Rossum3ac67412007-02-10 18:55:06 +00002595dictitems_iter(dictviewobject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00002596{
Guido van Rossum3ac67412007-02-10 18:55:06 +00002597 if (dv->dv_dict == NULL) {
Guido van Rossumb90c8482007-02-10 01:11:45 +00002598 Py_RETURN_NONE;
2599 }
Guido van Rossum3ac67412007-02-10 18:55:06 +00002600 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
2601}
2602
2603static int
2604dictitems_contains(dictviewobject *dv, PyObject *obj)
2605{
2606 PyObject *key, *value, *found;
2607 if (dv->dv_dict == NULL)
2608 return 0;
2609 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
2610 return 0;
2611 key = PyTuple_GET_ITEM(obj, 0);
2612 value = PyTuple_GET_ITEM(obj, 1);
2613 found = PyDict_GetItem((PyObject *)dv->dv_dict, key);
2614 if (found == NULL) {
2615 if (PyErr_Occurred())
2616 return -1;
2617 return 0;
2618 }
2619 return PyObject_RichCompareBool(value, found, Py_EQ);
Guido van Rossumb90c8482007-02-10 01:11:45 +00002620}
2621
Guido van Rossum83825ac2007-02-10 04:54:19 +00002622static PySequenceMethods dictitems_as_sequence = {
2623 (lenfunc)dictview_len, /* sq_length */
2624 0, /* sq_concat */
2625 0, /* sq_repeat */
2626 0, /* sq_item */
2627 0, /* sq_slice */
2628 0, /* sq_ass_item */
2629 0, /* sq_ass_slice */
Guido van Rossum3ac67412007-02-10 18:55:06 +00002630 (objobjproc)dictitems_contains, /* sq_contains */
Guido van Rossum83825ac2007-02-10 04:54:19 +00002631};
2632
Guido van Rossumb90c8482007-02-10 01:11:45 +00002633static PyMethodDef dictitems_methods[] = {
Guido van Rossumb90c8482007-02-10 01:11:45 +00002634 {NULL, NULL} /* sentinel */
2635};
2636
2637PyTypeObject PyDictItems_Type = {
2638 PyObject_HEAD_INIT(&PyType_Type)
2639 0, /* ob_size */
2640 "dict_items", /* tp_name */
2641 sizeof(dictviewobject), /* tp_basicsize */
2642 0, /* tp_itemsize */
2643 /* methods */
2644 (destructor)dictview_dealloc, /* tp_dealloc */
2645 0, /* tp_print */
2646 0, /* tp_getattr */
2647 0, /* tp_setattr */
2648 0, /* tp_compare */
2649 0, /* tp_repr */
2650 0, /* tp_as_number */
Guido van Rossum83825ac2007-02-10 04:54:19 +00002651 &dictitems_as_sequence, /* tp_as_sequence */
Guido van Rossumb90c8482007-02-10 01:11:45 +00002652 0, /* tp_as_mapping */
2653 0, /* tp_hash */
2654 0, /* tp_call */
2655 0, /* tp_str */
2656 PyObject_GenericGetAttr, /* tp_getattro */
2657 0, /* tp_setattro */
2658 0, /* tp_as_buffer */
2659 Py_TPFLAGS_DEFAULT, /* tp_flags */
2660 0, /* tp_doc */
2661 0, /* tp_traverse */
2662 0, /* tp_clear */
Guido van Rossumd9214d12007-02-12 02:23:40 +00002663 dictview_richcompare, /* tp_richcompare */
Guido van Rossumb90c8482007-02-10 01:11:45 +00002664 0, /* tp_weaklistoffset */
2665 (getiterfunc)dictitems_iter, /* tp_iter */
2666 0, /* tp_iternext */
2667 dictitems_methods, /* tp_methods */
2668 0,
2669};
2670
2671static PyObject *
2672dictitems_new(PyObject *dict)
2673{
2674 return dictview_new(dict, &PyDictItems_Type);
2675}
2676
Guido van Rossum3ac67412007-02-10 18:55:06 +00002677/*** dict_values ***/
Guido van Rossumb90c8482007-02-10 01:11:45 +00002678
2679static PyObject *
Guido van Rossum3ac67412007-02-10 18:55:06 +00002680dictvalues_iter(dictviewobject *dv)
Guido van Rossumb90c8482007-02-10 01:11:45 +00002681{
Guido van Rossum3ac67412007-02-10 18:55:06 +00002682 if (dv->dv_dict == NULL) {
Guido van Rossumb90c8482007-02-10 01:11:45 +00002683 Py_RETURN_NONE;
2684 }
Guido van Rossum3ac67412007-02-10 18:55:06 +00002685 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
Guido van Rossumb90c8482007-02-10 01:11:45 +00002686}
2687
Guido van Rossum83825ac2007-02-10 04:54:19 +00002688static PySequenceMethods dictvalues_as_sequence = {
2689 (lenfunc)dictview_len, /* sq_length */
2690 0, /* sq_concat */
2691 0, /* sq_repeat */
2692 0, /* sq_item */
2693 0, /* sq_slice */
2694 0, /* sq_ass_item */
2695 0, /* sq_ass_slice */
2696 (objobjproc)0, /* sq_contains */
2697};
2698
Guido van Rossumb90c8482007-02-10 01:11:45 +00002699static PyMethodDef dictvalues_methods[] = {
Guido van Rossumb90c8482007-02-10 01:11:45 +00002700 {NULL, NULL} /* sentinel */
2701};
2702
2703PyTypeObject PyDictValues_Type = {
2704 PyObject_HEAD_INIT(&PyType_Type)
2705 0, /* ob_size */
2706 "dict_values", /* tp_name */
2707 sizeof(dictviewobject), /* tp_basicsize */
2708 0, /* tp_itemsize */
2709 /* methods */
2710 (destructor)dictview_dealloc, /* tp_dealloc */
2711 0, /* tp_print */
2712 0, /* tp_getattr */
2713 0, /* tp_setattr */
2714 0, /* tp_compare */
2715 0, /* tp_repr */
2716 0, /* tp_as_number */
Guido van Rossum83825ac2007-02-10 04:54:19 +00002717 &dictvalues_as_sequence, /* tp_as_sequence */
Guido van Rossumb90c8482007-02-10 01:11:45 +00002718 0, /* tp_as_mapping */
2719 0, /* tp_hash */
2720 0, /* tp_call */
2721 0, /* tp_str */
2722 PyObject_GenericGetAttr, /* tp_getattro */
2723 0, /* tp_setattro */
2724 0, /* tp_as_buffer */
2725 Py_TPFLAGS_DEFAULT, /* tp_flags */
2726 0, /* tp_doc */
2727 0, /* tp_traverse */
2728 0, /* tp_clear */
2729 0, /* tp_richcompare */
2730 0, /* tp_weaklistoffset */
2731 (getiterfunc)dictvalues_iter, /* tp_iter */
2732 0, /* tp_iternext */
2733 dictvalues_methods, /* tp_methods */
2734 0,
2735};
2736
2737static PyObject *
2738dictvalues_new(PyObject *dict)
2739{
2740 return dictview_new(dict, &PyDictValues_Type);
2741}