blob: 1be0f421502d14bfd8193220b5bc1be03777860e [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,
5 describing explorations into dictionary design and optimization.
6 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
Tim Peterseb28ef22001-06-02 05:27:19 +000015/* Define this out if you don't want conversion statistics on exit. */
Fred Drake1bff34a2000-08-31 19:31:38 +000016#undef SHOW_CONVERSION_COUNTS
17
Tim Peterseb28ef22001-06-02 05:27:19 +000018/* See large comment block below. This must be >= 1. */
19#define PERTURB_SHIFT 5
20
Guido van Rossum16e93a81997-01-28 00:00:11 +000021/*
Tim Peterseb28ef22001-06-02 05:27:19 +000022Major subtleties ahead: Most hash schemes depend on having a "good" hash
23function, in the sense of simulating randomness. Python doesn't: its most
24important hash functions (for strings and ints) are very regular in common
25cases:
Tim Peters15d49292001-05-27 07:39:22 +000026
Tim Peterseb28ef22001-06-02 05:27:19 +000027>>> map(hash, (0, 1, 2, 3))
28[0, 1, 2, 3]
29>>> map(hash, ("namea", "nameb", "namec", "named"))
30[-1658398457, -1658398460, -1658398459, -1658398462]
31>>>
Tim Peters15d49292001-05-27 07:39:22 +000032
Tim Peterseb28ef22001-06-02 05:27:19 +000033This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
34the low-order i bits as the initial table index is extremely fast, and there
35are no collisions at all for dicts indexed by a contiguous range of ints.
36The same is approximately true when keys are "consecutive" strings. So this
37gives better-than-random behavior in common cases, and that's very desirable.
Tim Peters15d49292001-05-27 07:39:22 +000038
Tim Peterseb28ef22001-06-02 05:27:19 +000039OTOH, when collisions occur, the tendency to fill contiguous slices of the
40hash table makes a good collision resolution strategy crucial. Taking only
41the last i bits of the hash code is also vulnerable: for example, consider
42[i << 16 for i in range(20000)] as a set of keys. Since ints are their own
43hash codes, and this fits in a dict of size 2**15, the last 15 bits of every
44hash code are all 0: they *all* map to the same table index.
Tim Peters15d49292001-05-27 07:39:22 +000045
Tim Peterseb28ef22001-06-02 05:27:19 +000046But catering to unusual cases should not slow the usual ones, so we just take
47the last i bits anyway. It's up to collision resolution to do the rest. If
48we *usually* find the key we're looking for on the first try (and, it turns
49out, we usually do -- the table load factor is kept under 2/3, so the odds
50are solidly in our favor), then it makes best sense to keep the initial index
51computation dirt cheap.
Tim Peters15d49292001-05-27 07:39:22 +000052
Tim Peterseb28ef22001-06-02 05:27:19 +000053The first half of collision resolution is to visit table indices via this
54recurrence:
Tim Peters15d49292001-05-27 07:39:22 +000055
Tim Peterseb28ef22001-06-02 05:27:19 +000056 j = ((5*j) + 1) mod 2**i
Tim Peters15d49292001-05-27 07:39:22 +000057
Tim Peterseb28ef22001-06-02 05:27:19 +000058For any initial j in range(2**i), repeating that 2**i times generates each
59int in range(2**i) exactly once (see any text on random-number generation for
60proof). By itself, this doesn't help much: like linear probing (setting
61j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
62order. This would be bad, except that's not the only thing we do, and it's
63actually *good* in the common cases where hash keys are consecutive. In an
64example that's really too small to make this entirely clear, for a table of
65size 2**3 the order of indices is:
Tim Peters15d49292001-05-27 07:39:22 +000066
Tim Peterseb28ef22001-06-02 05:27:19 +000067 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
68
69If two things come in at index 5, the first place we look after is index 2,
70not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
71Linear probing is deadly in this case because there the fixed probe order
72is the *same* as the order consecutive keys are likely to arrive. But it's
73extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
74and certain that consecutive hash codes do not.
75
76The other half of the strategy is to get the other bits of the hash code
77into play. This is done by initializing a (unsigned) vrbl "perturb" to the
78full hash code, and changing the recurrence to:
79
80 j = (5*j) + 1 + perturb;
81 perturb >>= PERTURB_SHIFT;
82 use j % 2**i as the next table index;
83
84Now the probe sequence depends (eventually) on every bit in the hash code,
85and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
86because it quickly magnifies small differences in the bits that didn't affect
87the initial index. Note that because perturb is unsigned, if the recurrence
88is executed often enough perturb eventually becomes and remains 0. At that
89point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
90that's certain to find an empty slot eventually (since it generates every int
91in range(2**i), and we make sure there's always at least one empty slot).
92
93Selecting a good value for PERTURB_SHIFT is a balancing act. You want it
94small so that the high bits of the hash code continue to affect the probe
95sequence across iterations; but you want it large so that in really bad cases
96the high-order hash bits have an effect on early iterations. 5 was "the
97best" in minimizing total collisions across experiments Tim Peters ran (on
98both normal and pathological cases), but 4 and 6 weren't significantly worse.
99
100Historical: Reimer Behrends contributed the idea of using a polynomial-based
101approach, using repeated multiplication by x in GF(2**n) where an irreducible
102polynomial for each table size was chosen such that x was a primitive root.
103Christian Tismer later extended that to use division by x instead, as an
104efficient way to get the high bits of the hash code into play. This scheme
105also gave excellent collision statistics, but was more expensive: two
106if-tests were required inside the loop; computing "the next" index took about
107the same number of operations but without as much potential parallelism
108(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
109above, and then shifting perturb can be done while the table index is being
110masked); and the dictobject struct required a member to hold the table's
111polynomial. In Tim's experiments the current scheme ran faster, produced
112equally good collision statistics, needed less code & used less memory.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000113*/
Tim Petersdea48ec2001-05-22 20:40:22 +0000114
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000115/* Object used as dummy key to fill deleted entries */
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000116static PyObject *dummy; /* Initialized by first call to newdictobject() */
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000117
Fred Drake1bff34a2000-08-31 19:31:38 +0000118/* forward declarations */
119static dictentry *
120lookdict_string(dictobject *mp, PyObject *key, long hash);
121
122#ifdef SHOW_CONVERSION_COUNTS
123static long created = 0L;
124static long converted = 0L;
125
126static void
127show_counts(void)
128{
129 fprintf(stderr, "created %ld string dicts\n", created);
130 fprintf(stderr, "converted %ld to normal dicts\n", converted);
131 fprintf(stderr, "%.2f%% conversion rate\n", (100.0*converted)/created);
132}
133#endif
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000134
Tim Peters6d6c1a32001-08-02 04:15:00 +0000135/* Initialization macros.
136 There are two ways to create a dict: PyDict_New() is the main C API
137 function, and the tp_new slot maps to dict_new(). In the latter case we
138 can save a little time over what PyDict_New does because it's guaranteed
139 that the PyDictObject struct is already zeroed out.
140 Everyone except dict_new() should use EMPTY_TO_MINSIZE (unless they have
141 an excellent reason not to).
142*/
143
144#define INIT_NONZERO_DICT_SLOTS(mp) do { \
Tim Petersdea48ec2001-05-22 20:40:22 +0000145 (mp)->ma_table = (mp)->ma_smalltable; \
Tim Peters6d6c1a32001-08-02 04:15:00 +0000146 (mp)->ma_mask = PyDict_MINSIZE - 1; \
147 } while(0)
148
149#define EMPTY_TO_MINSIZE(mp) do { \
150 memset((mp)->ma_smalltable, 0, sizeof((mp)->ma_smalltable)); \
Tim Petersdea48ec2001-05-22 20:40:22 +0000151 (mp)->ma_used = (mp)->ma_fill = 0; \
Tim Peters6d6c1a32001-08-02 04:15:00 +0000152 INIT_NONZERO_DICT_SLOTS(mp); \
Tim Petersdea48ec2001-05-22 20:40:22 +0000153 } while(0)
154
Raymond Hettinger43442782004-03-17 21:55:03 +0000155/* Dictionary reuse scheme to save calls to malloc, free, and memset */
156#define MAXFREEDICTS 80
157static PyDictObject *free_dicts[MAXFREEDICTS];
158static int num_free_dicts = 0;
159
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000160PyObject *
Thomas Wouters78890102000-07-22 19:25:51 +0000161PyDict_New(void)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000162{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000163 register dictobject *mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000164 if (dummy == NULL) { /* Auto-initialize dummy */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000165 dummy = PyString_FromString("<dummy key>");
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000166 if (dummy == NULL)
167 return NULL;
Fred Drake1bff34a2000-08-31 19:31:38 +0000168#ifdef SHOW_CONVERSION_COUNTS
169 Py_AtExit(show_counts);
170#endif
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000171 }
Raymond Hettinger43442782004-03-17 21:55:03 +0000172 if (num_free_dicts) {
173 mp = free_dicts[--num_free_dicts];
174 assert (mp != NULL);
175 assert (mp->ob_type == &PyDict_Type);
176 _Py_NewReference((PyObject *)mp);
177 if (mp->ma_fill) {
178 EMPTY_TO_MINSIZE(mp);
179 }
180 assert (mp->ma_used == 0);
181 assert (mp->ma_table == mp->ma_smalltable);
182 assert (mp->ma_mask == PyDict_MINSIZE - 1);
183 } else {
184 mp = PyObject_GC_New(dictobject, &PyDict_Type);
185 if (mp == NULL)
186 return NULL;
187 EMPTY_TO_MINSIZE(mp);
188 }
Fred Drake1bff34a2000-08-31 19:31:38 +0000189 mp->ma_lookup = lookdict_string;
190#ifdef SHOW_CONVERSION_COUNTS
191 ++created;
192#endif
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000193 _PyObject_GC_TRACK(mp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000194 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000195}
196
197/*
198The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000199This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000200Open addressing is preferred over chaining since the link overhead for
201chaining would be substantial (100% with typical malloc overhead).
202
Tim Peterseb28ef22001-06-02 05:27:19 +0000203The initial probe index is computed as hash mod the table size. Subsequent
204probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000205
206All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000207
Tim Peterseb28ef22001-06-02 05:27:19 +0000208(The details in this version are due to Tim Peters, building on many past
209contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
210Christian Tismer).
Fred Drake1bff34a2000-08-31 19:31:38 +0000211
212This function must never return NULL; failures are indicated by returning
213a dictentry* for which the me_value field is NULL. Exceptions are never
214reported by this function, and outstanding exceptions are maintained.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000215*/
Tim Peterseb28ef22001-06-02 05:27:19 +0000216
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000217static dictentry *
Tim Peters1f5871e2000-07-04 17:44:48 +0000218lookdict(dictobject *mp, PyObject *key, register long hash)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000219{
Guido van Rossum16e93a81997-01-28 00:00:11 +0000220 register int i;
Tim Peterseb28ef22001-06-02 05:27:19 +0000221 register unsigned int perturb;
Guido van Rossumfd7a0b81997-08-18 21:52:47 +0000222 register dictentry *freeslot;
Tim Petersafb6ae82001-06-04 21:00:21 +0000223 register unsigned int mask = mp->ma_mask;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000224 dictentry *ep0 = mp->ma_table;
225 register dictentry *ep;
Tim Peters7b5d0af2001-06-03 04:14:43 +0000226 register int restore_error;
227 register int checked_error;
Fred Drakec88b99c2000-08-31 19:04:07 +0000228 register int cmp;
229 PyObject *err_type, *err_value, *err_tb;
Tim Peters453163d2001-06-03 04:54:32 +0000230 PyObject *startkey;
Tim Peterseb28ef22001-06-02 05:27:19 +0000231
Tim Peters2f228e72001-05-13 00:19:31 +0000232 i = hash & mask;
Guido van Rossumefb46091997-01-29 15:53:56 +0000233 ep = &ep0[i];
Guido van Rossumc1c7b1a1998-10-06 16:01:14 +0000234 if (ep->me_key == NULL || ep->me_key == key)
Guido van Rossum7d181591997-01-16 21:06:45 +0000235 return ep;
Tim Peters7b5d0af2001-06-03 04:14:43 +0000236
237 restore_error = checked_error = 0;
Guido van Rossum16e93a81997-01-28 00:00:11 +0000238 if (ep->me_key == dummy)
Guido van Rossum7d181591997-01-16 21:06:45 +0000239 freeslot = ep;
Guido van Rossumfd7a0b81997-08-18 21:52:47 +0000240 else {
Fred Drakec88b99c2000-08-31 19:04:07 +0000241 if (ep->me_hash == hash) {
242 /* error can't have been checked yet */
243 checked_error = 1;
244 if (PyErr_Occurred()) {
245 restore_error = 1;
246 PyErr_Fetch(&err_type, &err_value, &err_tb);
247 }
Tim Peters453163d2001-06-03 04:54:32 +0000248 startkey = ep->me_key;
249 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
Tim Peters7b5d0af2001-06-03 04:14:43 +0000250 if (cmp < 0)
Guido van Rossumb9324202001-01-18 00:39:02 +0000251 PyErr_Clear();
Tim Peters453163d2001-06-03 04:54:32 +0000252 if (ep0 == mp->ma_table && ep->me_key == startkey) {
253 if (cmp > 0)
254 goto Done;
255 }
256 else {
257 /* The compare did major nasty stuff to the
258 * dict: start over.
259 * XXX A clever adversary could prevent this
260 * XXX from terminating.
261 */
262 ep = lookdict(mp, key, hash);
263 goto Done;
264 }
Guido van Rossumfd7a0b81997-08-18 21:52:47 +0000265 }
266 freeslot = NULL;
Guido van Rossum2a61e741997-01-18 07:55:05 +0000267 }
Tim Peters15d49292001-05-27 07:39:22 +0000268
Tim Peters342c65e2001-05-13 06:43:53 +0000269 /* In the loop, me_key == dummy is by far (factor of 100s) the
270 least likely outcome, so test for that last. */
Tim Peterseb28ef22001-06-02 05:27:19 +0000271 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
272 i = (i << 2) + i + perturb + 1;
273 ep = &ep0[i & mask];
Guido van Rossum16e93a81997-01-28 00:00:11 +0000274 if (ep->me_key == NULL) {
Tim Peters7b5d0af2001-06-03 04:14:43 +0000275 if (freeslot != NULL)
276 ep = freeslot;
277 break;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000278 }
Tim Peters7b5d0af2001-06-03 04:14:43 +0000279 if (ep->me_key == key)
280 break;
281 if (ep->me_hash == hash && ep->me_key != dummy) {
Fred Drakec88b99c2000-08-31 19:04:07 +0000282 if (!checked_error) {
283 checked_error = 1;
284 if (PyErr_Occurred()) {
285 restore_error = 1;
286 PyErr_Fetch(&err_type, &err_value,
287 &err_tb);
288 }
289 }
Tim Peters453163d2001-06-03 04:54:32 +0000290 startkey = ep->me_key;
291 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
Tim Peters7b5d0af2001-06-03 04:14:43 +0000292 if (cmp < 0)
Guido van Rossumb9324202001-01-18 00:39:02 +0000293 PyErr_Clear();
Tim Peters453163d2001-06-03 04:54:32 +0000294 if (ep0 == mp->ma_table && ep->me_key == startkey) {
295 if (cmp > 0)
296 break;
297 }
298 else {
299 /* The compare did major nasty stuff to the
300 * dict: start over.
301 * XXX A clever adversary could prevent this
302 * XXX from terminating.
303 */
304 ep = lookdict(mp, key, hash);
305 break;
306 }
Guido van Rossum16e93a81997-01-28 00:00:11 +0000307 }
Tim Peters342c65e2001-05-13 06:43:53 +0000308 else if (ep->me_key == dummy && freeslot == NULL)
309 freeslot = ep;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000310 }
Tim Peters7b5d0af2001-06-03 04:14:43 +0000311
312Done:
313 if (restore_error)
314 PyErr_Restore(err_type, err_value, err_tb);
315 return ep;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000316}
317
318/*
Fred Drake1bff34a2000-08-31 19:31:38 +0000319 * Hacked up version of lookdict which can assume keys are always strings;
320 * this assumption allows testing for errors during PyObject_Compare() to
321 * be dropped; string-string comparisons never raise exceptions. This also
322 * means we don't need to go through PyObject_Compare(); we can always use
Martin v. Löwiscd353062001-05-24 16:56:35 +0000323 * _PyString_Eq directly.
Fred Drake1bff34a2000-08-31 19:31:38 +0000324 *
Tim Peters0ab085c2001-09-14 00:25:33 +0000325 * This is valuable because the general-case error handling in lookdict() is
326 * expensive, and dicts with pure-string keys are very common.
Fred Drake1bff34a2000-08-31 19:31:38 +0000327 */
328static dictentry *
329lookdict_string(dictobject *mp, PyObject *key, register long hash)
330{
331 register int i;
Tim Peterseb28ef22001-06-02 05:27:19 +0000332 register unsigned int perturb;
Fred Drake1bff34a2000-08-31 19:31:38 +0000333 register dictentry *freeslot;
Tim Petersafb6ae82001-06-04 21:00:21 +0000334 register unsigned int mask = mp->ma_mask;
Fred Drake1bff34a2000-08-31 19:31:38 +0000335 dictentry *ep0 = mp->ma_table;
336 register dictentry *ep;
Fred Drake1bff34a2000-08-31 19:31:38 +0000337
Tim Peters0ab085c2001-09-14 00:25:33 +0000338 /* Make sure this function doesn't have to handle non-string keys,
339 including subclasses of str; e.g., one reason to subclass
340 strings is to override __eq__, and for speed we don't cater to
341 that here. */
342 if (!PyString_CheckExact(key)) {
Fred Drake1bff34a2000-08-31 19:31:38 +0000343#ifdef SHOW_CONVERSION_COUNTS
344 ++converted;
345#endif
346 mp->ma_lookup = lookdict;
347 return lookdict(mp, key, hash);
348 }
Tim Peters2f228e72001-05-13 00:19:31 +0000349 i = hash & mask;
Fred Drake1bff34a2000-08-31 19:31:38 +0000350 ep = &ep0[i];
351 if (ep->me_key == NULL || ep->me_key == key)
352 return ep;
353 if (ep->me_key == dummy)
354 freeslot = ep;
355 else {
356 if (ep->me_hash == hash
Martin v. Löwiscd353062001-05-24 16:56:35 +0000357 && _PyString_Eq(ep->me_key, key)) {
Fred Drake1bff34a2000-08-31 19:31:38 +0000358 return ep;
359 }
360 freeslot = NULL;
361 }
Tim Peters15d49292001-05-27 07:39:22 +0000362
Tim Peters342c65e2001-05-13 06:43:53 +0000363 /* In the loop, me_key == dummy is by far (factor of 100s) the
364 least likely outcome, so test for that last. */
Tim Peterseb28ef22001-06-02 05:27:19 +0000365 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
366 i = (i << 2) + i + perturb + 1;
367 ep = &ep0[i & mask];
Tim Peters342c65e2001-05-13 06:43:53 +0000368 if (ep->me_key == NULL)
369 return freeslot == NULL ? ep : freeslot;
370 if (ep->me_key == key
371 || (ep->me_hash == hash
372 && ep->me_key != dummy
Martin v. Löwiscd353062001-05-24 16:56:35 +0000373 && _PyString_Eq(ep->me_key, key)))
Fred Drake1bff34a2000-08-31 19:31:38 +0000374 return ep;
Tim Petersdea48ec2001-05-22 20:40:22 +0000375 if (ep->me_key == dummy && freeslot == NULL)
Tim Peters342c65e2001-05-13 06:43:53 +0000376 freeslot = ep;
Fred Drake1bff34a2000-08-31 19:31:38 +0000377 }
378}
379
380/*
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000381Internal routine to insert a new item into the table.
382Used both by the internal resize routine and by the public insert routine.
383Eats a reference to key and one to value.
384*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000385static void
Tim Peters1f5871e2000-07-04 17:44:48 +0000386insertdict(register dictobject *mp, PyObject *key, long hash, PyObject *value)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000387{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000388 PyObject *old_value;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000389 register dictentry *ep;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000390 typedef PyDictEntry *(*lookupfunc)(PyDictObject *, PyObject *, long);
391
392 assert(mp->ma_lookup != NULL);
393 ep = mp->ma_lookup(mp, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000394 if (ep->me_value != NULL) {
Guido van Rossumd7047b31995-01-02 19:07:15 +0000395 old_value = ep->me_value;
396 ep->me_value = value;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000397 Py_DECREF(old_value); /* which **CAN** re-enter */
398 Py_DECREF(key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000399 }
400 else {
401 if (ep->me_key == NULL)
402 mp->ma_fill++;
403 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000404 Py_DECREF(ep->me_key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000405 ep->me_key = key;
406 ep->me_hash = hash;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000407 ep->me_value = value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000408 mp->ma_used++;
409 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000410}
411
412/*
413Restructure the table by allocating a new table and reinserting all
414items again. When entries have been deleted, the new table may
415actually be smaller than the old one.
416*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000417static int
Tim Peters1f5871e2000-07-04 17:44:48 +0000418dictresize(dictobject *mp, int minused)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000419{
Tim Peterseb28ef22001-06-02 05:27:19 +0000420 int newsize;
Tim Peters0c6010b2001-05-23 23:33:57 +0000421 dictentry *oldtable, *newtable, *ep;
422 int i;
423 int is_oldtable_malloced;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000424 dictentry small_copy[PyDict_MINSIZE];
Tim Peters91a364d2001-05-19 07:04:38 +0000425
426 assert(minused >= 0);
Tim Peters0c6010b2001-05-23 23:33:57 +0000427
Tim Peterseb28ef22001-06-02 05:27:19 +0000428 /* Find the smallest table size > minused. */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000429 for (newsize = PyDict_MINSIZE;
Tim Peterseb28ef22001-06-02 05:27:19 +0000430 newsize <= minused && newsize > 0;
431 newsize <<= 1)
432 ;
433 if (newsize <= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000434 PyErr_NoMemory();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000435 return -1;
436 }
Tim Peters0c6010b2001-05-23 23:33:57 +0000437
438 /* Get space for a new table. */
439 oldtable = mp->ma_table;
440 assert(oldtable != NULL);
441 is_oldtable_malloced = oldtable != mp->ma_smalltable;
442
Tim Peters6d6c1a32001-08-02 04:15:00 +0000443 if (newsize == PyDict_MINSIZE) {
Tim Petersf8a548c2001-05-24 16:26:40 +0000444 /* A large table is shrinking, or we can't get any smaller. */
Tim Petersdea48ec2001-05-22 20:40:22 +0000445 newtable = mp->ma_smalltable;
Tim Peters0c6010b2001-05-23 23:33:57 +0000446 if (newtable == oldtable) {
Tim Petersf8a548c2001-05-24 16:26:40 +0000447 if (mp->ma_fill == mp->ma_used) {
448 /* No dummies, so no point doing anything. */
Tim Peters0c6010b2001-05-23 23:33:57 +0000449 return 0;
Tim Petersf8a548c2001-05-24 16:26:40 +0000450 }
451 /* We're not going to resize it, but rebuild the
452 table anyway to purge old dummy entries.
453 Subtle: This is *necessary* if fill==size,
454 as lookdict needs at least one virgin slot to
455 terminate failing searches. If fill < size, it's
456 merely desirable, as dummies slow searches. */
457 assert(mp->ma_fill > mp->ma_used);
Tim Peters0c6010b2001-05-23 23:33:57 +0000458 memcpy(small_copy, oldtable, sizeof(small_copy));
459 oldtable = small_copy;
460 }
Tim Petersdea48ec2001-05-22 20:40:22 +0000461 }
462 else {
463 newtable = PyMem_NEW(dictentry, newsize);
464 if (newtable == NULL) {
465 PyErr_NoMemory();
466 return -1;
467 }
468 }
Tim Peters0c6010b2001-05-23 23:33:57 +0000469
470 /* Make the dict empty, using the new table. */
Tim Petersdea48ec2001-05-22 20:40:22 +0000471 assert(newtable != oldtable);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000472 mp->ma_table = newtable;
Tim Petersafb6ae82001-06-04 21:00:21 +0000473 mp->ma_mask = newsize - 1;
Tim Petersdea48ec2001-05-22 20:40:22 +0000474 memset(newtable, 0, sizeof(dictentry) * newsize);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000475 mp->ma_used = 0;
Tim Petersdea48ec2001-05-22 20:40:22 +0000476 i = mp->ma_fill;
477 mp->ma_fill = 0;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000478
Tim Peters19283142001-05-17 22:25:34 +0000479 /* Copy the data over; this is refcount-neutral for active entries;
480 dummy entries aren't copied over, of course */
Tim Petersdea48ec2001-05-22 20:40:22 +0000481 for (ep = oldtable; i > 0; ep++) {
482 if (ep->me_value != NULL) { /* active entry */
483 --i;
Tim Peters19283142001-05-17 22:25:34 +0000484 insertdict(mp, ep->me_key, ep->me_hash, ep->me_value);
Tim Petersdea48ec2001-05-22 20:40:22 +0000485 }
Tim Peters19283142001-05-17 22:25:34 +0000486 else if (ep->me_key != NULL) { /* dummy entry */
Tim Petersdea48ec2001-05-22 20:40:22 +0000487 --i;
Tim Peters19283142001-05-17 22:25:34 +0000488 assert(ep->me_key == dummy);
489 Py_DECREF(ep->me_key);
Guido van Rossum255443b1998-04-10 22:47:14 +0000490 }
Tim Peters19283142001-05-17 22:25:34 +0000491 /* else key == value == NULL: nothing to do */
Guido van Rossumd7047b31995-01-02 19:07:15 +0000492 }
493
Tim Peters0c6010b2001-05-23 23:33:57 +0000494 if (is_oldtable_malloced)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000495 PyMem_DEL(oldtable);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000496 return 0;
497}
498
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000499PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000500PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000501{
502 long hash;
Fred Drake1bff34a2000-08-31 19:31:38 +0000503 dictobject *mp = (dictobject *)op;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000504 if (!PyDict_Check(op)) {
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000505 return NULL;
506 }
Tim Peters0ab085c2001-09-14 00:25:33 +0000507 if (!PyString_CheckExact(key) ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000508 (hash = ((PyStringObject *) key)->ob_shash) == -1)
Guido van Rossumca756f21997-01-23 19:39:29 +0000509 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000510 hash = PyObject_Hash(key);
Guido van Rossum474b19e1998-05-14 01:00:51 +0000511 if (hash == -1) {
512 PyErr_Clear();
Guido van Rossumca756f21997-01-23 19:39:29 +0000513 return NULL;
Guido van Rossum474b19e1998-05-14 01:00:51 +0000514 }
Guido van Rossumca756f21997-01-23 19:39:29 +0000515 }
Fred Drake1bff34a2000-08-31 19:31:38 +0000516 return (mp->ma_lookup)(mp, key, hash)->me_value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000517}
518
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000519/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
520 * dictionary if it is merely replacing the value for an existing key.
521 * This is means that it's safe to loop over a dictionary with
522 * PyDict_Next() and occasionally replace a value -- but you can't
523 * insert new keys or remove them.
524 */
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000525int
Tim Peters1f5871e2000-07-04 17:44:48 +0000526PyDict_SetItem(register PyObject *op, PyObject *key, PyObject *value)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000527{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000528 register dictobject *mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000529 register long hash;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000530 register int n_used;
531
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000532 if (!PyDict_Check(op)) {
533 PyErr_BadInternalCall();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000534 return -1;
535 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000536 mp = (dictobject *)op;
Tim Peters0ab085c2001-09-14 00:25:33 +0000537 if (PyString_CheckExact(key)) {
Guido van Rossum45ec02a2002-08-19 21:43:18 +0000538 hash = ((PyStringObject *)key)->ob_shash;
539 if (hash == -1)
540 hash = PyObject_Hash(key);
Guido van Rossum2a61e741997-01-18 07:55:05 +0000541 }
Tim Peters1f7df352002-03-29 03:29:08 +0000542 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000543 hash = PyObject_Hash(key);
Guido van Rossum2a61e741997-01-18 07:55:05 +0000544 if (hash == -1)
545 return -1;
Guido van Rossum2a61e741997-01-18 07:55:05 +0000546 }
Tim Petersafb6ae82001-06-04 21:00:21 +0000547 assert(mp->ma_fill <= mp->ma_mask); /* at least one empty slot */
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000548 n_used = mp->ma_used;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000549 Py_INCREF(value);
550 Py_INCREF(key);
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000551 insertdict(mp, key, hash, value);
Raymond Hettinger3539f6b2003-05-05 22:22:10 +0000552 /* If we added a key, we can safely resize. Otherwise just return!
553 * If fill >= 2/3 size, adjust size. Normally, this doubles or
554 * quaduples the size, but it's also possible for the dict to shrink
555 * (if ma_fill is much larger than ma_used, meaning a lot of dict
556 * keys have been * deleted).
557 *
558 * Quadrupling the size improves average dictionary sparseness
559 * (reducing collisions) at the cost of some memory and iteration
560 * speed (which loops over every possible entry). It also halves
561 * the number of expensive resize operations in a growing dictionary.
562 *
563 * Very large dictionaries (over 50K items) use doubling instead.
564 * This may help applications with severe memory constraints.
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000565 */
Raymond Hettinger3539f6b2003-05-05 22:22:10 +0000566 if (!(mp->ma_used > n_used && mp->ma_fill*3 >= (mp->ma_mask+1)*2))
567 return 0;
568 return dictresize(mp, mp->ma_used*(mp->ma_used>50000 ? 2 : 4));
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000569}
570
571int
Tim Peters1f5871e2000-07-04 17:44:48 +0000572PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000573{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000574 register dictobject *mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000575 register long hash;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000576 register dictentry *ep;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000577 PyObject *old_value, *old_key;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000578
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000579 if (!PyDict_Check(op)) {
580 PyErr_BadInternalCall();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000581 return -1;
582 }
Tim Peters0ab085c2001-09-14 00:25:33 +0000583 if (!PyString_CheckExact(key) ||
Tim Peters1f7df352002-03-29 03:29:08 +0000584 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000585 hash = PyObject_Hash(key);
Guido van Rossumca756f21997-01-23 19:39:29 +0000586 if (hash == -1)
587 return -1;
588 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000589 mp = (dictobject *)op;
Fred Drake1bff34a2000-08-31 19:31:38 +0000590 ep = (mp->ma_lookup)(mp, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000591 if (ep->me_value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000592 PyErr_SetObject(PyExc_KeyError, key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000593 return -1;
594 }
Guido van Rossumd7047b31995-01-02 19:07:15 +0000595 old_key = ep->me_key;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000596 Py_INCREF(dummy);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000597 ep->me_key = dummy;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000598 old_value = ep->me_value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000599 ep->me_value = NULL;
600 mp->ma_used--;
Tim Petersea8f2bf2000-12-13 01:02:46 +0000601 Py_DECREF(old_value);
602 Py_DECREF(old_key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000603 return 0;
604}
605
Guido van Rossum25831651993-05-19 14:50:45 +0000606void
Tim Peters1f5871e2000-07-04 17:44:48 +0000607PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000608{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000609 dictobject *mp;
Tim Petersdea48ec2001-05-22 20:40:22 +0000610 dictentry *ep, *table;
611 int table_is_malloced;
612 int fill;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000613 dictentry small_copy[PyDict_MINSIZE];
Tim Petersdea48ec2001-05-22 20:40:22 +0000614#ifdef Py_DEBUG
615 int i, n;
616#endif
617
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000618 if (!PyDict_Check(op))
Guido van Rossum25831651993-05-19 14:50:45 +0000619 return;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000620 mp = (dictobject *)op;
Tim Petersdea48ec2001-05-22 20:40:22 +0000621#ifdef Py_DEBUG
Tim Petersafb6ae82001-06-04 21:00:21 +0000622 n = mp->ma_mask + 1;
Tim Petersdea48ec2001-05-22 20:40:22 +0000623 i = 0;
624#endif
625
626 table = mp->ma_table;
627 assert(table != NULL);
628 table_is_malloced = table != mp->ma_smalltable;
629
630 /* This is delicate. During the process of clearing the dict,
631 * decrefs can cause the dict to mutate. To avoid fatal confusion
632 * (voice of experience), we have to make the dict empty before
633 * clearing the slots, and never refer to anything via mp->xxx while
634 * clearing.
635 */
636 fill = mp->ma_fill;
637 if (table_is_malloced)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000638 EMPTY_TO_MINSIZE(mp);
Tim Petersdea48ec2001-05-22 20:40:22 +0000639
640 else if (fill > 0) {
641 /* It's a small table with something that needs to be cleared.
642 * Afraid the only safe way is to copy the dict entries into
643 * another small table first.
644 */
645 memcpy(small_copy, table, sizeof(small_copy));
646 table = small_copy;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000647 EMPTY_TO_MINSIZE(mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000648 }
Tim Petersdea48ec2001-05-22 20:40:22 +0000649 /* else it's a small table that's already empty */
650
651 /* Now we can finally clear things. If C had refcounts, we could
652 * assert that the refcount on table is 1 now, i.e. that this function
653 * has unique access to it, so decref side-effects can't alter it.
654 */
655 for (ep = table; fill > 0; ++ep) {
656#ifdef Py_DEBUG
657 assert(i < n);
658 ++i;
659#endif
660 if (ep->me_key) {
661 --fill;
662 Py_DECREF(ep->me_key);
663 Py_XDECREF(ep->me_value);
664 }
665#ifdef Py_DEBUG
666 else
667 assert(ep->me_value == NULL);
668#endif
669 }
670
671 if (table_is_malloced)
672 PyMem_DEL(table);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000673}
674
Tim Peters080c88b2003-02-15 03:01:11 +0000675/*
676 * Iterate over a dict. Use like so:
677 *
678 * int i;
679 * PyObject *key, *value;
680 * i = 0; # important! i should not otherwise be changed by you
Neal Norwitz07323012003-02-15 14:45:12 +0000681 * while (PyDict_Next(yourdict, &i, &key, &value)) {
Tim Peters080c88b2003-02-15 03:01:11 +0000682 * Refer to borrowed references in key and value.
683 * }
684 *
685 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
Tim Peters67830702001-03-21 19:23:56 +0000686 * mutates the dict. One exception: it is safe if the loop merely changes
687 * the values associated with the keys (but doesn't insert new keys or
688 * delete keys), via PyDict_SetItem().
689 */
Guido van Rossum25831651993-05-19 14:50:45 +0000690int
Tim Peters1f5871e2000-07-04 17:44:48 +0000691PyDict_Next(PyObject *op, int *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000692{
Raymond Hettinger43442782004-03-17 21:55:03 +0000693 register int i, mask;
694 register dictentry *ep;
695
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000696 if (!PyDict_Check(op))
Guido van Rossum25831651993-05-19 14:50:45 +0000697 return 0;
Guido van Rossum25831651993-05-19 14:50:45 +0000698 i = *ppos;
699 if (i < 0)
700 return 0;
Raymond Hettinger43442782004-03-17 21:55:03 +0000701 ep = ((dictobject *)op)->ma_table;
702 mask = ((dictobject *)op)->ma_mask;
703 while (i <= mask && ep[i].me_value == NULL)
Guido van Rossum25831651993-05-19 14:50:45 +0000704 i++;
705 *ppos = i+1;
Raymond Hettinger43442782004-03-17 21:55:03 +0000706 if (i > mask)
Guido van Rossum25831651993-05-19 14:50:45 +0000707 return 0;
708 if (pkey)
Raymond Hettinger43442782004-03-17 21:55:03 +0000709 *pkey = ep[i].me_key;
Guido van Rossum25831651993-05-19 14:50:45 +0000710 if (pvalue)
Raymond Hettinger43442782004-03-17 21:55:03 +0000711 *pvalue = ep[i].me_value;
Guido van Rossum25831651993-05-19 14:50:45 +0000712 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000713}
714
715/* Methods */
716
717static void
Tim Peters1f5871e2000-07-04 17:44:48 +0000718dict_dealloc(register dictobject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000719{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000720 register dictentry *ep;
Tim Petersdea48ec2001-05-22 20:40:22 +0000721 int fill = mp->ma_fill;
Guido van Rossumff413af2002-03-28 20:34:59 +0000722 PyObject_GC_UnTrack(mp);
Guido van Rossumd724b232000-03-13 16:01:29 +0000723 Py_TRASHCAN_SAFE_BEGIN(mp)
Tim Petersdea48ec2001-05-22 20:40:22 +0000724 for (ep = mp->ma_table; fill > 0; ep++) {
725 if (ep->me_key) {
726 --fill;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000727 Py_DECREF(ep->me_key);
Tim Petersdea48ec2001-05-22 20:40:22 +0000728 Py_XDECREF(ep->me_value);
Guido van Rossum255443b1998-04-10 22:47:14 +0000729 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000730 }
Tim Petersdea48ec2001-05-22 20:40:22 +0000731 if (mp->ma_table != mp->ma_smalltable)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000732 PyMem_DEL(mp->ma_table);
Raymond Hettinger43442782004-03-17 21:55:03 +0000733 if (num_free_dicts < MAXFREEDICTS && mp->ob_type == &PyDict_Type)
734 free_dicts[num_free_dicts++] = mp;
735 else
736 mp->ob_type->tp_free((PyObject *)mp);
Guido van Rossumd724b232000-03-13 16:01:29 +0000737 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000738}
739
740static int
Tim Peters1f5871e2000-07-04 17:44:48 +0000741dict_print(register dictobject *mp, register FILE *fp, register int flags)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000742{
743 register int i;
744 register int any;
Guido van Rossum255443b1998-04-10 22:47:14 +0000745
746 i = Py_ReprEnter((PyObject*)mp);
747 if (i != 0) {
748 if (i < 0)
749 return i;
750 fprintf(fp, "{...}");
751 return 0;
752 }
753
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000754 fprintf(fp, "{");
755 any = 0;
Tim Petersafb6ae82001-06-04 21:00:21 +0000756 for (i = 0; i <= mp->ma_mask; i++) {
Tim Peters23cf6be2001-06-02 08:02:56 +0000757 dictentry *ep = mp->ma_table + i;
758 PyObject *pvalue = ep->me_value;
759 if (pvalue != NULL) {
760 /* Prevent PyObject_Repr from deleting value during
761 key format */
762 Py_INCREF(pvalue);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000763 if (any++ > 0)
764 fprintf(fp, ", ");
Guido van Rossum255443b1998-04-10 22:47:14 +0000765 if (PyObject_Print((PyObject *)ep->me_key, fp, 0)!=0) {
Tim Peters23cf6be2001-06-02 08:02:56 +0000766 Py_DECREF(pvalue);
Guido van Rossum255443b1998-04-10 22:47:14 +0000767 Py_ReprLeave((PyObject*)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000768 return -1;
Guido van Rossum255443b1998-04-10 22:47:14 +0000769 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000770 fprintf(fp, ": ");
Tim Peters19b77cf2001-06-02 08:27:39 +0000771 if (PyObject_Print(pvalue, fp, 0) != 0) {
Tim Peters23cf6be2001-06-02 08:02:56 +0000772 Py_DECREF(pvalue);
Guido van Rossum255443b1998-04-10 22:47:14 +0000773 Py_ReprLeave((PyObject*)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000774 return -1;
Guido van Rossum255443b1998-04-10 22:47:14 +0000775 }
Tim Peters23cf6be2001-06-02 08:02:56 +0000776 Py_DECREF(pvalue);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000777 }
778 }
779 fprintf(fp, "}");
Guido van Rossum255443b1998-04-10 22:47:14 +0000780 Py_ReprLeave((PyObject*)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000781 return 0;
782}
783
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000784static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000785dict_repr(dictobject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000786{
Tim Petersc6057842001-06-16 07:52:53 +0000787 int i;
Tim Petersa7259592001-06-16 05:11:17 +0000788 PyObject *s, *temp, *colon = NULL;
789 PyObject *pieces = NULL, *result = NULL;
790 PyObject *key, *value;
Guido van Rossum255443b1998-04-10 22:47:14 +0000791
Tim Petersa7259592001-06-16 05:11:17 +0000792 i = Py_ReprEnter((PyObject *)mp);
Guido van Rossum255443b1998-04-10 22:47:14 +0000793 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000794 return i > 0 ? PyString_FromString("{...}") : NULL;
Guido van Rossum255443b1998-04-10 22:47:14 +0000795 }
796
Tim Petersa7259592001-06-16 05:11:17 +0000797 if (mp->ma_used == 0) {
798 result = PyString_FromString("{}");
799 goto Done;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000800 }
Tim Petersa7259592001-06-16 05:11:17 +0000801
802 pieces = PyList_New(0);
803 if (pieces == NULL)
804 goto Done;
805
806 colon = PyString_FromString(": ");
807 if (colon == NULL)
808 goto Done;
809
810 /* Do repr() on each key+value pair, and insert ": " between them.
811 Note that repr may mutate the dict. */
Tim Petersc6057842001-06-16 07:52:53 +0000812 i = 0;
813 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Tim Petersa7259592001-06-16 05:11:17 +0000814 int status;
815 /* Prevent repr from deleting value during key format. */
816 Py_INCREF(value);
817 s = PyObject_Repr(key);
818 PyString_Concat(&s, colon);
819 PyString_ConcatAndDel(&s, PyObject_Repr(value));
820 Py_DECREF(value);
821 if (s == NULL)
822 goto Done;
823 status = PyList_Append(pieces, s);
824 Py_DECREF(s); /* append created a new ref */
825 if (status < 0)
826 goto Done;
827 }
828
829 /* Add "{}" decorations to the first and last items. */
830 assert(PyList_GET_SIZE(pieces) > 0);
831 s = PyString_FromString("{");
832 if (s == NULL)
833 goto Done;
834 temp = PyList_GET_ITEM(pieces, 0);
835 PyString_ConcatAndDel(&s, temp);
836 PyList_SET_ITEM(pieces, 0, s);
837 if (s == NULL)
838 goto Done;
839
840 s = PyString_FromString("}");
841 if (s == NULL)
842 goto Done;
843 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
844 PyString_ConcatAndDel(&temp, s);
845 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
846 if (temp == NULL)
847 goto Done;
848
849 /* Paste them all together with ", " between. */
850 s = PyString_FromString(", ");
851 if (s == NULL)
852 goto Done;
853 result = _PyString_Join(s, pieces);
Tim Peters0ab085c2001-09-14 00:25:33 +0000854 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000855
856Done:
857 Py_XDECREF(pieces);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000858 Py_XDECREF(colon);
Tim Petersa7259592001-06-16 05:11:17 +0000859 Py_ReprLeave((PyObject *)mp);
860 return result;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000861}
862
863static int
Tim Peters1f5871e2000-07-04 17:44:48 +0000864dict_length(dictobject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000865{
866 return mp->ma_used;
867}
868
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000869static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000870dict_subscript(dictobject *mp, register PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000871{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000872 PyObject *v;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000873 long hash;
Tim Petersdea48ec2001-05-22 20:40:22 +0000874 assert(mp->ma_table != NULL);
Tim Peters0ab085c2001-09-14 00:25:33 +0000875 if (!PyString_CheckExact(key) ||
Tim Peters1f7df352002-03-29 03:29:08 +0000876 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000877 hash = PyObject_Hash(key);
Guido van Rossumca756f21997-01-23 19:39:29 +0000878 if (hash == -1)
879 return NULL;
880 }
Fred Drake1bff34a2000-08-31 19:31:38 +0000881 v = (mp->ma_lookup)(mp, key, hash) -> me_value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000882 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000883 PyErr_SetObject(PyExc_KeyError, key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000884 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000885 Py_INCREF(v);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000886 return v;
887}
888
889static int
Tim Peters1f5871e2000-07-04 17:44:48 +0000890dict_ass_sub(dictobject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000891{
892 if (w == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000893 return PyDict_DelItem((PyObject *)mp, v);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000894 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000895 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000896}
897
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000898static PyMappingMethods dict_as_mapping = {
899 (inquiry)dict_length, /*mp_length*/
900 (binaryfunc)dict_subscript, /*mp_subscript*/
901 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000902};
903
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000904static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000905dict_keys(register dictobject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000906{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000907 register PyObject *v;
Raymond Hettinger43442782004-03-17 21:55:03 +0000908 register int i, j;
909 dictentry *ep;
910 int mask, n;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000911
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000912 again:
913 n = mp->ma_used;
914 v = PyList_New(n);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000915 if (v == NULL)
916 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000917 if (n != mp->ma_used) {
918 /* Durnit. The allocations caused the dict to resize.
919 * Just start over, this shouldn't normally happen.
920 */
921 Py_DECREF(v);
922 goto again;
923 }
Raymond Hettinger43442782004-03-17 21:55:03 +0000924 ep = mp->ma_table;
925 mask = mp->ma_mask;
926 for (i = 0, j = 0; i <= mask; i++) {
927 if (ep[i].me_value != NULL) {
928 PyObject *key = ep[i].me_key;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000929 Py_INCREF(key);
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000930 PyList_SET_ITEM(v, j, key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000931 j++;
932 }
933 }
Raymond Hettinger43442782004-03-17 21:55:03 +0000934 assert(j == n);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000935 return v;
936}
937
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000938static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000939dict_values(register dictobject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +0000940{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000941 register PyObject *v;
Raymond Hettinger43442782004-03-17 21:55:03 +0000942 register int i, j;
943 dictentry *ep;
944 int mask, n;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000945
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000946 again:
947 n = mp->ma_used;
948 v = PyList_New(n);
Guido van Rossum25831651993-05-19 14:50:45 +0000949 if (v == NULL)
950 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000951 if (n != mp->ma_used) {
952 /* Durnit. The allocations caused the dict to resize.
953 * Just start over, this shouldn't normally happen.
954 */
955 Py_DECREF(v);
956 goto again;
957 }
Raymond Hettinger43442782004-03-17 21:55:03 +0000958 ep = mp->ma_table;
959 mask = mp->ma_mask;
960 for (i = 0, j = 0; i <= mask; i++) {
961 if (ep[i].me_value != NULL) {
962 PyObject *value = ep[i].me_value;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000963 Py_INCREF(value);
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000964 PyList_SET_ITEM(v, j, value);
Guido van Rossum25831651993-05-19 14:50:45 +0000965 j++;
966 }
967 }
Raymond Hettinger43442782004-03-17 21:55:03 +0000968 assert(j == n);
Guido van Rossum25831651993-05-19 14:50:45 +0000969 return v;
970}
971
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000972static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000973dict_items(register dictobject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +0000974{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000975 register PyObject *v;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000976 register int i, j, n;
Raymond Hettinger43442782004-03-17 21:55:03 +0000977 int mask;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000978 PyObject *item, *key, *value;
Raymond Hettinger43442782004-03-17 21:55:03 +0000979 dictentry *ep;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000980
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000981 /* Preallocate the list of tuples, to avoid allocations during
982 * the loop over the items, which could trigger GC, which
983 * could resize the dict. :-(
984 */
985 again:
986 n = mp->ma_used;
987 v = PyList_New(n);
Guido van Rossum25831651993-05-19 14:50:45 +0000988 if (v == NULL)
989 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000990 for (i = 0; i < n; i++) {
991 item = PyTuple_New(2);
992 if (item == NULL) {
993 Py_DECREF(v);
994 return NULL;
995 }
996 PyList_SET_ITEM(v, i, item);
997 }
998 if (n != mp->ma_used) {
999 /* Durnit. The allocations caused the dict to resize.
1000 * Just start over, this shouldn't normally happen.
1001 */
1002 Py_DECREF(v);
1003 goto again;
1004 }
1005 /* Nothing we do below makes any function calls. */
Raymond Hettinger43442782004-03-17 21:55:03 +00001006 ep = mp->ma_table;
1007 mask = mp->ma_mask;
1008 for (i = 0, j = 0; i <= mask; i++) {
1009 if (ep[i].me_value != NULL) {
1010 key = ep[i].me_key;
1011 value = ep[i].me_value;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001012 item = PyList_GET_ITEM(v, j);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001013 Py_INCREF(key);
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001014 PyTuple_SET_ITEM(item, 0, key);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001015 Py_INCREF(value);
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001016 PyTuple_SET_ITEM(item, 1, value);
Guido van Rossum25831651993-05-19 14:50:45 +00001017 j++;
1018 }
1019 }
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001020 assert(j == n);
Guido van Rossum25831651993-05-19 14:50:45 +00001021 return v;
1022}
1023
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001024static PyObject *
Tim Petersbca1cbc2002-12-09 22:56:13 +00001025dict_fromkeys(PyObject *cls, PyObject *args)
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001026{
1027 PyObject *seq;
1028 PyObject *value = Py_None;
1029 PyObject *it; /* iter(seq) */
1030 PyObject *key;
1031 PyObject *d;
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001032 int status;
1033
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001034 if (!PyArg_UnpackTuple(args, "fromkeys", 1, 2, &seq, &value))
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001035 return NULL;
1036
1037 d = PyObject_CallObject(cls, NULL);
1038 if (d == NULL)
1039 return NULL;
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001040
1041 it = PyObject_GetIter(seq);
1042 if (it == NULL){
1043 Py_DECREF(d);
1044 return NULL;
1045 }
1046
1047 for (;;) {
1048 key = PyIter_Next(it);
1049 if (key == NULL) {
1050 if (PyErr_Occurred())
1051 goto Fail;
1052 break;
1053 }
Raymond Hettingere03e5b12002-12-07 08:10:51 +00001054 status = PyObject_SetItem(d, key, value);
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001055 Py_DECREF(key);
1056 if (status < 0)
1057 goto Fail;
1058 }
1059
1060 Py_DECREF(it);
1061 return d;
1062
1063Fail:
1064 Py_DECREF(it);
1065 Py_DECREF(d);
1066 return NULL;
1067}
1068
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001069static int
1070dict_update_common(PyObject *self, PyObject *args, PyObject *kwds, char *methname)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001071{
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001072 PyObject *arg = NULL;
1073 int result = 0;
1074
1075 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
1076 result = -1;
1077
1078 else if (arg != NULL) {
1079 if (PyObject_HasAttrString(arg, "keys"))
1080 result = PyDict_Merge(self, arg, 1);
1081 else
1082 result = PyDict_MergeFromSeq2(self, arg, 1);
1083 }
1084 if (result == 0 && kwds != NULL)
1085 result = PyDict_Merge(self, kwds, 1);
1086 return result;
1087}
1088
1089static PyObject *
1090dict_update(PyObject *self, PyObject *args, PyObject *kwds)
1091{
1092 if (dict_update_common(self, args, kwds, "update") == -1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001093 return NULL;
1094 Py_INCREF(Py_None);
1095 return Py_None;
1096}
1097
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001098/* Update unconditionally replaces existing items.
1099 Merge has a 3rd argument 'override'; if set, it acts like Update,
Tim Peters1fc240e2001-10-26 05:06:50 +00001100 otherwise it leaves existing items unchanged.
1101
1102 PyDict_{Update,Merge} update/merge from a mapping object.
1103
Tim Petersf582b822001-12-11 18:51:08 +00001104 PyDict_MergeFromSeq2 updates/merges from any iterable object
Tim Peters1fc240e2001-10-26 05:06:50 +00001105 producing iterable objects of length 2.
1106*/
1107
Tim Petersf582b822001-12-11 18:51:08 +00001108int
Tim Peters1fc240e2001-10-26 05:06:50 +00001109PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
1110{
1111 PyObject *it; /* iter(seq2) */
1112 int i; /* index into seq2 of current element */
1113 PyObject *item; /* seq2[i] */
1114 PyObject *fast; /* item as a 2-tuple or 2-list */
1115
1116 assert(d != NULL);
1117 assert(PyDict_Check(d));
1118 assert(seq2 != NULL);
1119
1120 it = PyObject_GetIter(seq2);
1121 if (it == NULL)
1122 return -1;
1123
1124 for (i = 0; ; ++i) {
1125 PyObject *key, *value;
1126 int n;
1127
1128 fast = NULL;
1129 item = PyIter_Next(it);
1130 if (item == NULL) {
1131 if (PyErr_Occurred())
1132 goto Fail;
1133 break;
1134 }
1135
1136 /* Convert item to sequence, and verify length 2. */
1137 fast = PySequence_Fast(item, "");
1138 if (fast == NULL) {
1139 if (PyErr_ExceptionMatches(PyExc_TypeError))
1140 PyErr_Format(PyExc_TypeError,
1141 "cannot convert dictionary update "
1142 "sequence element #%d to a sequence",
1143 i);
1144 goto Fail;
1145 }
1146 n = PySequence_Fast_GET_SIZE(fast);
1147 if (n != 2) {
1148 PyErr_Format(PyExc_ValueError,
1149 "dictionary update sequence element #%d "
1150 "has length %d; 2 is required",
1151 i, n);
1152 goto Fail;
1153 }
1154
1155 /* Update/merge with this (key, value) pair. */
1156 key = PySequence_Fast_GET_ITEM(fast, 0);
1157 value = PySequence_Fast_GET_ITEM(fast, 1);
1158 if (override || PyDict_GetItem(d, key) == NULL) {
1159 int status = PyDict_SetItem(d, key, value);
1160 if (status < 0)
1161 goto Fail;
1162 }
1163 Py_DECREF(fast);
1164 Py_DECREF(item);
1165 }
1166
1167 i = 0;
1168 goto Return;
1169Fail:
1170 Py_XDECREF(item);
1171 Py_XDECREF(fast);
1172 i = -1;
1173Return:
1174 Py_DECREF(it);
1175 return i;
1176}
1177
Tim Peters6d6c1a32001-08-02 04:15:00 +00001178int
1179PyDict_Update(PyObject *a, PyObject *b)
1180{
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001181 return PyDict_Merge(a, b, 1);
1182}
1183
1184int
1185PyDict_Merge(PyObject *a, PyObject *b, int override)
1186{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001187 register PyDictObject *mp, *other;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001188 register int i;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001189 dictentry *entry;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001190
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001191 /* We accept for the argument either a concrete dictionary object,
1192 * or an abstract "mapping" object. For the former, we can do
1193 * things quite efficiently. For the latter, we only require that
1194 * PyMapping_Keys() and PyObject_GetItem() be supported.
1195 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001196 if (a == NULL || !PyDict_Check(a) || b == NULL) {
1197 PyErr_BadInternalCall();
1198 return -1;
1199 }
1200 mp = (dictobject*)a;
1201 if (PyDict_Check(b)) {
1202 other = (dictobject*)b;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001203 if (other == mp || other->ma_used == 0)
1204 /* a.update(a) or a.update({}); nothing to do */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001205 return 0;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001206 /* Do one big resize at the start, rather than
1207 * incrementally resizing as we insert new items. Expect
1208 * that there will be no (or few) overlapping keys.
1209 */
1210 if ((mp->ma_fill + other->ma_used)*3 >= (mp->ma_mask+1)*2) {
Raymond Hettingerc8d22902003-05-07 00:49:40 +00001211 if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001212 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001213 }
1214 for (i = 0; i <= other->ma_mask; i++) {
1215 entry = &other->ma_table[i];
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001216 if (entry->me_value != NULL &&
1217 (override ||
1218 PyDict_GetItem(a, entry->me_key) == NULL)) {
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001219 Py_INCREF(entry->me_key);
1220 Py_INCREF(entry->me_value);
1221 insertdict(mp, entry->me_key, entry->me_hash,
1222 entry->me_value);
1223 }
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001224 }
1225 }
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001226 else {
1227 /* Do it the generic, slower way */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001228 PyObject *keys = PyMapping_Keys(b);
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001229 PyObject *iter;
1230 PyObject *key, *value;
1231 int status;
1232
1233 if (keys == NULL)
1234 /* Docstring says this is equivalent to E.keys() so
1235 * if E doesn't have a .keys() method we want
1236 * AttributeError to percolate up. Might as well
1237 * do the same for any other error.
1238 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001239 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001240
1241 iter = PyObject_GetIter(keys);
1242 Py_DECREF(keys);
1243 if (iter == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001245
1246 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001247 if (!override && PyDict_GetItem(a, key) != NULL) {
1248 Py_DECREF(key);
1249 continue;
1250 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001251 value = PyObject_GetItem(b, key);
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001252 if (value == NULL) {
1253 Py_DECREF(iter);
1254 Py_DECREF(key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001255 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001256 }
Guido van Rossum05ac6de2001-08-10 20:28:28 +00001257 status = PyDict_SetItem(a, key, value);
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001258 Py_DECREF(key);
1259 Py_DECREF(value);
1260 if (status < 0) {
1261 Py_DECREF(iter);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001262 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001263 }
1264 }
1265 Py_DECREF(iter);
1266 if (PyErr_Occurred())
1267 /* Iterator completed, via error */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001268 return -1;
Barry Warsaw66a0d1d2001-06-26 20:08:32 +00001269 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001270 return 0;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001271}
1272
1273static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001274dict_copy(register dictobject *mp)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001275{
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001276 return PyDict_Copy((PyObject*)mp);
1277}
1278
1279PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001280PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001281{
Raymond Hettingerebedb2f2004-03-08 04:19:01 +00001282 PyObject *copy;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001283
1284 if (o == NULL || !PyDict_Check(o)) {
1285 PyErr_BadInternalCall();
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001286 return NULL;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001287 }
Raymond Hettingerebedb2f2004-03-08 04:19:01 +00001288 copy = PyDict_New();
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001289 if (copy == NULL)
1290 return NULL;
Raymond Hettingerebedb2f2004-03-08 04:19:01 +00001291 if (PyDict_Merge(copy, o, 1) == 0)
1292 return copy;
1293 Py_DECREF(copy);
1294 return copy;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001295}
1296
Guido van Rossum4199fac1993-11-05 10:18:44 +00001297int
Tim Peters1f5871e2000-07-04 17:44:48 +00001298PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00001299{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001300 if (mp == NULL || !PyDict_Check(mp)) {
1301 PyErr_BadInternalCall();
Jeremy Hylton7083bb72004-02-17 20:10:11 +00001302 return -1;
Guido van Rossum4199fac1993-11-05 10:18:44 +00001303 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001304 return ((dictobject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00001305}
1306
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001307PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001308PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001309{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001310 if (mp == NULL || !PyDict_Check(mp)) {
1311 PyErr_BadInternalCall();
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001312 return NULL;
1313 }
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001314 return dict_keys((dictobject *)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001315}
1316
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001317PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001318PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001319{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001320 if (mp == NULL || !PyDict_Check(mp)) {
1321 PyErr_BadInternalCall();
Guido van Rossum25831651993-05-19 14:50:45 +00001322 return NULL;
1323 }
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001324 return dict_values((dictobject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00001325}
1326
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001327PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001328PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001329{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001330 if (mp == NULL || !PyDict_Check(mp)) {
1331 PyErr_BadInternalCall();
Guido van Rossum25831651993-05-19 14:50:45 +00001332 return NULL;
1333 }
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001334 return dict_items((dictobject *)mp);
Guido van Rossum25831651993-05-19 14:50:45 +00001335}
1336
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001337/* Subroutine which returns the smallest key in a for which b's value
1338 is different or absent. The value is returned too, through the
Tim Peters95bf9392001-05-10 08:32:44 +00001339 pval argument. Both are NULL if no key in a is found for which b's status
1340 differs. The refcounts on (and only on) non-NULL *pval and function return
1341 values must be decremented by the caller (characterize() increments them
1342 to ensure that mutating comparison and PyDict_GetItem calls can't delete
1343 them before the caller is done looking at them). */
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001344
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001345static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001346characterize(dictobject *a, dictobject *b, PyObject **pval)
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001347{
Tim Peters95bf9392001-05-10 08:32:44 +00001348 PyObject *akey = NULL; /* smallest key in a s.t. a[akey] != b[akey] */
1349 PyObject *aval = NULL; /* a[akey] */
Guido van Rossumb9324202001-01-18 00:39:02 +00001350 int i, cmp;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001351
Tim Petersafb6ae82001-06-04 21:00:21 +00001352 for (i = 0; i <= a->ma_mask; i++) {
Tim Peters95bf9392001-05-10 08:32:44 +00001353 PyObject *thiskey, *thisaval, *thisbval;
1354 if (a->ma_table[i].me_value == NULL)
1355 continue;
1356 thiskey = a->ma_table[i].me_key;
1357 Py_INCREF(thiskey); /* keep alive across compares */
1358 if (akey != NULL) {
1359 cmp = PyObject_RichCompareBool(akey, thiskey, Py_LT);
1360 if (cmp < 0) {
1361 Py_DECREF(thiskey);
1362 goto Fail;
1363 }
1364 if (cmp > 0 ||
Tim Petersafb6ae82001-06-04 21:00:21 +00001365 i > a->ma_mask ||
Tim Peters95bf9392001-05-10 08:32:44 +00001366 a->ma_table[i].me_value == NULL)
1367 {
1368 /* Not the *smallest* a key; or maybe it is
1369 * but the compare shrunk the dict so we can't
1370 * find its associated value anymore; or
1371 * maybe it is but the compare deleted the
1372 * a[thiskey] entry.
1373 */
1374 Py_DECREF(thiskey);
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001375 continue;
Guido van Rossumb9324202001-01-18 00:39:02 +00001376 }
Tim Peters95bf9392001-05-10 08:32:44 +00001377 }
1378
1379 /* Compare a[thiskey] to b[thiskey]; cmp <- true iff equal. */
1380 thisaval = a->ma_table[i].me_value;
1381 assert(thisaval);
1382 Py_INCREF(thisaval); /* keep alive */
1383 thisbval = PyDict_GetItem((PyObject *)b, thiskey);
1384 if (thisbval == NULL)
1385 cmp = 0;
1386 else {
1387 /* both dicts have thiskey: same values? */
1388 cmp = PyObject_RichCompareBool(
1389 thisaval, thisbval, Py_EQ);
1390 if (cmp < 0) {
1391 Py_DECREF(thiskey);
1392 Py_DECREF(thisaval);
1393 goto Fail;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001394 }
1395 }
Tim Peters95bf9392001-05-10 08:32:44 +00001396 if (cmp == 0) {
1397 /* New winner. */
1398 Py_XDECREF(akey);
1399 Py_XDECREF(aval);
1400 akey = thiskey;
1401 aval = thisaval;
1402 }
1403 else {
1404 Py_DECREF(thiskey);
1405 Py_DECREF(thisaval);
1406 }
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001407 }
Tim Peters95bf9392001-05-10 08:32:44 +00001408 *pval = aval;
1409 return akey;
1410
1411Fail:
1412 Py_XDECREF(akey);
1413 Py_XDECREF(aval);
1414 *pval = NULL;
1415 return NULL;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001416}
1417
1418static int
Tim Peters1f5871e2000-07-04 17:44:48 +00001419dict_compare(dictobject *a, dictobject *b)
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001420{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001421 PyObject *adiff, *bdiff, *aval, *bval;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001422 int res;
1423
1424 /* Compare lengths first */
1425 if (a->ma_used < b->ma_used)
1426 return -1; /* a is shorter */
1427 else if (a->ma_used > b->ma_used)
1428 return 1; /* b is shorter */
Tim Peters95bf9392001-05-10 08:32:44 +00001429
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001430 /* Same length -- check all keys */
Tim Peters95bf9392001-05-10 08:32:44 +00001431 bdiff = bval = NULL;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001432 adiff = characterize(a, b, &aval);
Tim Peters95bf9392001-05-10 08:32:44 +00001433 if (adiff == NULL) {
1434 assert(!aval);
Tim Peters3918fb22001-05-10 18:58:31 +00001435 /* Either an error, or a is a subset with the same length so
Tim Peters95bf9392001-05-10 08:32:44 +00001436 * must be equal.
1437 */
1438 res = PyErr_Occurred() ? -1 : 0;
1439 goto Finished;
1440 }
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001441 bdiff = characterize(b, a, &bval);
Tim Peters95bf9392001-05-10 08:32:44 +00001442 if (bdiff == NULL && PyErr_Occurred()) {
1443 assert(!bval);
1444 res = -1;
1445 goto Finished;
1446 }
1447 res = 0;
1448 if (bdiff) {
1449 /* bdiff == NULL "should be" impossible now, but perhaps
1450 * the last comparison done by the characterize() on a had
1451 * the side effect of making the dicts equal!
1452 */
1453 res = PyObject_Compare(adiff, bdiff);
1454 }
1455 if (res == 0 && bval != NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001456 res = PyObject_Compare(aval, bval);
Tim Peters95bf9392001-05-10 08:32:44 +00001457
1458Finished:
1459 Py_XDECREF(adiff);
1460 Py_XDECREF(bdiff);
1461 Py_XDECREF(aval);
1462 Py_XDECREF(bval);
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001463 return res;
1464}
1465
Tim Peterse63415e2001-05-08 04:38:29 +00001466/* Return 1 if dicts equal, 0 if not, -1 if error.
1467 * Gets out as soon as any difference is detected.
1468 * Uses only Py_EQ comparison.
1469 */
1470static int
1471dict_equal(dictobject *a, dictobject *b)
1472{
1473 int i;
1474
1475 if (a->ma_used != b->ma_used)
1476 /* can't be equal if # of entries differ */
1477 return 0;
Tim Peterseb28ef22001-06-02 05:27:19 +00001478
Tim Peterse63415e2001-05-08 04:38:29 +00001479 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Tim Petersafb6ae82001-06-04 21:00:21 +00001480 for (i = 0; i <= a->ma_mask; i++) {
Tim Peterse63415e2001-05-08 04:38:29 +00001481 PyObject *aval = a->ma_table[i].me_value;
1482 if (aval != NULL) {
1483 int cmp;
1484 PyObject *bval;
1485 PyObject *key = a->ma_table[i].me_key;
1486 /* temporarily bump aval's refcount to ensure it stays
1487 alive until we're done with it */
1488 Py_INCREF(aval);
1489 bval = PyDict_GetItem((PyObject *)b, key);
1490 if (bval == NULL) {
1491 Py_DECREF(aval);
1492 return 0;
1493 }
1494 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
1495 Py_DECREF(aval);
1496 if (cmp <= 0) /* error or not equal */
1497 return cmp;
1498 }
1499 }
1500 return 1;
1501 }
1502
1503static PyObject *
1504dict_richcompare(PyObject *v, PyObject *w, int op)
1505{
1506 int cmp;
1507 PyObject *res;
1508
1509 if (!PyDict_Check(v) || !PyDict_Check(w)) {
1510 res = Py_NotImplemented;
1511 }
1512 else if (op == Py_EQ || op == Py_NE) {
1513 cmp = dict_equal((dictobject *)v, (dictobject *)w);
1514 if (cmp < 0)
1515 return NULL;
1516 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
1517 }
Tim Peters4fa58bf2001-05-10 21:45:19 +00001518 else
1519 res = Py_NotImplemented;
Tim Peterse63415e2001-05-08 04:38:29 +00001520 Py_INCREF(res);
1521 return res;
1522 }
1523
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001524static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001525dict_has_key(register dictobject *mp, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001526{
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001527 long hash;
1528 register long ok;
Tim Peters0ab085c2001-09-14 00:25:33 +00001529 if (!PyString_CheckExact(key) ||
Tim Peters1f7df352002-03-29 03:29:08 +00001530 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001531 hash = PyObject_Hash(key);
Guido van Rossumca756f21997-01-23 19:39:29 +00001532 if (hash == -1)
1533 return NULL;
1534 }
Tim Petersdea48ec2001-05-22 20:40:22 +00001535 ok = (mp->ma_lookup)(mp, key, hash)->me_value != NULL;
Guido van Rossum77f6a652002-04-03 22:41:51 +00001536 return PyBool_FromLong(ok);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001537}
1538
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001539static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001540dict_get(register dictobject *mp, PyObject *args)
Barry Warsawc38c5da1997-10-06 17:49:20 +00001541{
1542 PyObject *key;
Barry Warsaw320ac331997-10-20 17:26:25 +00001543 PyObject *failobj = Py_None;
Barry Warsawc38c5da1997-10-06 17:49:20 +00001544 PyObject *val = NULL;
1545 long hash;
1546
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001547 if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
Barry Warsawc38c5da1997-10-06 17:49:20 +00001548 return NULL;
1549
Tim Peters0ab085c2001-09-14 00:25:33 +00001550 if (!PyString_CheckExact(key) ||
Tim Peters1f7df352002-03-29 03:29:08 +00001551 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
Barry Warsawc38c5da1997-10-06 17:49:20 +00001552 hash = PyObject_Hash(key);
1553 if (hash == -1)
1554 return NULL;
1555 }
Fred Drake1bff34a2000-08-31 19:31:38 +00001556 val = (mp->ma_lookup)(mp, key, hash)->me_value;
Barry Warsaw320ac331997-10-20 17:26:25 +00001557
Barry Warsawc38c5da1997-10-06 17:49:20 +00001558 if (val == NULL)
1559 val = failobj;
1560 Py_INCREF(val);
1561 return val;
1562}
1563
1564
1565static PyObject *
Guido van Rossum164452c2000-08-08 16:12:54 +00001566dict_setdefault(register dictobject *mp, PyObject *args)
1567{
1568 PyObject *key;
1569 PyObject *failobj = Py_None;
1570 PyObject *val = NULL;
1571 long hash;
1572
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00001573 if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &failobj))
Guido van Rossum164452c2000-08-08 16:12:54 +00001574 return NULL;
Guido van Rossum164452c2000-08-08 16:12:54 +00001575
Tim Peters0ab085c2001-09-14 00:25:33 +00001576 if (!PyString_CheckExact(key) ||
Tim Peters1f7df352002-03-29 03:29:08 +00001577 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
Guido van Rossum164452c2000-08-08 16:12:54 +00001578 hash = PyObject_Hash(key);
1579 if (hash == -1)
1580 return NULL;
1581 }
Fred Drake1bff34a2000-08-31 19:31:38 +00001582 val = (mp->ma_lookup)(mp, key, hash)->me_value;
Guido van Rossum164452c2000-08-08 16:12:54 +00001583 if (val == NULL) {
1584 val = failobj;
1585 if (PyDict_SetItem((PyObject*)mp, key, failobj))
1586 val = NULL;
1587 }
1588 Py_XINCREF(val);
1589 return val;
1590}
1591
1592
1593static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001594dict_clear(register dictobject *mp)
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00001595{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001596 PyDict_Clear((PyObject *)mp);
1597 Py_INCREF(Py_None);
1598 return Py_None;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00001599}
1600
Guido van Rossumba6ab842000-12-12 22:02:18 +00001601static PyObject *
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001602dict_pop(dictobject *mp, PyObject *args)
Guido van Rossume027d982002-04-12 15:11:59 +00001603{
1604 long hash;
1605 dictentry *ep;
1606 PyObject *old_value, *old_key;
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001607 PyObject *key, *deflt = NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00001608
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001609 if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
1610 return NULL;
Guido van Rossume027d982002-04-12 15:11:59 +00001611 if (mp->ma_used == 0) {
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001612 if (deflt) {
1613 Py_INCREF(deflt);
1614 return deflt;
1615 }
Guido van Rossume027d982002-04-12 15:11:59 +00001616 PyErr_SetString(PyExc_KeyError,
1617 "pop(): dictionary is empty");
1618 return NULL;
1619 }
1620 if (!PyString_CheckExact(key) ||
1621 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
1622 hash = PyObject_Hash(key);
1623 if (hash == -1)
1624 return NULL;
1625 }
1626 ep = (mp->ma_lookup)(mp, key, hash);
1627 if (ep->me_value == NULL) {
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001628 if (deflt) {
1629 Py_INCREF(deflt);
1630 return deflt;
1631 }
Guido van Rossume027d982002-04-12 15:11:59 +00001632 PyErr_SetObject(PyExc_KeyError, key);
1633 return NULL;
1634 }
1635 old_key = ep->me_key;
1636 Py_INCREF(dummy);
1637 ep->me_key = dummy;
1638 old_value = ep->me_value;
1639 ep->me_value = NULL;
1640 mp->ma_used--;
1641 Py_DECREF(old_key);
1642 return old_value;
1643}
1644
1645static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001646dict_popitem(dictobject *mp)
Guido van Rossumba6ab842000-12-12 22:02:18 +00001647{
1648 int i = 0;
1649 dictentry *ep;
1650 PyObject *res;
1651
Tim Petersf4b33f62001-06-02 05:42:29 +00001652 /* Allocate the result tuple before checking the size. Believe it
1653 * or not, this allocation could trigger a garbage collection which
1654 * could empty the dict, so if we checked the size first and that
1655 * happened, the result would be an infinite loop (searching for an
1656 * entry that no longer exists). Note that the usual popitem()
1657 * idiom is "while d: k, v = d.popitem()". so needing to throw the
1658 * tuple away if the dict *is* empty isn't a significant
1659 * inefficiency -- possible, but unlikely in practice.
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001660 */
1661 res = PyTuple_New(2);
1662 if (res == NULL)
1663 return NULL;
Guido van Rossume04eaec2001-04-16 00:02:32 +00001664 if (mp->ma_used == 0) {
1665 Py_DECREF(res);
1666 PyErr_SetString(PyExc_KeyError,
1667 "popitem(): dictionary is empty");
1668 return NULL;
1669 }
Guido van Rossumba6ab842000-12-12 22:02:18 +00001670 /* Set ep to "the first" dict entry with a value. We abuse the hash
1671 * field of slot 0 to hold a search finger:
1672 * If slot 0 has a value, use slot 0.
1673 * Else slot 0 is being used to hold a search finger,
1674 * and we use its hash value as the first index to look.
1675 */
1676 ep = &mp->ma_table[0];
1677 if (ep->me_value == NULL) {
1678 i = (int)ep->me_hash;
Tim Petersdea48ec2001-05-22 20:40:22 +00001679 /* The hash field may be a real hash value, or it may be a
1680 * legit search finger, or it may be a once-legit search
1681 * finger that's out of bounds now because it wrapped around
1682 * or the table shrunk -- simply make sure it's in bounds now.
Guido van Rossumba6ab842000-12-12 22:02:18 +00001683 */
Tim Petersafb6ae82001-06-04 21:00:21 +00001684 if (i > mp->ma_mask || i < 1)
Guido van Rossumba6ab842000-12-12 22:02:18 +00001685 i = 1; /* skip slot 0 */
1686 while ((ep = &mp->ma_table[i])->me_value == NULL) {
1687 i++;
Tim Petersafb6ae82001-06-04 21:00:21 +00001688 if (i > mp->ma_mask)
Guido van Rossumba6ab842000-12-12 22:02:18 +00001689 i = 1;
1690 }
1691 }
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001692 PyTuple_SET_ITEM(res, 0, ep->me_key);
1693 PyTuple_SET_ITEM(res, 1, ep->me_value);
1694 Py_INCREF(dummy);
1695 ep->me_key = dummy;
1696 ep->me_value = NULL;
1697 mp->ma_used--;
1698 assert(mp->ma_table[0].me_value == NULL);
1699 mp->ma_table[0].me_hash = i + 1; /* next place to start */
Guido van Rossumba6ab842000-12-12 22:02:18 +00001700 return res;
1701}
1702
Jeremy Hylton8caad492000-06-23 14:18:11 +00001703static int
1704dict_traverse(PyObject *op, visitproc visit, void *arg)
1705{
1706 int i = 0, err;
1707 PyObject *pk;
1708 PyObject *pv;
1709
1710 while (PyDict_Next(op, &i, &pk, &pv)) {
1711 err = visit(pk, arg);
1712 if (err)
1713 return err;
1714 err = visit(pv, arg);
1715 if (err)
1716 return err;
1717 }
1718 return 0;
1719}
1720
1721static int
1722dict_tp_clear(PyObject *op)
1723{
1724 PyDict_Clear(op);
1725 return 0;
1726}
1727
Tim Petersf7f88b12000-12-13 23:18:45 +00001728
Raymond Hettinger019a1482004-03-18 02:41:19 +00001729extern PyTypeObject PyDictIterKey_Type; /* Forward */
1730extern PyTypeObject PyDictIterValue_Type; /* Forward */
1731extern PyTypeObject PyDictIterItem_Type; /* Forward */
1732static PyObject *dictiter_new(dictobject *, PyTypeObject *);
Guido van Rossum09e563a2001-05-01 12:10:21 +00001733
1734static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001735dict_iterkeys(dictobject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00001736{
Raymond Hettinger019a1482004-03-18 02:41:19 +00001737 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00001738}
1739
1740static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001741dict_itervalues(dictobject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00001742{
Raymond Hettinger019a1482004-03-18 02:41:19 +00001743 return dictiter_new(dict, &PyDictIterValue_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00001744}
1745
1746static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001747dict_iteritems(dictobject *dict)
Guido van Rossum09e563a2001-05-01 12:10:21 +00001748{
Raymond Hettinger019a1482004-03-18 02:41:19 +00001749 return dictiter_new(dict, &PyDictIterItem_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00001750}
1751
1752
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001753PyDoc_STRVAR(has_key__doc__,
Raymond Hettinger574aa322003-09-01 22:12:08 +00001754"D.has_key(k) -> True if D has a key k, else False");
Tim Petersf7f88b12000-12-13 23:18:45 +00001755
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00001756PyDoc_STRVAR(contains__doc__,
1757"D.__contains__(k) -> True if D has a key k, else False");
1758
1759PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
1760
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001761PyDoc_STRVAR(get__doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00001762"D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.");
Tim Petersf7f88b12000-12-13 23:18:45 +00001763
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001764PyDoc_STRVAR(setdefault_doc__,
Guido van Rossumefae8862002-09-04 11:29:45 +00001765"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 +00001766
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001767PyDoc_STRVAR(pop__doc__,
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001768"D.pop(k[,d]) -> v, remove specified key and return the corresponding value\n\
1769If key is not found, d is returned if given, otherwise KeyError is raised");
Guido van Rossume027d982002-04-12 15:11:59 +00001770
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001771PyDoc_STRVAR(popitem__doc__,
Tim Petersf7f88b12000-12-13 23:18:45 +00001772"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000017732-tuple; but raise KeyError if D is empty");
Tim Petersf7f88b12000-12-13 23:18:45 +00001774
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001775PyDoc_STRVAR(keys__doc__,
1776"D.keys() -> list of D's keys");
Tim Petersf7f88b12000-12-13 23:18:45 +00001777
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001778PyDoc_STRVAR(items__doc__,
1779"D.items() -> list of D's (key, value) pairs, as 2-tuples");
Tim Petersf7f88b12000-12-13 23:18:45 +00001780
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001781PyDoc_STRVAR(values__doc__,
1782"D.values() -> list of D's values");
Tim Petersf7f88b12000-12-13 23:18:45 +00001783
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001784PyDoc_STRVAR(update__doc__,
1785"D.update(E) -> None. Update D from E: for k in E.keys(): D[k] = E[k]");
Tim Petersf7f88b12000-12-13 23:18:45 +00001786
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001787PyDoc_STRVAR(fromkeys__doc__,
1788"dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.\n\
1789v defaults to None.");
1790
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001791PyDoc_STRVAR(clear__doc__,
1792"D.clear() -> None. Remove all items from D.");
Tim Petersf7f88b12000-12-13 23:18:45 +00001793
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001794PyDoc_STRVAR(copy__doc__,
1795"D.copy() -> a shallow copy of D");
Tim Petersf7f88b12000-12-13 23:18:45 +00001796
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001797PyDoc_STRVAR(iterkeys__doc__,
1798"D.iterkeys() -> an iterator over the keys of D");
Guido van Rossum09e563a2001-05-01 12:10:21 +00001799
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001800PyDoc_STRVAR(itervalues__doc__,
1801"D.itervalues() -> an iterator over the values of D");
Guido van Rossum09e563a2001-05-01 12:10:21 +00001802
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001803PyDoc_STRVAR(iteritems__doc__,
1804"D.iteritems() -> an iterator over the (key, value) items of D");
Guido van Rossum09e563a2001-05-01 12:10:21 +00001805
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001806static PyMethodDef mapp_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00001807 {"__contains__",(PyCFunction)dict_has_key, METH_O | METH_COEXIST,
1808 contains__doc__},
Raymond Hettinger0c669672003-12-13 13:31:55 +00001809 {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00001810 getitem__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001811 {"has_key", (PyCFunction)dict_has_key, METH_O,
Tim Petersf7f88b12000-12-13 23:18:45 +00001812 has_key__doc__},
1813 {"get", (PyCFunction)dict_get, METH_VARARGS,
1814 get__doc__},
1815 {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS,
1816 setdefault_doc__},
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +00001817 {"pop", (PyCFunction)dict_pop, METH_VARARGS,
Just van Rossuma797d812002-11-23 09:45:04 +00001818 pop__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001819 {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
Tim Petersf7f88b12000-12-13 23:18:45 +00001820 popitem__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001821 {"keys", (PyCFunction)dict_keys, METH_NOARGS,
Tim Petersf7f88b12000-12-13 23:18:45 +00001822 keys__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001823 {"items", (PyCFunction)dict_items, METH_NOARGS,
Tim Petersf7f88b12000-12-13 23:18:45 +00001824 items__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001825 {"values", (PyCFunction)dict_values, METH_NOARGS,
Tim Petersf7f88b12000-12-13 23:18:45 +00001826 values__doc__},
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001827 {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
Tim Petersf7f88b12000-12-13 23:18:45 +00001828 update__doc__},
Raymond Hettingere33d3df2002-11-27 07:29:33 +00001829 {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS,
1830 fromkeys__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001831 {"clear", (PyCFunction)dict_clear, METH_NOARGS,
Tim Petersf7f88b12000-12-13 23:18:45 +00001832 clear__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001833 {"copy", (PyCFunction)dict_copy, METH_NOARGS,
Tim Petersf7f88b12000-12-13 23:18:45 +00001834 copy__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001835 {"iterkeys", (PyCFunction)dict_iterkeys, METH_NOARGS,
Guido van Rossum09e563a2001-05-01 12:10:21 +00001836 iterkeys__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001837 {"itervalues", (PyCFunction)dict_itervalues, METH_NOARGS,
Guido van Rossum09e563a2001-05-01 12:10:21 +00001838 itervalues__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001839 {"iteritems", (PyCFunction)dict_iteritems, METH_NOARGS,
Guido van Rossum09e563a2001-05-01 12:10:21 +00001840 iteritems__doc__},
Tim Petersf7f88b12000-12-13 23:18:45 +00001841 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001842};
1843
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00001844int
1845PyDict_Contains(PyObject *op, PyObject *key)
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001846{
1847 long hash;
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00001848 dictobject *mp = (dictobject *)op;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001849
Tim Peters0ab085c2001-09-14 00:25:33 +00001850 if (!PyString_CheckExact(key) ||
Tim Peters1f7df352002-03-29 03:29:08 +00001851 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001852 hash = PyObject_Hash(key);
1853 if (hash == -1)
1854 return -1;
1855 }
Tim Petersdea48ec2001-05-22 20:40:22 +00001856 return (mp->ma_lookup)(mp, key, hash)->me_value != NULL;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001857}
1858
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001859/* Hack to implement "key in dict" */
1860static PySequenceMethods dict_as_sequence = {
1861 0, /* sq_length */
1862 0, /* sq_concat */
1863 0, /* sq_repeat */
1864 0, /* sq_item */
1865 0, /* sq_slice */
1866 0, /* sq_ass_item */
1867 0, /* sq_ass_slice */
Raymond Hettingerbc0f2ab2003-11-25 21:12:14 +00001868 (objobjproc)PyDict_Contains, /* sq_contains */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001869 0, /* sq_inplace_concat */
1870 0, /* sq_inplace_repeat */
1871};
1872
Guido van Rossum09e563a2001-05-01 12:10:21 +00001873static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001874dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1875{
1876 PyObject *self;
1877
1878 assert(type != NULL && type->tp_alloc != NULL);
1879 self = type->tp_alloc(type, 0);
1880 if (self != NULL) {
1881 PyDictObject *d = (PyDictObject *)self;
1882 /* It's guaranteed that tp->alloc zeroed out the struct. */
1883 assert(d->ma_table == NULL && d->ma_fill == 0 && d->ma_used == 0);
1884 INIT_NONZERO_DICT_SLOTS(d);
1885 d->ma_lookup = lookdict_string;
1886#ifdef SHOW_CONVERSION_COUNTS
1887 ++created;
1888#endif
1889 }
1890 return self;
1891}
1892
Tim Peters25786c02001-09-02 08:22:48 +00001893static int
1894dict_init(PyObject *self, PyObject *args, PyObject *kwds)
1895{
Raymond Hettinger31017ae2004-03-04 08:25:44 +00001896 return dict_update_common(self, args, kwds, "dict");
Tim Peters25786c02001-09-02 08:22:48 +00001897}
1898
Guido van Rossumdbb53d92001-12-03 16:32:18 +00001899static long
1900dict_nohash(PyObject *self)
1901{
1902 PyErr_SetString(PyExc_TypeError, "dict objects are unhashable");
1903 return -1;
1904}
1905
Tim Peters6d6c1a32001-08-02 04:15:00 +00001906static PyObject *
Guido van Rossum09e563a2001-05-01 12:10:21 +00001907dict_iter(dictobject *dict)
1908{
Raymond Hettinger019a1482004-03-18 02:41:19 +00001909 return dictiter_new(dict, &PyDictIterKey_Type);
Guido van Rossum09e563a2001-05-01 12:10:21 +00001910}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001911
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001912PyDoc_STRVAR(dictionary_doc,
Tim Petersa427a2b2001-10-29 22:25:45 +00001913"dict() -> new empty dictionary.\n"
1914"dict(mapping) -> new dictionary initialized from a mapping object's\n"
Tim Peters1fc240e2001-10-26 05:06:50 +00001915" (key, value) pairs.\n"
Tim Petersa427a2b2001-10-29 22:25:45 +00001916"dict(seq) -> new dictionary initialized as if via:\n"
Tim Peters4d859532001-10-27 18:27:48 +00001917" d = {}\n"
1918" for k, v in seq:\n"
Just van Rossuma797d812002-11-23 09:45:04 +00001919" d[k] = v\n"
1920"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
1921" in the keyword argument list. For example: dict(one=1, two=2)");
Tim Peters25786c02001-09-02 08:22:48 +00001922
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001923PyTypeObject PyDict_Type = {
1924 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001925 0,
Tim Petersa427a2b2001-10-29 22:25:45 +00001926 "dict",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00001927 sizeof(dictobject),
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001928 0,
Guido van Rossumb9324202001-01-18 00:39:02 +00001929 (destructor)dict_dealloc, /* tp_dealloc */
1930 (printfunc)dict_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001931 0, /* tp_getattr */
Guido van Rossumb9324202001-01-18 00:39:02 +00001932 0, /* tp_setattr */
Tim Peters4fa58bf2001-05-10 21:45:19 +00001933 (cmpfunc)dict_compare, /* tp_compare */
Guido van Rossumb9324202001-01-18 00:39:02 +00001934 (reprfunc)dict_repr, /* tp_repr */
1935 0, /* tp_as_number */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001936 &dict_as_sequence, /* tp_as_sequence */
Guido van Rossumb9324202001-01-18 00:39:02 +00001937 &dict_as_mapping, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00001938 dict_nohash, /* tp_hash */
Guido van Rossumb9324202001-01-18 00:39:02 +00001939 0, /* tp_call */
1940 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001941 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossumb9324202001-01-18 00:39:02 +00001942 0, /* tp_setattro */
1943 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00001944 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00001945 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters25786c02001-09-02 08:22:48 +00001946 dictionary_doc, /* tp_doc */
Guido van Rossumb9324202001-01-18 00:39:02 +00001947 (traverseproc)dict_traverse, /* tp_traverse */
1948 (inquiry)dict_tp_clear, /* tp_clear */
Tim Peterse63415e2001-05-08 04:38:29 +00001949 dict_richcompare, /* tp_richcompare */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001950 0, /* tp_weaklistoffset */
Guido van Rossum09e563a2001-05-01 12:10:21 +00001951 (getiterfunc)dict_iter, /* tp_iter */
Guido van Rossum213c7a62001-04-23 14:08:49 +00001952 0, /* tp_iternext */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001953 mapp_methods, /* tp_methods */
1954 0, /* tp_members */
1955 0, /* tp_getset */
1956 0, /* tp_base */
1957 0, /* tp_dict */
1958 0, /* tp_descr_get */
1959 0, /* tp_descr_set */
1960 0, /* tp_dictoffset */
Tim Peters25786c02001-09-02 08:22:48 +00001961 (initproc)dict_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001962 PyType_GenericAlloc, /* tp_alloc */
1963 dict_new, /* tp_new */
Neil Schemenauer6189b892002-04-12 02:43:00 +00001964 PyObject_GC_Del, /* tp_free */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001965};
1966
Guido van Rossum3cca2451997-05-16 14:23:33 +00001967/* For backward compatibility with old dictionary interface */
1968
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001969PyObject *
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00001970PyDict_GetItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001971{
Guido van Rossum3cca2451997-05-16 14:23:33 +00001972 PyObject *kv, *rv;
1973 kv = PyString_FromString(key);
1974 if (kv == NULL)
1975 return NULL;
Guido van Rossum3cca2451997-05-16 14:23:33 +00001976 rv = PyDict_GetItem(v, kv);
1977 Py_DECREF(kv);
1978 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001979}
1980
1981int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00001982PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001983{
Guido van Rossum3cca2451997-05-16 14:23:33 +00001984 PyObject *kv;
1985 int err;
1986 kv = PyString_FromString(key);
1987 if (kv == NULL)
Guido van Rossum037b2201997-05-20 18:35:19 +00001988 return -1;
Guido van Rossum4f3bf1e1997-09-29 23:31:11 +00001989 PyString_InternInPlace(&kv); /* XXX Should we really? */
Guido van Rossum3cca2451997-05-16 14:23:33 +00001990 err = PyDict_SetItem(v, kv, item);
1991 Py_DECREF(kv);
1992 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001993}
1994
1995int
Martin v. Löwis32b4a1b2002-12-11 13:21:12 +00001996PyDict_DelItemString(PyObject *v, const char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001997{
Guido van Rossum3cca2451997-05-16 14:23:33 +00001998 PyObject *kv;
1999 int err;
2000 kv = PyString_FromString(key);
2001 if (kv == NULL)
Guido van Rossum037b2201997-05-20 18:35:19 +00002002 return -1;
Guido van Rossum3cca2451997-05-16 14:23:33 +00002003 err = PyDict_DelItem(v, kv);
2004 Py_DECREF(kv);
2005 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00002006}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002007
Raymond Hettinger019a1482004-03-18 02:41:19 +00002008/* Dictionary iterator types */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002009
2010typedef struct {
2011 PyObject_HEAD
Guido van Rossum2147df72002-07-16 20:30:22 +00002012 dictobject *di_dict; /* Set to NULL when iterator is exhausted */
Guido van Rossumb1f35bf2001-05-02 15:13:44 +00002013 int di_used;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002014 int di_pos;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002015 PyObject* di_result; /* reusable result tuple for iteritems */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002016} dictiterobject;
2017
2018static PyObject *
Raymond Hettinger019a1482004-03-18 02:41:19 +00002019dictiter_new(dictobject *dict, PyTypeObject *itertype)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002020{
2021 dictiterobject *di;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002022 di = PyObject_New(dictiterobject, itertype);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002023 if (di == NULL)
2024 return NULL;
2025 Py_INCREF(dict);
2026 di->di_dict = dict;
Guido van Rossumb1f35bf2001-05-02 15:13:44 +00002027 di->di_used = dict->ma_used;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002028 di->di_pos = 0;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002029 if (itertype == &PyDictIterItem_Type) {
2030 di->di_result = PyTuple_Pack(2, Py_None, Py_None);
2031 if (di->di_result == NULL) {
2032 Py_DECREF(di);
2033 return NULL;
2034 }
2035 }
2036 else
2037 di->di_result = NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002038 return (PyObject *)di;
2039}
2040
2041static void
2042dictiter_dealloc(dictiterobject *di)
2043{
Guido van Rossum2147df72002-07-16 20:30:22 +00002044 Py_XDECREF(di->di_dict);
Raymond Hettinger019a1482004-03-18 02:41:19 +00002045 Py_XDECREF(di->di_result);
Neil Schemenauer6189b892002-04-12 02:43:00 +00002046 PyObject_Del(di);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002047}
2048
Raymond Hettinger019a1482004-03-18 02:41:19 +00002049static PyObject *dictiter_iternextkey(dictiterobject *di)
Guido van Rossum213c7a62001-04-23 14:08:49 +00002050{
Raymond Hettinger019a1482004-03-18 02:41:19 +00002051 PyObject *key;
2052 register int i, mask;
2053 register dictentry *ep;
2054 dictobject *d = di->di_dict;
Guido van Rossum213c7a62001-04-23 14:08:49 +00002055
Raymond Hettinger019a1482004-03-18 02:41:19 +00002056 if (d == NULL)
Guido van Rossum2147df72002-07-16 20:30:22 +00002057 return NULL;
Raymond Hettinger019a1482004-03-18 02:41:19 +00002058 assert (PyDict_Check(d));
Guido van Rossum2147df72002-07-16 20:30:22 +00002059
Raymond Hettinger019a1482004-03-18 02:41:19 +00002060 if (di->di_used != d->ma_used) {
Guido van Rossum213c7a62001-04-23 14:08:49 +00002061 PyErr_SetString(PyExc_RuntimeError,
2062 "dictionary changed size during iteration");
Guido van Rossum2147df72002-07-16 20:30:22 +00002063 di->di_used = -1; /* Make this state sticky */
Guido van Rossum213c7a62001-04-23 14:08:49 +00002064 return NULL;
2065 }
Guido van Rossum2147df72002-07-16 20:30:22 +00002066
Raymond Hettinger019a1482004-03-18 02:41:19 +00002067 i = di->di_pos;
2068 if (i < 0)
2069 goto fail;
2070 ep = d->ma_table;
2071 mask = d->ma_mask;
2072 while (i <= mask && ep[i].me_value == NULL)
2073 i++;
2074 di->di_pos = i+1;
2075 if (i > mask)
2076 goto fail;
2077 key = ep[i].me_key;
2078 Py_INCREF(key);
2079 return key;
2080
2081fail:
2082 Py_DECREF(d);
Guido van Rossum2147df72002-07-16 20:30:22 +00002083 di->di_dict = NULL;
Guido van Rossum213c7a62001-04-23 14:08:49 +00002084 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002085}
2086
Raymond Hettinger019a1482004-03-18 02:41:19 +00002087PyTypeObject PyDictIterKey_Type = {
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002088 PyObject_HEAD_INIT(&PyType_Type)
2089 0, /* ob_size */
Raymond Hettinger019a1482004-03-18 02:41:19 +00002090 "dictionary-keyiterator", /* tp_name */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002091 sizeof(dictiterobject), /* tp_basicsize */
2092 0, /* tp_itemsize */
2093 /* methods */
2094 (destructor)dictiter_dealloc, /* tp_dealloc */
2095 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002096 0, /* tp_getattr */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002097 0, /* tp_setattr */
2098 0, /* tp_compare */
2099 0, /* tp_repr */
2100 0, /* tp_as_number */
2101 0, /* tp_as_sequence */
2102 0, /* tp_as_mapping */
2103 0, /* tp_hash */
2104 0, /* tp_call */
2105 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002106 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002107 0, /* tp_setattro */
2108 0, /* tp_as_buffer */
2109 Py_TPFLAGS_DEFAULT, /* tp_flags */
2110 0, /* tp_doc */
2111 0, /* tp_traverse */
2112 0, /* tp_clear */
2113 0, /* tp_richcompare */
2114 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002115 PyObject_SelfIter, /* tp_iter */
Raymond Hettinger019a1482004-03-18 02:41:19 +00002116 (iternextfunc)dictiter_iternextkey, /* tp_iternext */
2117};
2118
2119static PyObject *dictiter_iternextvalue(dictiterobject *di)
2120{
2121 PyObject *value;
2122 register int i, mask;
2123 register dictentry *ep;
2124 dictobject *d = di->di_dict;
2125
2126 if (d == NULL)
2127 return NULL;
2128 assert (PyDict_Check(d));
2129
2130 if (di->di_used != d->ma_used) {
2131 PyErr_SetString(PyExc_RuntimeError,
2132 "dictionary changed size during iteration");
2133 di->di_used = -1; /* Make this state sticky */
2134 return NULL;
2135 }
2136
2137 i = di->di_pos;
2138 if (i < 0)
2139 goto fail;
2140 ep = d->ma_table;
2141 mask = d->ma_mask;
2142 while (i <= mask && (value=ep[i].me_value) == NULL)
2143 i++;
2144 di->di_pos = i+1;
2145 if (i > mask)
2146 goto fail;
2147 Py_INCREF(value);
2148 return value;
2149
2150fail:
2151 Py_DECREF(d);
2152 di->di_dict = NULL;
2153 return NULL;
2154}
2155
2156PyTypeObject PyDictIterValue_Type = {
2157 PyObject_HEAD_INIT(&PyType_Type)
2158 0, /* ob_size */
2159 "dictionary-valueiterator", /* tp_name */
2160 sizeof(dictiterobject), /* tp_basicsize */
2161 0, /* tp_itemsize */
2162 /* methods */
2163 (destructor)dictiter_dealloc, /* tp_dealloc */
2164 0, /* tp_print */
2165 0, /* tp_getattr */
2166 0, /* tp_setattr */
2167 0, /* tp_compare */
2168 0, /* tp_repr */
2169 0, /* tp_as_number */
2170 0, /* tp_as_sequence */
2171 0, /* tp_as_mapping */
2172 0, /* tp_hash */
2173 0, /* tp_call */
2174 0, /* tp_str */
2175 PyObject_GenericGetAttr, /* tp_getattro */
2176 0, /* tp_setattro */
2177 0, /* tp_as_buffer */
2178 Py_TPFLAGS_DEFAULT, /* tp_flags */
2179 0, /* tp_doc */
2180 0, /* tp_traverse */
2181 0, /* tp_clear */
2182 0, /* tp_richcompare */
2183 0, /* tp_weaklistoffset */
2184 PyObject_SelfIter, /* tp_iter */
2185 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
2186};
2187
2188static PyObject *dictiter_iternextitem(dictiterobject *di)
2189{
2190 PyObject *key, *value, *result = di->di_result;
2191 register int i, mask;
2192 register dictentry *ep;
2193 dictobject *d = di->di_dict;
2194
2195 if (d == NULL)
2196 return NULL;
2197 assert (PyDict_Check(d));
2198
2199 if (di->di_used != d->ma_used) {
2200 PyErr_SetString(PyExc_RuntimeError,
2201 "dictionary changed size during iteration");
2202 di->di_used = -1; /* Make this state sticky */
2203 return NULL;
2204 }
2205
2206 i = di->di_pos;
2207 if (i < 0)
2208 goto fail;
2209 ep = d->ma_table;
2210 mask = d->ma_mask;
2211 while (i <= mask && ep[i].me_value == NULL)
2212 i++;
2213 di->di_pos = i+1;
2214 if (i > mask)
2215 goto fail;
2216
2217 if (result->ob_refcnt == 1) {
2218 Py_INCREF(result);
2219 Py_DECREF(PyTuple_GET_ITEM(result, 0));
2220 Py_DECREF(PyTuple_GET_ITEM(result, 1));
2221 } else {
2222 result = PyTuple_New(2);
2223 if (result == NULL)
2224 return NULL;
2225 }
2226 key = ep[i].me_key;
2227 value = ep[i].me_value;
2228 Py_INCREF(key);
2229 Py_INCREF(value);
2230 PyTuple_SET_ITEM(result, 0, key);
2231 PyTuple_SET_ITEM(result, 1, value);
2232 return result;
2233
2234fail:
2235 Py_DECREF(d);
2236 di->di_dict = NULL;
2237 return NULL;
2238}
2239
2240PyTypeObject PyDictIterItem_Type = {
2241 PyObject_HEAD_INIT(&PyType_Type)
2242 0, /* ob_size */
2243 "dictionary-itemiterator", /* tp_name */
2244 sizeof(dictiterobject), /* tp_basicsize */
2245 0, /* tp_itemsize */
2246 /* methods */
2247 (destructor)dictiter_dealloc, /* tp_dealloc */
2248 0, /* tp_print */
2249 0, /* tp_getattr */
2250 0, /* tp_setattr */
2251 0, /* tp_compare */
2252 0, /* tp_repr */
2253 0, /* tp_as_number */
2254 0, /* tp_as_sequence */
2255 0, /* tp_as_mapping */
2256 0, /* tp_hash */
2257 0, /* tp_call */
2258 0, /* tp_str */
2259 PyObject_GenericGetAttr, /* tp_getattro */
2260 0, /* tp_setattro */
2261 0, /* tp_as_buffer */
2262 Py_TPFLAGS_DEFAULT, /* tp_flags */
2263 0, /* tp_doc */
2264 0, /* tp_traverse */
2265 0, /* tp_clear */
2266 0, /* tp_richcompare */
2267 0, /* tp_weaklistoffset */
2268 PyObject_SelfIter, /* tp_iter */
2269 (iternextfunc)dictiter_iternextitem, /* tp_iternext */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002270};