blob: 754c75055be828a39ab89355ec154c0a4ba10048 [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
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossum4b1302b1993-03-27 18:11:32 +00005
Tim Peterseb28ef22001-06-02 05:27:19 +00006/* MINSIZE is the minimum size of a dictionary. This many slots are
Tim Petersdea48ec2001-05-22 20:40:22 +00007 * allocated directly in the dict object (in the ma_smalltable member).
Tim Peterseb28ef22001-06-02 05:27:19 +00008 * It must be a power of 2, and at least 4. 8 allows dicts with no more than
9 * 5 active entries to live in ma_smalltable (and so avoid an additional
10 * malloc); instrumentation suggested this suffices for the majority of
11 * dicts (consisting mostly of usually-small instance dicts and usually-small
12 * dicts created to pass keyword arguments).
Guido van Rossum16e93a81997-01-28 00:00:11 +000013 */
Tim Petersdea48ec2001-05-22 20:40:22 +000014#define MINSIZE 8
Guido van Rossum16e93a81997-01-28 00:00:11 +000015
Tim Peterseb28ef22001-06-02 05:27:19 +000016/* Define this out if you don't want conversion statistics on exit. */
Fred Drake1bff34a2000-08-31 19:31:38 +000017#undef SHOW_CONVERSION_COUNTS
18
Tim Peterseb28ef22001-06-02 05:27:19 +000019/* See large comment block below. This must be >= 1. */
20#define PERTURB_SHIFT 5
21
Guido van Rossum16e93a81997-01-28 00:00:11 +000022/*
Tim Peterseb28ef22001-06-02 05:27:19 +000023Major subtleties ahead: Most hash schemes depend on having a "good" hash
24function, in the sense of simulating randomness. Python doesn't: its most
25important hash functions (for strings and ints) are very regular in common
26cases:
Tim Peters15d49292001-05-27 07:39:22 +000027
Tim Peterseb28ef22001-06-02 05:27:19 +000028>>> map(hash, (0, 1, 2, 3))
29[0, 1, 2, 3]
30>>> map(hash, ("namea", "nameb", "namec", "named"))
31[-1658398457, -1658398460, -1658398459, -1658398462]
32>>>
Tim Peters15d49292001-05-27 07:39:22 +000033
Tim Peterseb28ef22001-06-02 05:27:19 +000034This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
35the low-order i bits as the initial table index is extremely fast, and there
36are no collisions at all for dicts indexed by a contiguous range of ints.
37The same is approximately true when keys are "consecutive" strings. So this
38gives better-than-random behavior in common cases, and that's very desirable.
Tim Peters15d49292001-05-27 07:39:22 +000039
Tim Peterseb28ef22001-06-02 05:27:19 +000040OTOH, when collisions occur, the tendency to fill contiguous slices of the
41hash table makes a good collision resolution strategy crucial. Taking only
42the last i bits of the hash code is also vulnerable: for example, consider
43[i << 16 for i in range(20000)] as a set of keys. Since ints are their own
44hash codes, and this fits in a dict of size 2**15, the last 15 bits of every
45hash code are all 0: they *all* map to the same table index.
Tim Peters15d49292001-05-27 07:39:22 +000046
Tim Peterseb28ef22001-06-02 05:27:19 +000047But catering to unusual cases should not slow the usual ones, so we just take
48the last i bits anyway. It's up to collision resolution to do the rest. If
49we *usually* find the key we're looking for on the first try (and, it turns
50out, we usually do -- the table load factor is kept under 2/3, so the odds
51are solidly in our favor), then it makes best sense to keep the initial index
52computation dirt cheap.
Tim Peters15d49292001-05-27 07:39:22 +000053
Tim Peterseb28ef22001-06-02 05:27:19 +000054The first half of collision resolution is to visit table indices via this
55recurrence:
Tim Peters15d49292001-05-27 07:39:22 +000056
Tim Peterseb28ef22001-06-02 05:27:19 +000057 j = ((5*j) + 1) mod 2**i
Tim Peters15d49292001-05-27 07:39:22 +000058
Tim Peterseb28ef22001-06-02 05:27:19 +000059For any initial j in range(2**i), repeating that 2**i times generates each
60int in range(2**i) exactly once (see any text on random-number generation for
61proof). By itself, this doesn't help much: like linear probing (setting
62j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
63order. This would be bad, except that's not the only thing we do, and it's
64actually *good* in the common cases where hash keys are consecutive. In an
65example that's really too small to make this entirely clear, for a table of
66size 2**3 the order of indices is:
Tim Peters15d49292001-05-27 07:39:22 +000067
Tim Peterseb28ef22001-06-02 05:27:19 +000068 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
69
70If two things come in at index 5, the first place we look after is index 2,
71not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
72Linear probing is deadly in this case because there the fixed probe order
73is the *same* as the order consecutive keys are likely to arrive. But it's
74extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
75and certain that consecutive hash codes do not.
76
77The other half of the strategy is to get the other bits of the hash code
78into play. This is done by initializing a (unsigned) vrbl "perturb" to the
79full hash code, and changing the recurrence to:
80
81 j = (5*j) + 1 + perturb;
82 perturb >>= PERTURB_SHIFT;
83 use j % 2**i as the next table index;
84
85Now the probe sequence depends (eventually) on every bit in the hash code,
86and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
87because it quickly magnifies small differences in the bits that didn't affect
88the initial index. Note that because perturb is unsigned, if the recurrence
89is executed often enough perturb eventually becomes and remains 0. At that
90point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
91that's certain to find an empty slot eventually (since it generates every int
92in range(2**i), and we make sure there's always at least one empty slot).
93
94Selecting a good value for PERTURB_SHIFT is a balancing act. You want it
95small so that the high bits of the hash code continue to affect the probe
96sequence across iterations; but you want it large so that in really bad cases
97the high-order hash bits have an effect on early iterations. 5 was "the
98best" in minimizing total collisions across experiments Tim Peters ran (on
99both normal and pathological cases), but 4 and 6 weren't significantly worse.
100
101Historical: Reimer Behrends contributed the idea of using a polynomial-based
102approach, using repeated multiplication by x in GF(2**n) where an irreducible
103polynomial for each table size was chosen such that x was a primitive root.
104Christian Tismer later extended that to use division by x instead, as an
105efficient way to get the high bits of the hash code into play. This scheme
106also gave excellent collision statistics, but was more expensive: two
107if-tests were required inside the loop; computing "the next" index took about
108the same number of operations but without as much potential parallelism
109(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
110above, and then shifting perturb can be done while the table index is being
111masked); and the dictobject struct required a member to hold the table's
112polynomial. In Tim's experiments the current scheme ran faster, produced
113equally good collision statistics, needed less code & used less memory.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000114*/
Tim Petersdea48ec2001-05-22 20:40:22 +0000115
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000116/* Object used as dummy key to fill deleted entries */
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000117static PyObject *dummy; /* Initialized by first call to newdictobject() */
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000118
119/*
Tim Petersea8f2bf2000-12-13 01:02:46 +0000120There are three kinds of slots in the table:
121
1221. Unused. me_key == me_value == NULL
123 Does not hold an active (key, value) pair now and never did. Unused can
124 transition to Active upon key insertion. This is the only case in which
125 me_key is NULL, and is each slot's initial state.
126
1272. Active. me_key != NULL and me_key != dummy and me_value != NULL
128 Holds an active (key, value) pair. Active can transition to Dummy upon
129 key deletion. This is the only case in which me_value != NULL.
130
Tim Petersf1c7c882000-12-13 19:58:25 +00001313. Dummy. me_key == dummy and me_value == NULL
Tim Petersea8f2bf2000-12-13 01:02:46 +0000132 Previously held an active (key, value) pair, but that was deleted and an
133 active pair has not yet overwritten the slot. Dummy can transition to
134 Active upon key insertion. Dummy slots cannot be made Unused again
135 (cannot have me_key set to NULL), else the probe sequence in case of
136 collision would have no way to know they were once active.
Tim Petersf1c7c882000-12-13 19:58:25 +0000137
138Note: .popitem() abuses the me_hash field of an Unused or Dummy slot to
139hold a search finger. The me_hash field of Unused or Dummy slots has no
140meaning otherwise.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000141*/
142typedef struct {
Tim Petersea8f2bf2000-12-13 01:02:46 +0000143 long me_hash; /* cached hash code of me_key */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000144 PyObject *me_key;
145 PyObject *me_value;
Guido van Rossum36488841997-04-11 19:14:07 +0000146#ifdef USE_CACHE_ALIGNED
147 long aligner;
148#endif
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000149} dictentry;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000150
151/*
Tim Petersf1c7c882000-12-13 19:58:25 +0000152To ensure the lookup algorithm terminates, there must be at least one Unused
Tim Petersea8f2bf2000-12-13 01:02:46 +0000153slot (NULL key) in the table.
154The value ma_fill is the number of non-NULL keys (sum of Active and Dummy);
155ma_used is the number of non-NULL, non-dummy keys (== the number of non-NULL
156values == the number of Active items).
157To avoid slowing down lookups on a near-full table, we resize the table when
Tim Peters67830702001-03-21 19:23:56 +0000158it's two-thirds full.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000159*/
Fred Drake1bff34a2000-08-31 19:31:38 +0000160typedef struct dictobject dictobject;
161struct dictobject {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000162 PyObject_HEAD
Tim Petersea8f2bf2000-12-13 01:02:46 +0000163 int ma_fill; /* # Active + # Dummy */
164 int ma_used; /* # Active */
165 int ma_size; /* total # slots in ma_table */
Tim Petersdea48ec2001-05-22 20:40:22 +0000166 /* ma_table points to ma_smalltable for small tables, else to
167 * additional malloc'ed memory. ma_table is never NULL! This rule
168 * saves repeated runtime null-tests in the workhorse getitem and
169 * setitem calls.
170 */
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000171 dictentry *ma_table;
Fred Drake1bff34a2000-08-31 19:31:38 +0000172 dictentry *(*ma_lookup)(dictobject *mp, PyObject *key, long hash);
Tim Petersdea48ec2001-05-22 20:40:22 +0000173 dictentry ma_smalltable[MINSIZE];
Fred Drake1bff34a2000-08-31 19:31:38 +0000174};
175
176/* forward declarations */
177static dictentry *
178lookdict_string(dictobject *mp, PyObject *key, long hash);
179
180#ifdef SHOW_CONVERSION_COUNTS
181static long created = 0L;
182static long converted = 0L;
183
184static void
185show_counts(void)
186{
187 fprintf(stderr, "created %ld string dicts\n", created);
188 fprintf(stderr, "converted %ld to normal dicts\n", converted);
189 fprintf(stderr, "%.2f%% conversion rate\n", (100.0*converted)/created);
190}
191#endif
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000192
Tim Petersdea48ec2001-05-22 20:40:22 +0000193/* Set dictobject* mp to empty but w/ MINSIZE slots, using ma_smalltable. */
194#define empty_to_minsize(mp) do { \
195 memset((mp)->ma_smalltable, 0, sizeof((mp)->ma_smalltable)); \
196 (mp)->ma_table = (mp)->ma_smalltable; \
197 (mp)->ma_size = MINSIZE; \
198 (mp)->ma_used = (mp)->ma_fill = 0; \
Tim Petersdea48ec2001-05-22 20:40:22 +0000199 } while(0)
200
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000201PyObject *
Thomas Wouters78890102000-07-22 19:25:51 +0000202PyDict_New(void)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000203{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000204 register dictobject *mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000205 if (dummy == NULL) { /* Auto-initialize dummy */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000206 dummy = PyString_FromString("<dummy key>");
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000207 if (dummy == NULL)
208 return NULL;
Fred Drake1bff34a2000-08-31 19:31:38 +0000209#ifdef SHOW_CONVERSION_COUNTS
210 Py_AtExit(show_counts);
211#endif
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000212 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000213 mp = PyObject_NEW(dictobject, &PyDict_Type);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000214 if (mp == NULL)
215 return NULL;
Tim Petersdea48ec2001-05-22 20:40:22 +0000216 empty_to_minsize(mp);
Fred Drake1bff34a2000-08-31 19:31:38 +0000217 mp->ma_lookup = lookdict_string;
218#ifdef SHOW_CONVERSION_COUNTS
219 ++created;
220#endif
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000221 PyObject_GC_Init(mp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000222 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000223}
224
225/*
226The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000227This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000228Open addressing is preferred over chaining since the link overhead for
229chaining would be substantial (100% with typical malloc overhead).
230
Tim Peterseb28ef22001-06-02 05:27:19 +0000231The initial probe index is computed as hash mod the table size. Subsequent
232probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000233
234All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000235
Tim Peterseb28ef22001-06-02 05:27:19 +0000236(The details in this version are due to Tim Peters, building on many past
237contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
238Christian Tismer).
Fred Drake1bff34a2000-08-31 19:31:38 +0000239
240This function must never return NULL; failures are indicated by returning
241a dictentry* for which the me_value field is NULL. Exceptions are never
242reported by this function, and outstanding exceptions are maintained.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000243*/
Tim Peterseb28ef22001-06-02 05:27:19 +0000244
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000245static dictentry *
Tim Peters1f5871e2000-07-04 17:44:48 +0000246lookdict(dictobject *mp, PyObject *key, register long hash)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000247{
Guido van Rossum16e93a81997-01-28 00:00:11 +0000248 register int i;
Tim Peterseb28ef22001-06-02 05:27:19 +0000249 register unsigned int perturb;
Guido van Rossumfd7a0b81997-08-18 21:52:47 +0000250 register dictentry *freeslot;
Guido van Rossum2095d241997-04-09 19:41:24 +0000251 register unsigned int mask = mp->ma_size-1;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000252 dictentry *ep0 = mp->ma_table;
253 register dictentry *ep;
Fred Drakec88b99c2000-08-31 19:04:07 +0000254 register int restore_error = 0;
255 register int checked_error = 0;
256 register int cmp;
257 PyObject *err_type, *err_value, *err_tb;
Tim Peterseb28ef22001-06-02 05:27:19 +0000258
Tim Peters2f228e72001-05-13 00:19:31 +0000259 i = hash & mask;
Guido van Rossumefb46091997-01-29 15:53:56 +0000260 ep = &ep0[i];
Guido van Rossumc1c7b1a1998-10-06 16:01:14 +0000261 if (ep->me_key == NULL || ep->me_key == key)
Guido van Rossum7d181591997-01-16 21:06:45 +0000262 return ep;
Guido van Rossum16e93a81997-01-28 00:00:11 +0000263 if (ep->me_key == dummy)
Guido van Rossum7d181591997-01-16 21:06:45 +0000264 freeslot = ep;
Guido van Rossumfd7a0b81997-08-18 21:52:47 +0000265 else {
Fred Drakec88b99c2000-08-31 19:04:07 +0000266 if (ep->me_hash == hash) {
267 /* error can't have been checked yet */
268 checked_error = 1;
269 if (PyErr_Occurred()) {
270 restore_error = 1;
271 PyErr_Fetch(&err_type, &err_value, &err_tb);
272 }
Guido van Rossumb9324202001-01-18 00:39:02 +0000273 cmp = PyObject_RichCompareBool(ep->me_key, key, Py_EQ);
274 if (cmp > 0) {
Fred Drakec88b99c2000-08-31 19:04:07 +0000275 if (restore_error)
276 PyErr_Restore(err_type, err_value,
277 err_tb);
278 return ep;
279 }
Guido van Rossumb9324202001-01-18 00:39:02 +0000280 else if (cmp < 0)
281 PyErr_Clear();
Guido van Rossumfd7a0b81997-08-18 21:52:47 +0000282 }
283 freeslot = NULL;
Guido van Rossum2a61e741997-01-18 07:55:05 +0000284 }
Tim Peters15d49292001-05-27 07:39:22 +0000285
Tim Peters342c65e2001-05-13 06:43:53 +0000286 /* In the loop, me_key == dummy is by far (factor of 100s) the
287 least likely outcome, so test for that last. */
Tim Peterseb28ef22001-06-02 05:27:19 +0000288 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
289 i = (i << 2) + i + perturb + 1;
290 ep = &ep0[i & mask];
Guido van Rossum16e93a81997-01-28 00:00:11 +0000291 if (ep->me_key == NULL) {
Fred Drakec88b99c2000-08-31 19:04:07 +0000292 if (restore_error)
293 PyErr_Restore(err_type, err_value, err_tb);
Tim Peters342c65e2001-05-13 06:43:53 +0000294 return freeslot == NULL ? ep : freeslot;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000295 }
Tim Peters342c65e2001-05-13 06:43:53 +0000296 if (ep->me_key == key) {
Fred Drakec88b99c2000-08-31 19:04:07 +0000297 if (restore_error)
298 PyErr_Restore(err_type, err_value, err_tb);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000299 return ep;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000300 }
Tim Peters342c65e2001-05-13 06:43:53 +0000301 else if (ep->me_hash == hash && ep->me_key != dummy) {
Fred Drakec88b99c2000-08-31 19:04:07 +0000302 if (!checked_error) {
303 checked_error = 1;
304 if (PyErr_Occurred()) {
305 restore_error = 1;
306 PyErr_Fetch(&err_type, &err_value,
307 &err_tb);
308 }
309 }
Guido van Rossumb9324202001-01-18 00:39:02 +0000310 cmp = PyObject_RichCompareBool(ep->me_key, key, Py_EQ);
311 if (cmp > 0) {
Fred Drakec88b99c2000-08-31 19:04:07 +0000312 if (restore_error)
313 PyErr_Restore(err_type, err_value,
314 err_tb);
315 return ep;
316 }
Guido van Rossumb9324202001-01-18 00:39:02 +0000317 else if (cmp < 0)
318 PyErr_Clear();
Guido van Rossum16e93a81997-01-28 00:00:11 +0000319 }
Tim Peters342c65e2001-05-13 06:43:53 +0000320 else if (ep->me_key == dummy && freeslot == NULL)
321 freeslot = ep;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000322 }
323}
324
325/*
Fred Drake1bff34a2000-08-31 19:31:38 +0000326 * Hacked up version of lookdict which can assume keys are always strings;
327 * this assumption allows testing for errors during PyObject_Compare() to
328 * be dropped; string-string comparisons never raise exceptions. This also
329 * means we don't need to go through PyObject_Compare(); we can always use
Martin v. Löwiscd353062001-05-24 16:56:35 +0000330 * _PyString_Eq directly.
Fred Drake1bff34a2000-08-31 19:31:38 +0000331 *
332 * This really only becomes meaningful if proper error handling in lookdict()
333 * is too expensive.
334 */
335static dictentry *
336lookdict_string(dictobject *mp, PyObject *key, register long hash)
337{
338 register int i;
Tim Peterseb28ef22001-06-02 05:27:19 +0000339 register unsigned int perturb;
Fred Drake1bff34a2000-08-31 19:31:38 +0000340 register dictentry *freeslot;
341 register unsigned int mask = mp->ma_size-1;
342 dictentry *ep0 = mp->ma_table;
343 register dictentry *ep;
Fred Drake1bff34a2000-08-31 19:31:38 +0000344
345 /* make sure this function doesn't have to handle non-string keys */
346 if (!PyString_Check(key)) {
347#ifdef SHOW_CONVERSION_COUNTS
348 ++converted;
349#endif
350 mp->ma_lookup = lookdict;
351 return lookdict(mp, key, hash);
352 }
Tim Peters2f228e72001-05-13 00:19:31 +0000353 i = hash & mask;
Fred Drake1bff34a2000-08-31 19:31:38 +0000354 ep = &ep0[i];
355 if (ep->me_key == NULL || ep->me_key == key)
356 return ep;
357 if (ep->me_key == dummy)
358 freeslot = ep;
359 else {
360 if (ep->me_hash == hash
Martin v. Löwiscd353062001-05-24 16:56:35 +0000361 && _PyString_Eq(ep->me_key, key)) {
Fred Drake1bff34a2000-08-31 19:31:38 +0000362 return ep;
363 }
364 freeslot = NULL;
365 }
Tim Peters15d49292001-05-27 07:39:22 +0000366
Tim Peters342c65e2001-05-13 06:43:53 +0000367 /* In the loop, me_key == dummy is by far (factor of 100s) the
368 least likely outcome, so test for that last. */
Tim Peterseb28ef22001-06-02 05:27:19 +0000369 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
370 i = (i << 2) + i + perturb + 1;
371 ep = &ep0[i & mask];
Tim Peters342c65e2001-05-13 06:43:53 +0000372 if (ep->me_key == NULL)
373 return freeslot == NULL ? ep : freeslot;
374 if (ep->me_key == key
375 || (ep->me_hash == hash
376 && ep->me_key != dummy
Martin v. Löwiscd353062001-05-24 16:56:35 +0000377 && _PyString_Eq(ep->me_key, key)))
Fred Drake1bff34a2000-08-31 19:31:38 +0000378 return ep;
Tim Petersdea48ec2001-05-22 20:40:22 +0000379 if (ep->me_key == dummy && freeslot == NULL)
Tim Peters342c65e2001-05-13 06:43:53 +0000380 freeslot = ep;
Fred Drake1bff34a2000-08-31 19:31:38 +0000381 }
382}
383
384/*
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000385Internal routine to insert a new item into the table.
386Used both by the internal resize routine and by the public insert routine.
387Eats a reference to key and one to value.
388*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000389static void
Tim Peters1f5871e2000-07-04 17:44:48 +0000390insertdict(register dictobject *mp, PyObject *key, long hash, PyObject *value)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000391{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000392 PyObject *old_value;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000393 register dictentry *ep;
Fred Drake1bff34a2000-08-31 19:31:38 +0000394 ep = (mp->ma_lookup)(mp, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000395 if (ep->me_value != NULL) {
Guido van Rossumd7047b31995-01-02 19:07:15 +0000396 old_value = ep->me_value;
397 ep->me_value = value;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000398 Py_DECREF(old_value); /* which **CAN** re-enter */
399 Py_DECREF(key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000400 }
401 else {
402 if (ep->me_key == NULL)
403 mp->ma_fill++;
404 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000405 Py_DECREF(ep->me_key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000406 ep->me_key = key;
407 ep->me_hash = hash;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000408 ep->me_value = value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000409 mp->ma_used++;
410 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000411}
412
413/*
414Restructure the table by allocating a new table and reinserting all
415items again. When entries have been deleted, the new table may
416actually be smaller than the old one.
417*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000418static int
Tim Peters1f5871e2000-07-04 17:44:48 +0000419dictresize(dictobject *mp, int minused)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000420{
Tim Peterseb28ef22001-06-02 05:27:19 +0000421 int newsize;
Tim Peters0c6010b2001-05-23 23:33:57 +0000422 dictentry *oldtable, *newtable, *ep;
423 int i;
424 int is_oldtable_malloced;
425 dictentry small_copy[MINSIZE];
Tim Peters91a364d2001-05-19 07:04:38 +0000426
427 assert(minused >= 0);
Tim Peters0c6010b2001-05-23 23:33:57 +0000428
Tim Peterseb28ef22001-06-02 05:27:19 +0000429 /* Find the smallest table size > minused. */
430 for (newsize = MINSIZE;
431 newsize <= minused && newsize > 0;
432 newsize <<= 1)
433 ;
434 if (newsize <= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000435 PyErr_NoMemory();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000436 return -1;
437 }
Tim Peters0c6010b2001-05-23 23:33:57 +0000438
439 /* Get space for a new table. */
440 oldtable = mp->ma_table;
441 assert(oldtable != NULL);
442 is_oldtable_malloced = oldtable != mp->ma_smalltable;
443
Tim Petersdea48ec2001-05-22 20:40:22 +0000444 if (newsize == MINSIZE) {
Tim Petersf8a548c2001-05-24 16:26:40 +0000445 /* A large table is shrinking, or we can't get any smaller. */
Tim Petersdea48ec2001-05-22 20:40:22 +0000446 newtable = mp->ma_smalltable;
Tim Peters0c6010b2001-05-23 23:33:57 +0000447 if (newtable == oldtable) {
Tim Petersf8a548c2001-05-24 16:26:40 +0000448 if (mp->ma_fill == mp->ma_used) {
449 /* No dummies, so no point doing anything. */
Tim Peters0c6010b2001-05-23 23:33:57 +0000450 return 0;
Tim Petersf8a548c2001-05-24 16:26:40 +0000451 }
452 /* We're not going to resize it, but rebuild the
453 table anyway to purge old dummy entries.
454 Subtle: This is *necessary* if fill==size,
455 as lookdict needs at least one virgin slot to
456 terminate failing searches. If fill < size, it's
457 merely desirable, as dummies slow searches. */
458 assert(mp->ma_fill > mp->ma_used);
Tim Peters0c6010b2001-05-23 23:33:57 +0000459 memcpy(small_copy, oldtable, sizeof(small_copy));
460 oldtable = small_copy;
461 }
Tim Petersdea48ec2001-05-22 20:40:22 +0000462 }
463 else {
464 newtable = PyMem_NEW(dictentry, newsize);
465 if (newtable == NULL) {
466 PyErr_NoMemory();
467 return -1;
468 }
469 }
Tim Peters0c6010b2001-05-23 23:33:57 +0000470
471 /* Make the dict empty, using the new table. */
Tim Petersdea48ec2001-05-22 20:40:22 +0000472 assert(newtable != oldtable);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000473 mp->ma_table = newtable;
Tim Petersdea48ec2001-05-22 20:40:22 +0000474 mp->ma_size = newsize;
475 memset(newtable, 0, sizeof(dictentry) * newsize);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000476 mp->ma_used = 0;
Tim Petersdea48ec2001-05-22 20:40:22 +0000477 i = mp->ma_fill;
478 mp->ma_fill = 0;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000479
Tim Peters19283142001-05-17 22:25:34 +0000480 /* Copy the data over; this is refcount-neutral for active entries;
481 dummy entries aren't copied over, of course */
Tim Petersdea48ec2001-05-22 20:40:22 +0000482 for (ep = oldtable; i > 0; ep++) {
483 if (ep->me_value != NULL) { /* active entry */
484 --i;
Tim Peters19283142001-05-17 22:25:34 +0000485 insertdict(mp, ep->me_key, ep->me_hash, ep->me_value);
Tim Petersdea48ec2001-05-22 20:40:22 +0000486 }
Tim Peters19283142001-05-17 22:25:34 +0000487 else if (ep->me_key != NULL) { /* dummy entry */
Tim Petersdea48ec2001-05-22 20:40:22 +0000488 --i;
Tim Peters19283142001-05-17 22:25:34 +0000489 assert(ep->me_key == dummy);
490 Py_DECREF(ep->me_key);
Guido van Rossum255443b1998-04-10 22:47:14 +0000491 }
Tim Peters19283142001-05-17 22:25:34 +0000492 /* else key == value == NULL: nothing to do */
Guido van Rossumd7047b31995-01-02 19:07:15 +0000493 }
494
Tim Peters0c6010b2001-05-23 23:33:57 +0000495 if (is_oldtable_malloced)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000496 PyMem_DEL(oldtable);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000497 return 0;
498}
499
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000500PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000501PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000502{
503 long hash;
Fred Drake1bff34a2000-08-31 19:31:38 +0000504 dictobject *mp = (dictobject *)op;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000505 if (!PyDict_Check(op)) {
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000506 return NULL;
507 }
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000508#ifdef CACHE_HASH
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000509 if (!PyString_Check(key) ||
510 (hash = ((PyStringObject *) key)->ob_shash) == -1)
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000511#endif
Guido van Rossumca756f21997-01-23 19:39:29 +0000512 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000513 hash = PyObject_Hash(key);
Guido van Rossum474b19e1998-05-14 01:00:51 +0000514 if (hash == -1) {
515 PyErr_Clear();
Guido van Rossumca756f21997-01-23 19:39:29 +0000516 return NULL;
Guido van Rossum474b19e1998-05-14 01:00:51 +0000517 }
Guido van Rossumca756f21997-01-23 19:39:29 +0000518 }
Fred Drake1bff34a2000-08-31 19:31:38 +0000519 return (mp->ma_lookup)(mp, key, hash)->me_value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000520}
521
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000522/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
523 * dictionary if it is merely replacing the value for an existing key.
524 * This is means that it's safe to loop over a dictionary with
525 * PyDict_Next() and occasionally replace a value -- but you can't
526 * insert new keys or remove them.
527 */
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000528int
Tim Peters1f5871e2000-07-04 17:44:48 +0000529PyDict_SetItem(register PyObject *op, PyObject *key, PyObject *value)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000530{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000531 register dictobject *mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000532 register long hash;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000533 register int n_used;
534
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000535 if (!PyDict_Check(op)) {
536 PyErr_BadInternalCall();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000537 return -1;
538 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000539 mp = (dictobject *)op;
Guido van Rossum2a61e741997-01-18 07:55:05 +0000540#ifdef CACHE_HASH
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000541 if (PyString_Check(key)) {
Guido van Rossum2a61e741997-01-18 07:55:05 +0000542#ifdef INTERN_STRINGS
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000543 if (((PyStringObject *)key)->ob_sinterned != NULL) {
544 key = ((PyStringObject *)key)->ob_sinterned;
545 hash = ((PyStringObject *)key)->ob_shash;
Guido van Rossum2a61e741997-01-18 07:55:05 +0000546 }
547 else
548#endif
549 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000550 hash = ((PyStringObject *)key)->ob_shash;
Guido van Rossum2a61e741997-01-18 07:55:05 +0000551 if (hash == -1)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000552 hash = PyObject_Hash(key);
Guido van Rossum2a61e741997-01-18 07:55:05 +0000553 }
554 }
555 else
556#endif
557 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000558 hash = PyObject_Hash(key);
Guido van Rossum2a61e741997-01-18 07:55:05 +0000559 if (hash == -1)
560 return -1;
Guido van Rossum2a61e741997-01-18 07:55:05 +0000561 }
Tim Petersdea48ec2001-05-22 20:40:22 +0000562 assert(mp->ma_fill < mp->ma_size);
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000563 n_used = mp->ma_used;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000564 Py_INCREF(value);
565 Py_INCREF(key);
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000566 insertdict(mp, key, hash, value);
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000567 /* If we added a key, we can safely resize. Otherwise skip this!
568 * If fill >= 2/3 size, adjust size. Normally, this doubles the
569 * size, but it's also possible for the dict to shrink (if ma_fill is
570 * much larger than ma_used, meaning a lot of dict keys have been
571 * deleted).
572 */
573 if (mp->ma_used > n_used && mp->ma_fill*3 >= mp->ma_size*2) {
574 if (dictresize(mp, mp->ma_used*2) != 0)
575 return -1;
576 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000577 return 0;
578}
579
580int
Tim Peters1f5871e2000-07-04 17:44:48 +0000581PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000582{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000583 register dictobject *mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000584 register long hash;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000585 register dictentry *ep;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000586 PyObject *old_value, *old_key;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000587
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000588 if (!PyDict_Check(op)) {
589 PyErr_BadInternalCall();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000590 return -1;
591 }
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000592#ifdef CACHE_HASH
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000593 if (!PyString_Check(key) ||
594 (hash = ((PyStringObject *) key)->ob_shash) == -1)
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000595#endif
Guido van Rossumca756f21997-01-23 19:39:29 +0000596 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000597 hash = PyObject_Hash(key);
Guido van Rossumca756f21997-01-23 19:39:29 +0000598 if (hash == -1)
599 return -1;
600 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000601 mp = (dictobject *)op;
Fred Drake1bff34a2000-08-31 19:31:38 +0000602 ep = (mp->ma_lookup)(mp, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000603 if (ep->me_value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000604 PyErr_SetObject(PyExc_KeyError, key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000605 return -1;
606 }
Guido van Rossumd7047b31995-01-02 19:07:15 +0000607 old_key = ep->me_key;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000608 Py_INCREF(dummy);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000609 ep->me_key = dummy;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000610 old_value = ep->me_value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000611 ep->me_value = NULL;
612 mp->ma_used--;
Tim Petersea8f2bf2000-12-13 01:02:46 +0000613 Py_DECREF(old_value);
614 Py_DECREF(old_key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000615 return 0;
616}
617
Guido van Rossum25831651993-05-19 14:50:45 +0000618void
Tim Peters1f5871e2000-07-04 17:44:48 +0000619PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000620{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000621 dictobject *mp;
Tim Petersdea48ec2001-05-22 20:40:22 +0000622 dictentry *ep, *table;
623 int table_is_malloced;
624 int fill;
625 dictentry small_copy[MINSIZE];
626#ifdef Py_DEBUG
627 int i, n;
628#endif
629
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000630 if (!PyDict_Check(op))
Guido van Rossum25831651993-05-19 14:50:45 +0000631 return;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000632 mp = (dictobject *)op;
Tim Petersdea48ec2001-05-22 20:40:22 +0000633#ifdef Py_DEBUG
Guido van Rossumd7047b31995-01-02 19:07:15 +0000634 n = mp->ma_size;
Tim Petersdea48ec2001-05-22 20:40:22 +0000635 i = 0;
636#endif
637
638 table = mp->ma_table;
639 assert(table != NULL);
640 table_is_malloced = table != mp->ma_smalltable;
641
642 /* This is delicate. During the process of clearing the dict,
643 * decrefs can cause the dict to mutate. To avoid fatal confusion
644 * (voice of experience), we have to make the dict empty before
645 * clearing the slots, and never refer to anything via mp->xxx while
646 * clearing.
647 */
648 fill = mp->ma_fill;
649 if (table_is_malloced)
650 empty_to_minsize(mp);
651
652 else if (fill > 0) {
653 /* It's a small table with something that needs to be cleared.
654 * Afraid the only safe way is to copy the dict entries into
655 * another small table first.
656 */
657 memcpy(small_copy, table, sizeof(small_copy));
658 table = small_copy;
659 empty_to_minsize(mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000660 }
Tim Petersdea48ec2001-05-22 20:40:22 +0000661 /* else it's a small table that's already empty */
662
663 /* Now we can finally clear things. If C had refcounts, we could
664 * assert that the refcount on table is 1 now, i.e. that this function
665 * has unique access to it, so decref side-effects can't alter it.
666 */
667 for (ep = table; fill > 0; ++ep) {
668#ifdef Py_DEBUG
669 assert(i < n);
670 ++i;
671#endif
672 if (ep->me_key) {
673 --fill;
674 Py_DECREF(ep->me_key);
675 Py_XDECREF(ep->me_value);
676 }
677#ifdef Py_DEBUG
678 else
679 assert(ep->me_value == NULL);
680#endif
681 }
682
683 if (table_is_malloced)
684 PyMem_DEL(table);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000685}
686
Tim Peters67830702001-03-21 19:23:56 +0000687/* CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
688 * mutates the dict. One exception: it is safe if the loop merely changes
689 * the values associated with the keys (but doesn't insert new keys or
690 * delete keys), via PyDict_SetItem().
691 */
Guido van Rossum25831651993-05-19 14:50:45 +0000692int
Tim Peters1f5871e2000-07-04 17:44:48 +0000693PyDict_Next(PyObject *op, int *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000694{
Guido van Rossum25831651993-05-19 14:50:45 +0000695 int i;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000696 register dictobject *mp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000697 if (!PyDict_Check(op))
Guido van Rossum25831651993-05-19 14:50:45 +0000698 return 0;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000699 mp = (dictobject *)op;
Guido van Rossum25831651993-05-19 14:50:45 +0000700 i = *ppos;
701 if (i < 0)
702 return 0;
703 while (i < mp->ma_size && mp->ma_table[i].me_value == NULL)
704 i++;
705 *ppos = i+1;
706 if (i >= mp->ma_size)
707 return 0;
708 if (pkey)
709 *pkey = mp->ma_table[i].me_key;
710 if (pvalue)
711 *pvalue = mp->ma_table[i].me_value;
712 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 Rossumd724b232000-03-13 16:01:29 +0000722 Py_TRASHCAN_SAFE_BEGIN(mp)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000723 PyObject_GC_Fini(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);
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000733 mp = (dictobject *) PyObject_AS_GC(mp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000734 PyObject_DEL(mp);
Guido van Rossumd724b232000-03-13 16:01:29 +0000735 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000736}
737
738static int
Tim Peters1f5871e2000-07-04 17:44:48 +0000739dict_print(register dictobject *mp, register FILE *fp, register int flags)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000740{
741 register int i;
742 register int any;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000743 register dictentry *ep;
Guido van Rossum255443b1998-04-10 22:47:14 +0000744
745 i = Py_ReprEnter((PyObject*)mp);
746 if (i != 0) {
747 if (i < 0)
748 return i;
749 fprintf(fp, "{...}");
750 return 0;
751 }
752
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000753 fprintf(fp, "{");
754 any = 0;
755 for (i = 0, ep = mp->ma_table; i < mp->ma_size; i++, ep++) {
756 if (ep->me_value != NULL) {
757 if (any++ > 0)
758 fprintf(fp, ", ");
Guido van Rossum255443b1998-04-10 22:47:14 +0000759 if (PyObject_Print((PyObject *)ep->me_key, fp, 0)!=0) {
760 Py_ReprLeave((PyObject*)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000761 return -1;
Guido van Rossum255443b1998-04-10 22:47:14 +0000762 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000763 fprintf(fp, ": ");
Guido van Rossum255443b1998-04-10 22:47:14 +0000764 if (PyObject_Print(ep->me_value, fp, 0) != 0) {
765 Py_ReprLeave((PyObject*)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000766 return -1;
Guido van Rossum255443b1998-04-10 22:47:14 +0000767 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000768 }
769 }
770 fprintf(fp, "}");
Guido van Rossum255443b1998-04-10 22:47:14 +0000771 Py_ReprLeave((PyObject*)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000772 return 0;
773}
774
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000775static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000776dict_repr(dictobject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000777{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000778 auto PyObject *v;
779 PyObject *sepa, *colon;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000780 register int i;
781 register int any;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000782 register dictentry *ep;
Guido van Rossum255443b1998-04-10 22:47:14 +0000783
784 i = Py_ReprEnter((PyObject*)mp);
785 if (i != 0) {
786 if (i > 0)
787 return PyString_FromString("{...}");
788 return NULL;
789 }
790
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000791 v = PyString_FromString("{");
792 sepa = PyString_FromString(", ");
793 colon = PyString_FromString(": ");
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000794 any = 0;
Guido van Rossum1d5735e1994-08-30 08:27:36 +0000795 for (i = 0, ep = mp->ma_table; i < mp->ma_size && v; i++, ep++) {
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000796 if (ep->me_value != NULL) {
797 if (any++)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000798 PyString_Concat(&v, sepa);
799 PyString_ConcatAndDel(&v, PyObject_Repr(ep->me_key));
800 PyString_Concat(&v, colon);
801 PyString_ConcatAndDel(&v, PyObject_Repr(ep->me_value));
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000802 }
803 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000804 PyString_ConcatAndDel(&v, PyString_FromString("}"));
Guido van Rossum255443b1998-04-10 22:47:14 +0000805 Py_ReprLeave((PyObject*)mp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000806 Py_XDECREF(sepa);
807 Py_XDECREF(colon);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000808 return v;
809}
810
811static int
Tim Peters1f5871e2000-07-04 17:44:48 +0000812dict_length(dictobject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000813{
814 return mp->ma_used;
815}
816
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000817static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000818dict_subscript(dictobject *mp, register PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000819{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000820 PyObject *v;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000821 long hash;
Tim Petersdea48ec2001-05-22 20:40:22 +0000822 assert(mp->ma_table != NULL);
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000823#ifdef CACHE_HASH
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000824 if (!PyString_Check(key) ||
825 (hash = ((PyStringObject *) key)->ob_shash) == -1)
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000826#endif
Guido van Rossumca756f21997-01-23 19:39:29 +0000827 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000828 hash = PyObject_Hash(key);
Guido van Rossumca756f21997-01-23 19:39:29 +0000829 if (hash == -1)
830 return NULL;
831 }
Fred Drake1bff34a2000-08-31 19:31:38 +0000832 v = (mp->ma_lookup)(mp, key, hash) -> me_value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000833 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000834 PyErr_SetObject(PyExc_KeyError, key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000835 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000836 Py_INCREF(v);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000837 return v;
838}
839
840static int
Tim Peters1f5871e2000-07-04 17:44:48 +0000841dict_ass_sub(dictobject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000842{
843 if (w == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000844 return PyDict_DelItem((PyObject *)mp, v);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000845 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000846 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000847}
848
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000849static PyMappingMethods dict_as_mapping = {
850 (inquiry)dict_length, /*mp_length*/
851 (binaryfunc)dict_subscript, /*mp_subscript*/
852 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000853};
854
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000855static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000856dict_keys(register dictobject *mp, PyObject *args)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000857{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000858 register PyObject *v;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000859 register int i, j, n;
860
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000861 if (!PyArg_NoArgs(args))
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000862 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000863 again:
864 n = mp->ma_used;
865 v = PyList_New(n);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000866 if (v == NULL)
867 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000868 if (n != mp->ma_used) {
869 /* Durnit. The allocations caused the dict to resize.
870 * Just start over, this shouldn't normally happen.
871 */
872 Py_DECREF(v);
873 goto again;
874 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000875 for (i = 0, j = 0; i < mp->ma_size; i++) {
876 if (mp->ma_table[i].me_value != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000877 PyObject *key = mp->ma_table[i].me_key;
878 Py_INCREF(key);
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000879 PyList_SET_ITEM(v, j, key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000880 j++;
881 }
882 }
883 return v;
884}
885
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000886static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000887dict_values(register dictobject *mp, PyObject *args)
Guido van Rossum25831651993-05-19 14:50:45 +0000888{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000889 register PyObject *v;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000890 register int i, j, n;
891
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000892 if (!PyArg_NoArgs(args))
Guido van Rossum25831651993-05-19 14:50:45 +0000893 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000894 again:
895 n = mp->ma_used;
896 v = PyList_New(n);
Guido van Rossum25831651993-05-19 14:50:45 +0000897 if (v == NULL)
898 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000899 if (n != mp->ma_used) {
900 /* Durnit. The allocations caused the dict to resize.
901 * Just start over, this shouldn't normally happen.
902 */
903 Py_DECREF(v);
904 goto again;
905 }
Guido van Rossum25831651993-05-19 14:50:45 +0000906 for (i = 0, j = 0; i < mp->ma_size; i++) {
907 if (mp->ma_table[i].me_value != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000908 PyObject *value = mp->ma_table[i].me_value;
909 Py_INCREF(value);
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000910 PyList_SET_ITEM(v, j, value);
Guido van Rossum25831651993-05-19 14:50:45 +0000911 j++;
912 }
913 }
914 return v;
915}
916
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000917static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000918dict_items(register dictobject *mp, PyObject *args)
Guido van Rossum25831651993-05-19 14:50:45 +0000919{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000920 register PyObject *v;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000921 register int i, j, n;
922 PyObject *item, *key, *value;
923
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000924 if (!PyArg_NoArgs(args))
Guido van Rossum25831651993-05-19 14:50:45 +0000925 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000926 /* Preallocate the list of tuples, to avoid allocations during
927 * the loop over the items, which could trigger GC, which
928 * could resize the dict. :-(
929 */
930 again:
931 n = mp->ma_used;
932 v = PyList_New(n);
Guido van Rossum25831651993-05-19 14:50:45 +0000933 if (v == NULL)
934 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000935 for (i = 0; i < n; i++) {
936 item = PyTuple_New(2);
937 if (item == NULL) {
938 Py_DECREF(v);
939 return NULL;
940 }
941 PyList_SET_ITEM(v, i, item);
942 }
943 if (n != mp->ma_used) {
944 /* Durnit. The allocations caused the dict to resize.
945 * Just start over, this shouldn't normally happen.
946 */
947 Py_DECREF(v);
948 goto again;
949 }
950 /* Nothing we do below makes any function calls. */
Guido van Rossum25831651993-05-19 14:50:45 +0000951 for (i = 0, j = 0; i < mp->ma_size; i++) {
952 if (mp->ma_table[i].me_value != NULL) {
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000953 key = mp->ma_table[i].me_key;
954 value = mp->ma_table[i].me_value;
955 item = PyList_GET_ITEM(v, j);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000956 Py_INCREF(key);
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000957 PyTuple_SET_ITEM(item, 0, key);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000958 Py_INCREF(value);
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000959 PyTuple_SET_ITEM(item, 1, value);
Guido van Rossum25831651993-05-19 14:50:45 +0000960 j++;
961 }
962 }
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000963 assert(j == n);
Guido van Rossum25831651993-05-19 14:50:45 +0000964 return v;
965}
966
Guido van Rossume3f5b9c1997-05-28 19:15:28 +0000967static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000968dict_update(register dictobject *mp, PyObject *args)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +0000969{
970 register int i;
971 dictobject *other;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000972 dictentry *entry;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +0000973 if (!PyArg_Parse(args, "O!", &PyDict_Type, &other))
974 return NULL;
Jeremy Hylton1fb60882001-01-03 22:34:59 +0000975 if (other == mp || other->ma_used == 0)
976 goto done; /* a.update(a) or a.update({}); nothing to do */
Guido van Rossume3f5b9c1997-05-28 19:15:28 +0000977 /* Do one big resize at the start, rather than incrementally
978 resizing as we insert new items. Expect that there will be
979 no (or few) overlapping keys. */
980 if ((mp->ma_fill + other->ma_used)*3 >= mp->ma_size*2) {
981 if (dictresize(mp, (mp->ma_used + other->ma_used)*3/2) != 0)
982 return NULL;
983 }
984 for (i = 0; i < other->ma_size; i++) {
985 entry = &other->ma_table[i];
986 if (entry->me_value != NULL) {
987 Py_INCREF(entry->me_key);
988 Py_INCREF(entry->me_value);
989 insertdict(mp, entry->me_key, entry->me_hash,
990 entry->me_value);
991 }
992 }
993 done:
994 Py_INCREF(Py_None);
995 return Py_None;
996}
997
998static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000999dict_copy(register dictobject *mp, PyObject *args)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001000{
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001001 if (!PyArg_Parse(args, ""))
1002 return NULL;
1003 return PyDict_Copy((PyObject*)mp);
1004}
1005
1006PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001007PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001008{
1009 register dictobject *mp;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001010 register int i;
1011 dictobject *copy;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001012 dictentry *entry;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001013
1014 if (o == NULL || !PyDict_Check(o)) {
1015 PyErr_BadInternalCall();
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001016 return NULL;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001017 }
1018 mp = (dictobject *)o;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001019 copy = (dictobject *)PyDict_New();
1020 if (copy == NULL)
1021 return NULL;
1022 if (mp->ma_used > 0) {
1023 if (dictresize(copy, mp->ma_used*3/2) != 0)
1024 return NULL;
1025 for (i = 0; i < mp->ma_size; i++) {
1026 entry = &mp->ma_table[i];
1027 if (entry->me_value != NULL) {
1028 Py_INCREF(entry->me_key);
1029 Py_INCREF(entry->me_value);
1030 insertdict(copy, entry->me_key, entry->me_hash,
1031 entry->me_value);
1032 }
1033 }
1034 }
1035 return (PyObject *)copy;
1036}
1037
Guido van Rossum4199fac1993-11-05 10:18:44 +00001038int
Tim Peters1f5871e2000-07-04 17:44:48 +00001039PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00001040{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001041 if (mp == NULL || !PyDict_Check(mp)) {
1042 PyErr_BadInternalCall();
Guido van Rossumb376a4a1993-11-23 17:53:17 +00001043 return 0;
Guido van Rossum4199fac1993-11-05 10:18:44 +00001044 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001045 return ((dictobject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00001046}
1047
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001048PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001049PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001050{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001051 if (mp == NULL || !PyDict_Check(mp)) {
1052 PyErr_BadInternalCall();
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001053 return NULL;
1054 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001055 return dict_keys((dictobject *)mp, (PyObject *)NULL);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001056}
1057
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001058PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001059PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001060{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001061 if (mp == NULL || !PyDict_Check(mp)) {
1062 PyErr_BadInternalCall();
Guido van Rossum25831651993-05-19 14:50:45 +00001063 return NULL;
1064 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001065 return dict_values((dictobject *)mp, (PyObject *)NULL);
Guido van Rossum25831651993-05-19 14:50:45 +00001066}
1067
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001068PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001069PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001070{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001071 if (mp == NULL || !PyDict_Check(mp)) {
1072 PyErr_BadInternalCall();
Guido van Rossum25831651993-05-19 14:50:45 +00001073 return NULL;
1074 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001075 return dict_items((dictobject *)mp, (PyObject *)NULL);
Guido van Rossum25831651993-05-19 14:50:45 +00001076}
1077
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001078/* Subroutine which returns the smallest key in a for which b's value
1079 is different or absent. The value is returned too, through the
Tim Peters95bf9392001-05-10 08:32:44 +00001080 pval argument. Both are NULL if no key in a is found for which b's status
1081 differs. The refcounts on (and only on) non-NULL *pval and function return
1082 values must be decremented by the caller (characterize() increments them
1083 to ensure that mutating comparison and PyDict_GetItem calls can't delete
1084 them before the caller is done looking at them). */
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001085
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001086static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001087characterize(dictobject *a, dictobject *b, PyObject **pval)
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001088{
Tim Peters95bf9392001-05-10 08:32:44 +00001089 PyObject *akey = NULL; /* smallest key in a s.t. a[akey] != b[akey] */
1090 PyObject *aval = NULL; /* a[akey] */
Guido van Rossumb9324202001-01-18 00:39:02 +00001091 int i, cmp;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001092
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001093 for (i = 0; i < a->ma_size; i++) {
Tim Peters95bf9392001-05-10 08:32:44 +00001094 PyObject *thiskey, *thisaval, *thisbval;
1095 if (a->ma_table[i].me_value == NULL)
1096 continue;
1097 thiskey = a->ma_table[i].me_key;
1098 Py_INCREF(thiskey); /* keep alive across compares */
1099 if (akey != NULL) {
1100 cmp = PyObject_RichCompareBool(akey, thiskey, Py_LT);
1101 if (cmp < 0) {
1102 Py_DECREF(thiskey);
1103 goto Fail;
1104 }
1105 if (cmp > 0 ||
1106 i >= a->ma_size ||
1107 a->ma_table[i].me_value == NULL)
1108 {
1109 /* Not the *smallest* a key; or maybe it is
1110 * but the compare shrunk the dict so we can't
1111 * find its associated value anymore; or
1112 * maybe it is but the compare deleted the
1113 * a[thiskey] entry.
1114 */
1115 Py_DECREF(thiskey);
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001116 continue;
Guido van Rossumb9324202001-01-18 00:39:02 +00001117 }
Tim Peters95bf9392001-05-10 08:32:44 +00001118 }
1119
1120 /* Compare a[thiskey] to b[thiskey]; cmp <- true iff equal. */
1121 thisaval = a->ma_table[i].me_value;
1122 assert(thisaval);
1123 Py_INCREF(thisaval); /* keep alive */
1124 thisbval = PyDict_GetItem((PyObject *)b, thiskey);
1125 if (thisbval == NULL)
1126 cmp = 0;
1127 else {
1128 /* both dicts have thiskey: same values? */
1129 cmp = PyObject_RichCompareBool(
1130 thisaval, thisbval, Py_EQ);
1131 if (cmp < 0) {
1132 Py_DECREF(thiskey);
1133 Py_DECREF(thisaval);
1134 goto Fail;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001135 }
1136 }
Tim Peters95bf9392001-05-10 08:32:44 +00001137 if (cmp == 0) {
1138 /* New winner. */
1139 Py_XDECREF(akey);
1140 Py_XDECREF(aval);
1141 akey = thiskey;
1142 aval = thisaval;
1143 }
1144 else {
1145 Py_DECREF(thiskey);
1146 Py_DECREF(thisaval);
1147 }
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001148 }
Tim Peters95bf9392001-05-10 08:32:44 +00001149 *pval = aval;
1150 return akey;
1151
1152Fail:
1153 Py_XDECREF(akey);
1154 Py_XDECREF(aval);
1155 *pval = NULL;
1156 return NULL;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001157}
1158
1159static int
Tim Peters1f5871e2000-07-04 17:44:48 +00001160dict_compare(dictobject *a, dictobject *b)
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001161{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001162 PyObject *adiff, *bdiff, *aval, *bval;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001163 int res;
1164
1165 /* Compare lengths first */
1166 if (a->ma_used < b->ma_used)
1167 return -1; /* a is shorter */
1168 else if (a->ma_used > b->ma_used)
1169 return 1; /* b is shorter */
Tim Peters95bf9392001-05-10 08:32:44 +00001170
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001171 /* Same length -- check all keys */
Tim Peters95bf9392001-05-10 08:32:44 +00001172 bdiff = bval = NULL;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001173 adiff = characterize(a, b, &aval);
Tim Peters95bf9392001-05-10 08:32:44 +00001174 if (adiff == NULL) {
1175 assert(!aval);
Tim Peters3918fb22001-05-10 18:58:31 +00001176 /* Either an error, or a is a subset with the same length so
Tim Peters95bf9392001-05-10 08:32:44 +00001177 * must be equal.
1178 */
1179 res = PyErr_Occurred() ? -1 : 0;
1180 goto Finished;
1181 }
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001182 bdiff = characterize(b, a, &bval);
Tim Peters95bf9392001-05-10 08:32:44 +00001183 if (bdiff == NULL && PyErr_Occurred()) {
1184 assert(!bval);
1185 res = -1;
1186 goto Finished;
1187 }
1188 res = 0;
1189 if (bdiff) {
1190 /* bdiff == NULL "should be" impossible now, but perhaps
1191 * the last comparison done by the characterize() on a had
1192 * the side effect of making the dicts equal!
1193 */
1194 res = PyObject_Compare(adiff, bdiff);
1195 }
1196 if (res == 0 && bval != NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001197 res = PyObject_Compare(aval, bval);
Tim Peters95bf9392001-05-10 08:32:44 +00001198
1199Finished:
1200 Py_XDECREF(adiff);
1201 Py_XDECREF(bdiff);
1202 Py_XDECREF(aval);
1203 Py_XDECREF(bval);
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001204 return res;
1205}
1206
Tim Peterse63415e2001-05-08 04:38:29 +00001207/* Return 1 if dicts equal, 0 if not, -1 if error.
1208 * Gets out as soon as any difference is detected.
1209 * Uses only Py_EQ comparison.
1210 */
1211static int
1212dict_equal(dictobject *a, dictobject *b)
1213{
1214 int i;
1215
1216 if (a->ma_used != b->ma_used)
1217 /* can't be equal if # of entries differ */
1218 return 0;
Tim Peterseb28ef22001-06-02 05:27:19 +00001219
Tim Peterse63415e2001-05-08 04:38:29 +00001220 /* Same # of entries -- check all of 'em. Exit early on any diff. */
1221 for (i = 0; i < a->ma_size; i++) {
1222 PyObject *aval = a->ma_table[i].me_value;
1223 if (aval != NULL) {
1224 int cmp;
1225 PyObject *bval;
1226 PyObject *key = a->ma_table[i].me_key;
1227 /* temporarily bump aval's refcount to ensure it stays
1228 alive until we're done with it */
1229 Py_INCREF(aval);
1230 bval = PyDict_GetItem((PyObject *)b, key);
1231 if (bval == NULL) {
1232 Py_DECREF(aval);
1233 return 0;
1234 }
1235 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
1236 Py_DECREF(aval);
1237 if (cmp <= 0) /* error or not equal */
1238 return cmp;
1239 }
1240 }
1241 return 1;
1242 }
1243
1244static PyObject *
1245dict_richcompare(PyObject *v, PyObject *w, int op)
1246{
1247 int cmp;
1248 PyObject *res;
1249
1250 if (!PyDict_Check(v) || !PyDict_Check(w)) {
1251 res = Py_NotImplemented;
1252 }
1253 else if (op == Py_EQ || op == Py_NE) {
1254 cmp = dict_equal((dictobject *)v, (dictobject *)w);
1255 if (cmp < 0)
1256 return NULL;
1257 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
1258 }
Tim Peters4fa58bf2001-05-10 21:45:19 +00001259 else
1260 res = Py_NotImplemented;
Tim Peterse63415e2001-05-08 04:38:29 +00001261 Py_INCREF(res);
1262 return res;
1263 }
1264
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001265static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001266dict_has_key(register dictobject *mp, PyObject *args)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001267{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001268 PyObject *key;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001269 long hash;
1270 register long ok;
Fred Drake52fccfd2000-02-23 15:47:16 +00001271 if (!PyArg_ParseTuple(args, "O:has_key", &key))
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001272 return NULL;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +00001273#ifdef CACHE_HASH
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001274 if (!PyString_Check(key) ||
1275 (hash = ((PyStringObject *) key)->ob_shash) == -1)
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +00001276#endif
Guido van Rossumca756f21997-01-23 19:39:29 +00001277 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001278 hash = PyObject_Hash(key);
Guido van Rossumca756f21997-01-23 19:39:29 +00001279 if (hash == -1)
1280 return NULL;
1281 }
Tim Petersdea48ec2001-05-22 20:40:22 +00001282 ok = (mp->ma_lookup)(mp, key, hash)->me_value != NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001283 return PyInt_FromLong(ok);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001284}
1285
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001286static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001287dict_get(register dictobject *mp, PyObject *args)
Barry Warsawc38c5da1997-10-06 17:49:20 +00001288{
1289 PyObject *key;
Barry Warsaw320ac331997-10-20 17:26:25 +00001290 PyObject *failobj = Py_None;
Barry Warsawc38c5da1997-10-06 17:49:20 +00001291 PyObject *val = NULL;
1292 long hash;
1293
Fred Drake52fccfd2000-02-23 15:47:16 +00001294 if (!PyArg_ParseTuple(args, "O|O:get", &key, &failobj))
Barry Warsawc38c5da1997-10-06 17:49:20 +00001295 return NULL;
1296
Barry Warsawc38c5da1997-10-06 17:49:20 +00001297#ifdef CACHE_HASH
1298 if (!PyString_Check(key) ||
1299 (hash = ((PyStringObject *) key)->ob_shash) == -1)
1300#endif
1301 {
1302 hash = PyObject_Hash(key);
1303 if (hash == -1)
1304 return NULL;
1305 }
Fred Drake1bff34a2000-08-31 19:31:38 +00001306 val = (mp->ma_lookup)(mp, key, hash)->me_value;
Barry Warsaw320ac331997-10-20 17:26:25 +00001307
Barry Warsawc38c5da1997-10-06 17:49:20 +00001308 if (val == NULL)
1309 val = failobj;
1310 Py_INCREF(val);
1311 return val;
1312}
1313
1314
1315static PyObject *
Guido van Rossum164452c2000-08-08 16:12:54 +00001316dict_setdefault(register dictobject *mp, PyObject *args)
1317{
1318 PyObject *key;
1319 PyObject *failobj = Py_None;
1320 PyObject *val = NULL;
1321 long hash;
1322
1323 if (!PyArg_ParseTuple(args, "O|O:setdefault", &key, &failobj))
1324 return NULL;
Guido van Rossum164452c2000-08-08 16:12:54 +00001325
1326#ifdef CACHE_HASH
1327 if (!PyString_Check(key) ||
1328 (hash = ((PyStringObject *) key)->ob_shash) == -1)
1329#endif
1330 {
1331 hash = PyObject_Hash(key);
1332 if (hash == -1)
1333 return NULL;
1334 }
Fred Drake1bff34a2000-08-31 19:31:38 +00001335 val = (mp->ma_lookup)(mp, key, hash)->me_value;
Guido van Rossum164452c2000-08-08 16:12:54 +00001336 if (val == NULL) {
1337 val = failobj;
1338 if (PyDict_SetItem((PyObject*)mp, key, failobj))
1339 val = NULL;
1340 }
1341 Py_XINCREF(val);
1342 return val;
1343}
1344
1345
1346static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001347dict_clear(register dictobject *mp, PyObject *args)
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00001348{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001349 if (!PyArg_NoArgs(args))
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00001350 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001351 PyDict_Clear((PyObject *)mp);
1352 Py_INCREF(Py_None);
1353 return Py_None;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00001354}
1355
Guido van Rossumba6ab842000-12-12 22:02:18 +00001356static PyObject *
1357dict_popitem(dictobject *mp, PyObject *args)
1358{
1359 int i = 0;
1360 dictentry *ep;
1361 PyObject *res;
1362
1363 if (!PyArg_NoArgs(args))
1364 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001365 /* Allocate the result tuple first. Believe it or not,
1366 * this allocation could trigger a garbage collection which
1367 * could resize the dict, which would invalidate the pointer
1368 * (ep) into the dict calculated below.
1369 * So we have to do this first.
1370 */
1371 res = PyTuple_New(2);
1372 if (res == NULL)
1373 return NULL;
Guido van Rossume04eaec2001-04-16 00:02:32 +00001374 if (mp->ma_used == 0) {
1375 Py_DECREF(res);
1376 PyErr_SetString(PyExc_KeyError,
1377 "popitem(): dictionary is empty");
1378 return NULL;
1379 }
Guido van Rossumba6ab842000-12-12 22:02:18 +00001380 /* Set ep to "the first" dict entry with a value. We abuse the hash
1381 * field of slot 0 to hold a search finger:
1382 * If slot 0 has a value, use slot 0.
1383 * Else slot 0 is being used to hold a search finger,
1384 * and we use its hash value as the first index to look.
1385 */
1386 ep = &mp->ma_table[0];
1387 if (ep->me_value == NULL) {
1388 i = (int)ep->me_hash;
Tim Petersdea48ec2001-05-22 20:40:22 +00001389 /* The hash field may be a real hash value, or it may be a
1390 * legit search finger, or it may be a once-legit search
1391 * finger that's out of bounds now because it wrapped around
1392 * or the table shrunk -- simply make sure it's in bounds now.
Guido van Rossumba6ab842000-12-12 22:02:18 +00001393 */
1394 if (i >= mp->ma_size || i < 1)
1395 i = 1; /* skip slot 0 */
1396 while ((ep = &mp->ma_table[i])->me_value == NULL) {
1397 i++;
1398 if (i >= mp->ma_size)
1399 i = 1;
1400 }
1401 }
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001402 PyTuple_SET_ITEM(res, 0, ep->me_key);
1403 PyTuple_SET_ITEM(res, 1, ep->me_value);
1404 Py_INCREF(dummy);
1405 ep->me_key = dummy;
1406 ep->me_value = NULL;
1407 mp->ma_used--;
1408 assert(mp->ma_table[0].me_value == NULL);
1409 mp->ma_table[0].me_hash = i + 1; /* next place to start */
Guido van Rossumba6ab842000-12-12 22:02:18 +00001410 return res;
1411}
1412
Jeremy Hylton8caad492000-06-23 14:18:11 +00001413static int
1414dict_traverse(PyObject *op, visitproc visit, void *arg)
1415{
1416 int i = 0, err;
1417 PyObject *pk;
1418 PyObject *pv;
1419
1420 while (PyDict_Next(op, &i, &pk, &pv)) {
1421 err = visit(pk, arg);
1422 if (err)
1423 return err;
1424 err = visit(pv, arg);
1425 if (err)
1426 return err;
1427 }
1428 return 0;
1429}
1430
1431static int
1432dict_tp_clear(PyObject *op)
1433{
1434 PyDict_Clear(op);
1435 return 0;
1436}
1437
Tim Petersf7f88b12000-12-13 23:18:45 +00001438
Guido van Rossum09e563a2001-05-01 12:10:21 +00001439staticforward PyObject *dictiter_new(dictobject *, binaryfunc);
1440
1441static PyObject *
1442select_key(PyObject *key, PyObject *value)
1443{
1444 Py_INCREF(key);
1445 return key;
1446}
1447
1448static PyObject *
1449select_value(PyObject *key, PyObject *value)
1450{
1451 Py_INCREF(value);
1452 return value;
1453}
1454
1455static PyObject *
1456select_item(PyObject *key, PyObject *value)
1457{
1458 PyObject *res = PyTuple_New(2);
1459
1460 if (res != NULL) {
1461 Py_INCREF(key);
1462 Py_INCREF(value);
1463 PyTuple_SET_ITEM(res, 0, key);
1464 PyTuple_SET_ITEM(res, 1, value);
1465 }
1466 return res;
1467}
1468
1469static PyObject *
1470dict_iterkeys(dictobject *dict, PyObject *args)
1471{
1472 if (!PyArg_ParseTuple(args, ""))
1473 return NULL;
1474 return dictiter_new(dict, select_key);
1475}
1476
1477static PyObject *
1478dict_itervalues(dictobject *dict, PyObject *args)
1479{
1480 if (!PyArg_ParseTuple(args, ""))
1481 return NULL;
1482 return dictiter_new(dict, select_value);
1483}
1484
1485static PyObject *
1486dict_iteritems(dictobject *dict, PyObject *args)
1487{
1488 if (!PyArg_ParseTuple(args, ""))
1489 return NULL;
1490 return dictiter_new(dict, select_item);
1491}
1492
1493
Tim Petersf7f88b12000-12-13 23:18:45 +00001494static char has_key__doc__[] =
1495"D.has_key(k) -> 1 if D has a key k, else 0";
1496
1497static char get__doc__[] =
1498"D.get(k[,d]) -> D[k] if D.has_key(k), else d. d defaults to None.";
1499
1500static char setdefault_doc__[] =
1501"D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if not D.has_key(k)";
1502
1503static char popitem__doc__[] =
1504"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
15052-tuple; but raise KeyError if D is empty";
1506
1507static char keys__doc__[] =
1508"D.keys() -> list of D's keys";
1509
1510static char items__doc__[] =
1511"D.items() -> list of D's (key, value) pairs, as 2-tuples";
1512
1513static char values__doc__[] =
1514"D.values() -> list of D's values";
1515
1516static char update__doc__[] =
1517"D.update(E) -> None. Update D from E: for k in E.keys(): D[k] = E[k]";
1518
1519static char clear__doc__[] =
1520"D.clear() -> None. Remove all items from D.";
1521
1522static char copy__doc__[] =
1523"D.copy() -> a shallow copy of D";
1524
Guido van Rossum09e563a2001-05-01 12:10:21 +00001525static char iterkeys__doc__[] =
1526"D.iterkeys() -> an iterator over the keys of D";
1527
1528static char itervalues__doc__[] =
1529"D.itervalues() -> an iterator over the values of D";
1530
1531static char iteritems__doc__[] =
1532"D.iteritems() -> an iterator over the (key, value) items of D";
1533
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001534static PyMethodDef mapp_methods[] = {
Tim Petersf7f88b12000-12-13 23:18:45 +00001535 {"has_key", (PyCFunction)dict_has_key, METH_VARARGS,
1536 has_key__doc__},
1537 {"get", (PyCFunction)dict_get, METH_VARARGS,
1538 get__doc__},
1539 {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS,
1540 setdefault_doc__},
1541 {"popitem", (PyCFunction)dict_popitem, METH_OLDARGS,
1542 popitem__doc__},
1543 {"keys", (PyCFunction)dict_keys, METH_OLDARGS,
1544 keys__doc__},
1545 {"items", (PyCFunction)dict_items, METH_OLDARGS,
1546 items__doc__},
1547 {"values", (PyCFunction)dict_values, METH_OLDARGS,
1548 values__doc__},
1549 {"update", (PyCFunction)dict_update, METH_OLDARGS,
1550 update__doc__},
1551 {"clear", (PyCFunction)dict_clear, METH_OLDARGS,
1552 clear__doc__},
1553 {"copy", (PyCFunction)dict_copy, METH_OLDARGS,
1554 copy__doc__},
Guido van Rossum09e563a2001-05-01 12:10:21 +00001555 {"iterkeys", (PyCFunction)dict_iterkeys, METH_VARARGS,
1556 iterkeys__doc__},
1557 {"itervalues", (PyCFunction)dict_itervalues, METH_VARARGS,
1558 itervalues__doc__},
1559 {"iteritems", (PyCFunction)dict_iteritems, METH_VARARGS,
1560 iteritems__doc__},
Tim Petersf7f88b12000-12-13 23:18:45 +00001561 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001562};
1563
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001564static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001565dict_getattr(dictobject *mp, char *name)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001566{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001567 return Py_FindMethod(mapp_methods, (PyObject *)mp, name);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001568}
1569
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001570static int
1571dict_contains(dictobject *mp, PyObject *key)
1572{
1573 long hash;
1574
1575#ifdef CACHE_HASH
1576 if (!PyString_Check(key) ||
1577 (hash = ((PyStringObject *) key)->ob_shash) == -1)
1578#endif
1579 {
1580 hash = PyObject_Hash(key);
1581 if (hash == -1)
1582 return -1;
1583 }
Tim Petersdea48ec2001-05-22 20:40:22 +00001584 return (mp->ma_lookup)(mp, key, hash)->me_value != NULL;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001585}
1586
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001587/* Hack to implement "key in dict" */
1588static PySequenceMethods dict_as_sequence = {
1589 0, /* sq_length */
1590 0, /* sq_concat */
1591 0, /* sq_repeat */
1592 0, /* sq_item */
1593 0, /* sq_slice */
1594 0, /* sq_ass_item */
1595 0, /* sq_ass_slice */
1596 (objobjproc)dict_contains, /* sq_contains */
1597 0, /* sq_inplace_concat */
1598 0, /* sq_inplace_repeat */
1599};
1600
Guido van Rossum09e563a2001-05-01 12:10:21 +00001601static PyObject *
1602dict_iter(dictobject *dict)
1603{
1604 return dictiter_new(dict, select_key);
1605}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001606
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001607PyTypeObject PyDict_Type = {
1608 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001609 0,
Guido van Rossum9bfef441993-03-29 10:43:31 +00001610 "dictionary",
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001611 sizeof(dictobject) + PyGC_HEAD_SIZE,
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001612 0,
Guido van Rossumb9324202001-01-18 00:39:02 +00001613 (destructor)dict_dealloc, /* tp_dealloc */
1614 (printfunc)dict_print, /* tp_print */
1615 (getattrfunc)dict_getattr, /* tp_getattr */
1616 0, /* tp_setattr */
Tim Peters4fa58bf2001-05-10 21:45:19 +00001617 (cmpfunc)dict_compare, /* tp_compare */
Guido van Rossumb9324202001-01-18 00:39:02 +00001618 (reprfunc)dict_repr, /* tp_repr */
1619 0, /* tp_as_number */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001620 &dict_as_sequence, /* tp_as_sequence */
Guido van Rossumb9324202001-01-18 00:39:02 +00001621 &dict_as_mapping, /* tp_as_mapping */
1622 0, /* tp_hash */
1623 0, /* tp_call */
1624 0, /* tp_str */
1625 0, /* tp_getattro */
1626 0, /* tp_setattro */
1627 0, /* tp_as_buffer */
1628 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /* tp_flags */
1629 0, /* tp_doc */
1630 (traverseproc)dict_traverse, /* tp_traverse */
1631 (inquiry)dict_tp_clear, /* tp_clear */
Tim Peterse63415e2001-05-08 04:38:29 +00001632 dict_richcompare, /* tp_richcompare */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001633 0, /* tp_weaklistoffset */
Guido van Rossum09e563a2001-05-01 12:10:21 +00001634 (getiterfunc)dict_iter, /* tp_iter */
Guido van Rossum213c7a62001-04-23 14:08:49 +00001635 0, /* tp_iternext */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001636};
1637
Guido van Rossum3cca2451997-05-16 14:23:33 +00001638/* For backward compatibility with old dictionary interface */
1639
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001640PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001641PyDict_GetItemString(PyObject *v, char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001642{
Guido van Rossum3cca2451997-05-16 14:23:33 +00001643 PyObject *kv, *rv;
1644 kv = PyString_FromString(key);
1645 if (kv == NULL)
1646 return NULL;
Guido van Rossum3cca2451997-05-16 14:23:33 +00001647 rv = PyDict_GetItem(v, kv);
1648 Py_DECREF(kv);
1649 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001650}
1651
1652int
Tim Peters1f5871e2000-07-04 17:44:48 +00001653PyDict_SetItemString(PyObject *v, char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001654{
Guido van Rossum3cca2451997-05-16 14:23:33 +00001655 PyObject *kv;
1656 int err;
1657 kv = PyString_FromString(key);
1658 if (kv == NULL)
Guido van Rossum037b2201997-05-20 18:35:19 +00001659 return -1;
Guido van Rossum4f3bf1e1997-09-29 23:31:11 +00001660 PyString_InternInPlace(&kv); /* XXX Should we really? */
Guido van Rossum3cca2451997-05-16 14:23:33 +00001661 err = PyDict_SetItem(v, kv, item);
1662 Py_DECREF(kv);
1663 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001664}
1665
1666int
Tim Peters1f5871e2000-07-04 17:44:48 +00001667PyDict_DelItemString(PyObject *v, char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001668{
Guido van Rossum3cca2451997-05-16 14:23:33 +00001669 PyObject *kv;
1670 int err;
1671 kv = PyString_FromString(key);
1672 if (kv == NULL)
Guido van Rossum037b2201997-05-20 18:35:19 +00001673 return -1;
Guido van Rossum3cca2451997-05-16 14:23:33 +00001674 err = PyDict_DelItem(v, kv);
1675 Py_DECREF(kv);
1676 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001677}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001678
1679/* Dictionary iterator type */
1680
1681extern PyTypeObject PyDictIter_Type; /* Forward */
1682
1683typedef struct {
1684 PyObject_HEAD
1685 dictobject *di_dict;
Guido van Rossumb1f35bf2001-05-02 15:13:44 +00001686 int di_used;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001687 int di_pos;
Guido van Rossum09e563a2001-05-01 12:10:21 +00001688 binaryfunc di_select;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001689} dictiterobject;
1690
1691static PyObject *
Guido van Rossum09e563a2001-05-01 12:10:21 +00001692dictiter_new(dictobject *dict, binaryfunc select)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001693{
1694 dictiterobject *di;
1695 di = PyObject_NEW(dictiterobject, &PyDictIter_Type);
1696 if (di == NULL)
1697 return NULL;
1698 Py_INCREF(dict);
1699 di->di_dict = dict;
Guido van Rossumb1f35bf2001-05-02 15:13:44 +00001700 di->di_used = dict->ma_used;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001701 di->di_pos = 0;
Guido van Rossum09e563a2001-05-01 12:10:21 +00001702 di->di_select = select;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001703 return (PyObject *)di;
1704}
1705
1706static void
1707dictiter_dealloc(dictiterobject *di)
1708{
1709 Py_DECREF(di->di_dict);
1710 PyObject_DEL(di);
1711}
1712
1713static PyObject *
1714dictiter_next(dictiterobject *di, PyObject *args)
1715{
Guido van Rossum09e563a2001-05-01 12:10:21 +00001716 PyObject *key, *value;
Guido van Rossum213c7a62001-04-23 14:08:49 +00001717
Guido van Rossumb1f35bf2001-05-02 15:13:44 +00001718 if (di->di_used != di->di_dict->ma_used) {
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001719 PyErr_SetString(PyExc_RuntimeError,
1720 "dictionary changed size during iteration");
1721 return NULL;
1722 }
Guido van Rossum09e563a2001-05-01 12:10:21 +00001723 if (PyDict_Next((PyObject *)(di->di_dict), &di->di_pos, &key, &value)) {
1724 return (*di->di_select)(key, value);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001725 }
1726 PyErr_SetObject(PyExc_StopIteration, Py_None);
1727 return NULL;
1728}
1729
1730static PyObject *
1731dictiter_getiter(PyObject *it)
1732{
1733 Py_INCREF(it);
1734 return it;
1735}
1736
1737static PyMethodDef dictiter_methods[] = {
1738 {"next", (PyCFunction)dictiter_next, METH_VARARGS,
1739 "it.next() -- get the next value, or raise StopIteration"},
1740 {NULL, NULL} /* sentinel */
1741};
1742
1743static PyObject *
Guido van Rossum213c7a62001-04-23 14:08:49 +00001744dictiter_getattr(dictiterobject *di, char *name)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001745{
Guido van Rossum213c7a62001-04-23 14:08:49 +00001746 return Py_FindMethod(dictiter_methods, (PyObject *)di, name);
1747}
1748
1749static PyObject *dictiter_iternext(dictiterobject *di)
1750{
Guido van Rossum09e563a2001-05-01 12:10:21 +00001751 PyObject *key, *value;
Guido van Rossum213c7a62001-04-23 14:08:49 +00001752
Guido van Rossumb1f35bf2001-05-02 15:13:44 +00001753 if (di->di_used != di->di_dict->ma_used) {
Guido van Rossum213c7a62001-04-23 14:08:49 +00001754 PyErr_SetString(PyExc_RuntimeError,
1755 "dictionary changed size during iteration");
1756 return NULL;
1757 }
Guido van Rossum09e563a2001-05-01 12:10:21 +00001758 if (PyDict_Next((PyObject *)(di->di_dict), &di->di_pos, &key, &value)) {
1759 return (*di->di_select)(key, value);
Guido van Rossum213c7a62001-04-23 14:08:49 +00001760 }
1761 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001762}
1763
1764PyTypeObject PyDictIter_Type = {
1765 PyObject_HEAD_INIT(&PyType_Type)
1766 0, /* ob_size */
1767 "dictionary-iterator", /* tp_name */
1768 sizeof(dictiterobject), /* tp_basicsize */
1769 0, /* tp_itemsize */
1770 /* methods */
1771 (destructor)dictiter_dealloc, /* tp_dealloc */
1772 0, /* tp_print */
1773 (getattrfunc)dictiter_getattr, /* tp_getattr */
1774 0, /* tp_setattr */
1775 0, /* tp_compare */
1776 0, /* tp_repr */
1777 0, /* tp_as_number */
1778 0, /* tp_as_sequence */
1779 0, /* tp_as_mapping */
1780 0, /* tp_hash */
1781 0, /* tp_call */
1782 0, /* tp_str */
1783 0, /* tp_getattro */
1784 0, /* tp_setattro */
1785 0, /* tp_as_buffer */
1786 Py_TPFLAGS_DEFAULT, /* tp_flags */
1787 0, /* tp_doc */
1788 0, /* tp_traverse */
1789 0, /* tp_clear */
1790 0, /* tp_richcompare */
1791 0, /* tp_weaklistoffset */
1792 (getiterfunc)dictiter_getiter, /* tp_iter */
Guido van Rossum213c7a62001-04-23 14:08:49 +00001793 (iternextfunc)dictiter_iternext, /* tp_iternext */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001794};