blob: 21cc6c6ce14b76e063221bc59825be3b2378e3ed [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 */
Tim Petersafb6ae82001-06-04 21:00:21 +0000165
166 /* The table contains ma_mask + 1 slots, and that's a power of 2.
167 * We store the mask instead of the size because the mask is more
168 * frequently needed.
169 */
170 int ma_mask;
171
Tim Petersdea48ec2001-05-22 20:40:22 +0000172 /* ma_table points to ma_smalltable for small tables, else to
173 * additional malloc'ed memory. ma_table is never NULL! This rule
174 * saves repeated runtime null-tests in the workhorse getitem and
175 * setitem calls.
176 */
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000177 dictentry *ma_table;
Fred Drake1bff34a2000-08-31 19:31:38 +0000178 dictentry *(*ma_lookup)(dictobject *mp, PyObject *key, long hash);
Tim Petersdea48ec2001-05-22 20:40:22 +0000179 dictentry ma_smalltable[MINSIZE];
Fred Drake1bff34a2000-08-31 19:31:38 +0000180};
181
182/* forward declarations */
183static dictentry *
184lookdict_string(dictobject *mp, PyObject *key, long hash);
185
186#ifdef SHOW_CONVERSION_COUNTS
187static long created = 0L;
188static long converted = 0L;
189
190static void
191show_counts(void)
192{
193 fprintf(stderr, "created %ld string dicts\n", created);
194 fprintf(stderr, "converted %ld to normal dicts\n", converted);
195 fprintf(stderr, "%.2f%% conversion rate\n", (100.0*converted)/created);
196}
197#endif
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000198
Tim Petersdea48ec2001-05-22 20:40:22 +0000199/* Set dictobject* mp to empty but w/ MINSIZE slots, using ma_smalltable. */
200#define empty_to_minsize(mp) do { \
201 memset((mp)->ma_smalltable, 0, sizeof((mp)->ma_smalltable)); \
202 (mp)->ma_table = (mp)->ma_smalltable; \
Tim Petersafb6ae82001-06-04 21:00:21 +0000203 (mp)->ma_mask = MINSIZE - 1; \
Tim Petersdea48ec2001-05-22 20:40:22 +0000204 (mp)->ma_used = (mp)->ma_fill = 0; \
Tim Petersdea48ec2001-05-22 20:40:22 +0000205 } while(0)
206
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000207PyObject *
Thomas Wouters78890102000-07-22 19:25:51 +0000208PyDict_New(void)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000209{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000210 register dictobject *mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000211 if (dummy == NULL) { /* Auto-initialize dummy */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000212 dummy = PyString_FromString("<dummy key>");
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000213 if (dummy == NULL)
214 return NULL;
Fred Drake1bff34a2000-08-31 19:31:38 +0000215#ifdef SHOW_CONVERSION_COUNTS
216 Py_AtExit(show_counts);
217#endif
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000218 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000219 mp = PyObject_NEW(dictobject, &PyDict_Type);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000220 if (mp == NULL)
221 return NULL;
Tim Petersdea48ec2001-05-22 20:40:22 +0000222 empty_to_minsize(mp);
Fred Drake1bff34a2000-08-31 19:31:38 +0000223 mp->ma_lookup = lookdict_string;
224#ifdef SHOW_CONVERSION_COUNTS
225 ++created;
226#endif
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000227 PyObject_GC_Init(mp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000228 return (PyObject *)mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000229}
230
231/*
232The basic lookup function used by all operations.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000233This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000234Open addressing is preferred over chaining since the link overhead for
235chaining would be substantial (100% with typical malloc overhead).
236
Tim Peterseb28ef22001-06-02 05:27:19 +0000237The initial probe index is computed as hash mod the table size. Subsequent
238probe indices are computed as explained earlier.
Guido van Rossum2bc13791999-03-24 19:06:42 +0000239
240All arithmetic on hash should ignore overflow.
Guido van Rossum16e93a81997-01-28 00:00:11 +0000241
Tim Peterseb28ef22001-06-02 05:27:19 +0000242(The details in this version are due to Tim Peters, building on many past
243contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
244Christian Tismer).
Fred Drake1bff34a2000-08-31 19:31:38 +0000245
246This function must never return NULL; failures are indicated by returning
247a dictentry* for which the me_value field is NULL. Exceptions are never
248reported by this function, and outstanding exceptions are maintained.
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000249*/
Tim Peterseb28ef22001-06-02 05:27:19 +0000250
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000251static dictentry *
Tim Peters1f5871e2000-07-04 17:44:48 +0000252lookdict(dictobject *mp, PyObject *key, register long hash)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000253{
Guido van Rossum16e93a81997-01-28 00:00:11 +0000254 register int i;
Tim Peterseb28ef22001-06-02 05:27:19 +0000255 register unsigned int perturb;
Guido van Rossumfd7a0b81997-08-18 21:52:47 +0000256 register dictentry *freeslot;
Tim Petersafb6ae82001-06-04 21:00:21 +0000257 register unsigned int mask = mp->ma_mask;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000258 dictentry *ep0 = mp->ma_table;
259 register dictentry *ep;
Tim Peters7b5d0af2001-06-03 04:14:43 +0000260 register int restore_error;
261 register int checked_error;
Fred Drakec88b99c2000-08-31 19:04:07 +0000262 register int cmp;
263 PyObject *err_type, *err_value, *err_tb;
Tim Peters453163d2001-06-03 04:54:32 +0000264 PyObject *startkey;
Tim Peterseb28ef22001-06-02 05:27:19 +0000265
Tim Peters2f228e72001-05-13 00:19:31 +0000266 i = hash & mask;
Guido van Rossumefb46091997-01-29 15:53:56 +0000267 ep = &ep0[i];
Guido van Rossumc1c7b1a1998-10-06 16:01:14 +0000268 if (ep->me_key == NULL || ep->me_key == key)
Guido van Rossum7d181591997-01-16 21:06:45 +0000269 return ep;
Tim Peters7b5d0af2001-06-03 04:14:43 +0000270
271 restore_error = checked_error = 0;
Guido van Rossum16e93a81997-01-28 00:00:11 +0000272 if (ep->me_key == dummy)
Guido van Rossum7d181591997-01-16 21:06:45 +0000273 freeslot = ep;
Guido van Rossumfd7a0b81997-08-18 21:52:47 +0000274 else {
Fred Drakec88b99c2000-08-31 19:04:07 +0000275 if (ep->me_hash == hash) {
276 /* error can't have been checked yet */
277 checked_error = 1;
278 if (PyErr_Occurred()) {
279 restore_error = 1;
280 PyErr_Fetch(&err_type, &err_value, &err_tb);
281 }
Tim Peters453163d2001-06-03 04:54:32 +0000282 startkey = ep->me_key;
283 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
Tim Peters7b5d0af2001-06-03 04:14:43 +0000284 if (cmp < 0)
Guido van Rossumb9324202001-01-18 00:39:02 +0000285 PyErr_Clear();
Tim Peters453163d2001-06-03 04:54:32 +0000286 if (ep0 == mp->ma_table && ep->me_key == startkey) {
287 if (cmp > 0)
288 goto Done;
289 }
290 else {
291 /* The compare did major nasty stuff to the
292 * dict: start over.
293 * XXX A clever adversary could prevent this
294 * XXX from terminating.
295 */
296 ep = lookdict(mp, key, hash);
297 goto Done;
298 }
Guido van Rossumfd7a0b81997-08-18 21:52:47 +0000299 }
300 freeslot = NULL;
Guido van Rossum2a61e741997-01-18 07:55:05 +0000301 }
Tim Peters15d49292001-05-27 07:39:22 +0000302
Tim Peters342c65e2001-05-13 06:43:53 +0000303 /* In the loop, me_key == dummy is by far (factor of 100s) the
304 least likely outcome, so test for that last. */
Tim Peterseb28ef22001-06-02 05:27:19 +0000305 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
306 i = (i << 2) + i + perturb + 1;
307 ep = &ep0[i & mask];
Guido van Rossum16e93a81997-01-28 00:00:11 +0000308 if (ep->me_key == NULL) {
Tim Peters7b5d0af2001-06-03 04:14:43 +0000309 if (freeslot != NULL)
310 ep = freeslot;
311 break;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000312 }
Tim Peters7b5d0af2001-06-03 04:14:43 +0000313 if (ep->me_key == key)
314 break;
315 if (ep->me_hash == hash && ep->me_key != dummy) {
Fred Drakec88b99c2000-08-31 19:04:07 +0000316 if (!checked_error) {
317 checked_error = 1;
318 if (PyErr_Occurred()) {
319 restore_error = 1;
320 PyErr_Fetch(&err_type, &err_value,
321 &err_tb);
322 }
323 }
Tim Peters453163d2001-06-03 04:54:32 +0000324 startkey = ep->me_key;
325 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
Tim Peters7b5d0af2001-06-03 04:14:43 +0000326 if (cmp < 0)
Guido van Rossumb9324202001-01-18 00:39:02 +0000327 PyErr_Clear();
Tim Peters453163d2001-06-03 04:54:32 +0000328 if (ep0 == mp->ma_table && ep->me_key == startkey) {
329 if (cmp > 0)
330 break;
331 }
332 else {
333 /* The compare did major nasty stuff to the
334 * dict: start over.
335 * XXX A clever adversary could prevent this
336 * XXX from terminating.
337 */
338 ep = lookdict(mp, key, hash);
339 break;
340 }
Guido van Rossum16e93a81997-01-28 00:00:11 +0000341 }
Tim Peters342c65e2001-05-13 06:43:53 +0000342 else if (ep->me_key == dummy && freeslot == NULL)
343 freeslot = ep;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000344 }
Tim Peters7b5d0af2001-06-03 04:14:43 +0000345
346Done:
347 if (restore_error)
348 PyErr_Restore(err_type, err_value, err_tb);
349 return ep;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000350}
351
352/*
Fred Drake1bff34a2000-08-31 19:31:38 +0000353 * Hacked up version of lookdict which can assume keys are always strings;
354 * this assumption allows testing for errors during PyObject_Compare() to
355 * be dropped; string-string comparisons never raise exceptions. This also
356 * means we don't need to go through PyObject_Compare(); we can always use
Martin v. Löwiscd353062001-05-24 16:56:35 +0000357 * _PyString_Eq directly.
Fred Drake1bff34a2000-08-31 19:31:38 +0000358 *
359 * This really only becomes meaningful if proper error handling in lookdict()
360 * is too expensive.
361 */
362static dictentry *
363lookdict_string(dictobject *mp, PyObject *key, register long hash)
364{
365 register int i;
Tim Peterseb28ef22001-06-02 05:27:19 +0000366 register unsigned int perturb;
Fred Drake1bff34a2000-08-31 19:31:38 +0000367 register dictentry *freeslot;
Tim Petersafb6ae82001-06-04 21:00:21 +0000368 register unsigned int mask = mp->ma_mask;
Fred Drake1bff34a2000-08-31 19:31:38 +0000369 dictentry *ep0 = mp->ma_table;
370 register dictentry *ep;
Fred Drake1bff34a2000-08-31 19:31:38 +0000371
372 /* make sure this function doesn't have to handle non-string keys */
373 if (!PyString_Check(key)) {
374#ifdef SHOW_CONVERSION_COUNTS
375 ++converted;
376#endif
377 mp->ma_lookup = lookdict;
378 return lookdict(mp, key, hash);
379 }
Tim Peters2f228e72001-05-13 00:19:31 +0000380 i = hash & mask;
Fred Drake1bff34a2000-08-31 19:31:38 +0000381 ep = &ep0[i];
382 if (ep->me_key == NULL || ep->me_key == key)
383 return ep;
384 if (ep->me_key == dummy)
385 freeslot = ep;
386 else {
387 if (ep->me_hash == hash
Martin v. Löwiscd353062001-05-24 16:56:35 +0000388 && _PyString_Eq(ep->me_key, key)) {
Fred Drake1bff34a2000-08-31 19:31:38 +0000389 return ep;
390 }
391 freeslot = NULL;
392 }
Tim Peters15d49292001-05-27 07:39:22 +0000393
Tim Peters342c65e2001-05-13 06:43:53 +0000394 /* In the loop, me_key == dummy is by far (factor of 100s) the
395 least likely outcome, so test for that last. */
Tim Peterseb28ef22001-06-02 05:27:19 +0000396 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
397 i = (i << 2) + i + perturb + 1;
398 ep = &ep0[i & mask];
Tim Peters342c65e2001-05-13 06:43:53 +0000399 if (ep->me_key == NULL)
400 return freeslot == NULL ? ep : freeslot;
401 if (ep->me_key == key
402 || (ep->me_hash == hash
403 && ep->me_key != dummy
Martin v. Löwiscd353062001-05-24 16:56:35 +0000404 && _PyString_Eq(ep->me_key, key)))
Fred Drake1bff34a2000-08-31 19:31:38 +0000405 return ep;
Tim Petersdea48ec2001-05-22 20:40:22 +0000406 if (ep->me_key == dummy && freeslot == NULL)
Tim Peters342c65e2001-05-13 06:43:53 +0000407 freeslot = ep;
Fred Drake1bff34a2000-08-31 19:31:38 +0000408 }
409}
410
411/*
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000412Internal routine to insert a new item into the table.
413Used both by the internal resize routine and by the public insert routine.
414Eats a reference to key and one to value.
415*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000416static void
Tim Peters1f5871e2000-07-04 17:44:48 +0000417insertdict(register dictobject *mp, PyObject *key, long hash, PyObject *value)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000418{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000419 PyObject *old_value;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000420 register dictentry *ep;
Fred Drake1bff34a2000-08-31 19:31:38 +0000421 ep = (mp->ma_lookup)(mp, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000422 if (ep->me_value != NULL) {
Guido van Rossumd7047b31995-01-02 19:07:15 +0000423 old_value = ep->me_value;
424 ep->me_value = value;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000425 Py_DECREF(old_value); /* which **CAN** re-enter */
426 Py_DECREF(key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000427 }
428 else {
429 if (ep->me_key == NULL)
430 mp->ma_fill++;
431 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000432 Py_DECREF(ep->me_key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000433 ep->me_key = key;
434 ep->me_hash = hash;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000435 ep->me_value = value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000436 mp->ma_used++;
437 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000438}
439
440/*
441Restructure the table by allocating a new table and reinserting all
442items again. When entries have been deleted, the new table may
443actually be smaller than the old one.
444*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000445static int
Tim Peters1f5871e2000-07-04 17:44:48 +0000446dictresize(dictobject *mp, int minused)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000447{
Tim Peterseb28ef22001-06-02 05:27:19 +0000448 int newsize;
Tim Peters0c6010b2001-05-23 23:33:57 +0000449 dictentry *oldtable, *newtable, *ep;
450 int i;
451 int is_oldtable_malloced;
452 dictentry small_copy[MINSIZE];
Tim Peters91a364d2001-05-19 07:04:38 +0000453
454 assert(minused >= 0);
Tim Peters0c6010b2001-05-23 23:33:57 +0000455
Tim Peterseb28ef22001-06-02 05:27:19 +0000456 /* Find the smallest table size > minused. */
457 for (newsize = MINSIZE;
458 newsize <= minused && newsize > 0;
459 newsize <<= 1)
460 ;
461 if (newsize <= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000462 PyErr_NoMemory();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000463 return -1;
464 }
Tim Peters0c6010b2001-05-23 23:33:57 +0000465
466 /* Get space for a new table. */
467 oldtable = mp->ma_table;
468 assert(oldtable != NULL);
469 is_oldtable_malloced = oldtable != mp->ma_smalltable;
470
Tim Petersdea48ec2001-05-22 20:40:22 +0000471 if (newsize == MINSIZE) {
Tim Petersf8a548c2001-05-24 16:26:40 +0000472 /* A large table is shrinking, or we can't get any smaller. */
Tim Petersdea48ec2001-05-22 20:40:22 +0000473 newtable = mp->ma_smalltable;
Tim Peters0c6010b2001-05-23 23:33:57 +0000474 if (newtable == oldtable) {
Tim Petersf8a548c2001-05-24 16:26:40 +0000475 if (mp->ma_fill == mp->ma_used) {
476 /* No dummies, so no point doing anything. */
Tim Peters0c6010b2001-05-23 23:33:57 +0000477 return 0;
Tim Petersf8a548c2001-05-24 16:26:40 +0000478 }
479 /* We're not going to resize it, but rebuild the
480 table anyway to purge old dummy entries.
481 Subtle: This is *necessary* if fill==size,
482 as lookdict needs at least one virgin slot to
483 terminate failing searches. If fill < size, it's
484 merely desirable, as dummies slow searches. */
485 assert(mp->ma_fill > mp->ma_used);
Tim Peters0c6010b2001-05-23 23:33:57 +0000486 memcpy(small_copy, oldtable, sizeof(small_copy));
487 oldtable = small_copy;
488 }
Tim Petersdea48ec2001-05-22 20:40:22 +0000489 }
490 else {
491 newtable = PyMem_NEW(dictentry, newsize);
492 if (newtable == NULL) {
493 PyErr_NoMemory();
494 return -1;
495 }
496 }
Tim Peters0c6010b2001-05-23 23:33:57 +0000497
498 /* Make the dict empty, using the new table. */
Tim Petersdea48ec2001-05-22 20:40:22 +0000499 assert(newtable != oldtable);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000500 mp->ma_table = newtable;
Tim Petersafb6ae82001-06-04 21:00:21 +0000501 mp->ma_mask = newsize - 1;
Tim Petersdea48ec2001-05-22 20:40:22 +0000502 memset(newtable, 0, sizeof(dictentry) * newsize);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000503 mp->ma_used = 0;
Tim Petersdea48ec2001-05-22 20:40:22 +0000504 i = mp->ma_fill;
505 mp->ma_fill = 0;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000506
Tim Peters19283142001-05-17 22:25:34 +0000507 /* Copy the data over; this is refcount-neutral for active entries;
508 dummy entries aren't copied over, of course */
Tim Petersdea48ec2001-05-22 20:40:22 +0000509 for (ep = oldtable; i > 0; ep++) {
510 if (ep->me_value != NULL) { /* active entry */
511 --i;
Tim Peters19283142001-05-17 22:25:34 +0000512 insertdict(mp, ep->me_key, ep->me_hash, ep->me_value);
Tim Petersdea48ec2001-05-22 20:40:22 +0000513 }
Tim Peters19283142001-05-17 22:25:34 +0000514 else if (ep->me_key != NULL) { /* dummy entry */
Tim Petersdea48ec2001-05-22 20:40:22 +0000515 --i;
Tim Peters19283142001-05-17 22:25:34 +0000516 assert(ep->me_key == dummy);
517 Py_DECREF(ep->me_key);
Guido van Rossum255443b1998-04-10 22:47:14 +0000518 }
Tim Peters19283142001-05-17 22:25:34 +0000519 /* else key == value == NULL: nothing to do */
Guido van Rossumd7047b31995-01-02 19:07:15 +0000520 }
521
Tim Peters0c6010b2001-05-23 23:33:57 +0000522 if (is_oldtable_malloced)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000523 PyMem_DEL(oldtable);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000524 return 0;
525}
526
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000527PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000528PyDict_GetItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000529{
530 long hash;
Fred Drake1bff34a2000-08-31 19:31:38 +0000531 dictobject *mp = (dictobject *)op;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000532 if (!PyDict_Check(op)) {
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000533 return NULL;
534 }
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000535#ifdef CACHE_HASH
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000536 if (!PyString_Check(key) ||
537 (hash = ((PyStringObject *) key)->ob_shash) == -1)
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000538#endif
Guido van Rossumca756f21997-01-23 19:39:29 +0000539 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000540 hash = PyObject_Hash(key);
Guido van Rossum474b19e1998-05-14 01:00:51 +0000541 if (hash == -1) {
542 PyErr_Clear();
Guido van Rossumca756f21997-01-23 19:39:29 +0000543 return NULL;
Guido van Rossum474b19e1998-05-14 01:00:51 +0000544 }
Guido van Rossumca756f21997-01-23 19:39:29 +0000545 }
Fred Drake1bff34a2000-08-31 19:31:38 +0000546 return (mp->ma_lookup)(mp, key, hash)->me_value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000547}
548
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000549/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
550 * dictionary if it is merely replacing the value for an existing key.
551 * This is means that it's safe to loop over a dictionary with
552 * PyDict_Next() and occasionally replace a value -- but you can't
553 * insert new keys or remove them.
554 */
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000555int
Tim Peters1f5871e2000-07-04 17:44:48 +0000556PyDict_SetItem(register PyObject *op, PyObject *key, PyObject *value)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000557{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000558 register dictobject *mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000559 register long hash;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000560 register int n_used;
561
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000562 if (!PyDict_Check(op)) {
563 PyErr_BadInternalCall();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000564 return -1;
565 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000566 mp = (dictobject *)op;
Guido van Rossum2a61e741997-01-18 07:55:05 +0000567#ifdef CACHE_HASH
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000568 if (PyString_Check(key)) {
Guido van Rossum2a61e741997-01-18 07:55:05 +0000569#ifdef INTERN_STRINGS
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000570 if (((PyStringObject *)key)->ob_sinterned != NULL) {
571 key = ((PyStringObject *)key)->ob_sinterned;
572 hash = ((PyStringObject *)key)->ob_shash;
Guido van Rossum2a61e741997-01-18 07:55:05 +0000573 }
574 else
575#endif
576 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000577 hash = ((PyStringObject *)key)->ob_shash;
Guido van Rossum2a61e741997-01-18 07:55:05 +0000578 if (hash == -1)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000579 hash = PyObject_Hash(key);
Guido van Rossum2a61e741997-01-18 07:55:05 +0000580 }
581 }
582 else
583#endif
584 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000585 hash = PyObject_Hash(key);
Guido van Rossum2a61e741997-01-18 07:55:05 +0000586 if (hash == -1)
587 return -1;
Guido van Rossum2a61e741997-01-18 07:55:05 +0000588 }
Tim Petersafb6ae82001-06-04 21:00:21 +0000589 assert(mp->ma_fill <= mp->ma_mask); /* at least one empty slot */
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000590 n_used = mp->ma_used;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000591 Py_INCREF(value);
592 Py_INCREF(key);
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000593 insertdict(mp, key, hash, value);
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000594 /* If we added a key, we can safely resize. Otherwise skip this!
595 * If fill >= 2/3 size, adjust size. Normally, this doubles the
596 * size, but it's also possible for the dict to shrink (if ma_fill is
597 * much larger than ma_used, meaning a lot of dict keys have been
598 * deleted).
599 */
Tim Petersafb6ae82001-06-04 21:00:21 +0000600 if (mp->ma_used > n_used && mp->ma_fill*3 >= (mp->ma_mask+1)*2) {
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000601 if (dictresize(mp, mp->ma_used*2) != 0)
602 return -1;
603 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000604 return 0;
605}
606
607int
Tim Peters1f5871e2000-07-04 17:44:48 +0000608PyDict_DelItem(PyObject *op, PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000609{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000610 register dictobject *mp;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000611 register long hash;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000612 register dictentry *ep;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000613 PyObject *old_value, *old_key;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000614
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000615 if (!PyDict_Check(op)) {
616 PyErr_BadInternalCall();
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000617 return -1;
618 }
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000619#ifdef CACHE_HASH
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000620 if (!PyString_Check(key) ||
621 (hash = ((PyStringObject *) key)->ob_shash) == -1)
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000622#endif
Guido van Rossumca756f21997-01-23 19:39:29 +0000623 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000624 hash = PyObject_Hash(key);
Guido van Rossumca756f21997-01-23 19:39:29 +0000625 if (hash == -1)
626 return -1;
627 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000628 mp = (dictobject *)op;
Fred Drake1bff34a2000-08-31 19:31:38 +0000629 ep = (mp->ma_lookup)(mp, key, hash);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000630 if (ep->me_value == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000631 PyErr_SetObject(PyExc_KeyError, key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000632 return -1;
633 }
Guido van Rossumd7047b31995-01-02 19:07:15 +0000634 old_key = ep->me_key;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000635 Py_INCREF(dummy);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000636 ep->me_key = dummy;
Guido van Rossumd7047b31995-01-02 19:07:15 +0000637 old_value = ep->me_value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000638 ep->me_value = NULL;
639 mp->ma_used--;
Tim Petersea8f2bf2000-12-13 01:02:46 +0000640 Py_DECREF(old_value);
641 Py_DECREF(old_key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000642 return 0;
643}
644
Guido van Rossum25831651993-05-19 14:50:45 +0000645void
Tim Peters1f5871e2000-07-04 17:44:48 +0000646PyDict_Clear(PyObject *op)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000647{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000648 dictobject *mp;
Tim Petersdea48ec2001-05-22 20:40:22 +0000649 dictentry *ep, *table;
650 int table_is_malloced;
651 int fill;
652 dictentry small_copy[MINSIZE];
653#ifdef Py_DEBUG
654 int i, n;
655#endif
656
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000657 if (!PyDict_Check(op))
Guido van Rossum25831651993-05-19 14:50:45 +0000658 return;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000659 mp = (dictobject *)op;
Tim Petersdea48ec2001-05-22 20:40:22 +0000660#ifdef Py_DEBUG
Tim Petersafb6ae82001-06-04 21:00:21 +0000661 n = mp->ma_mask + 1;
Tim Petersdea48ec2001-05-22 20:40:22 +0000662 i = 0;
663#endif
664
665 table = mp->ma_table;
666 assert(table != NULL);
667 table_is_malloced = table != mp->ma_smalltable;
668
669 /* This is delicate. During the process of clearing the dict,
670 * decrefs can cause the dict to mutate. To avoid fatal confusion
671 * (voice of experience), we have to make the dict empty before
672 * clearing the slots, and never refer to anything via mp->xxx while
673 * clearing.
674 */
675 fill = mp->ma_fill;
676 if (table_is_malloced)
677 empty_to_minsize(mp);
678
679 else if (fill > 0) {
680 /* It's a small table with something that needs to be cleared.
681 * Afraid the only safe way is to copy the dict entries into
682 * another small table first.
683 */
684 memcpy(small_copy, table, sizeof(small_copy));
685 table = small_copy;
686 empty_to_minsize(mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000687 }
Tim Petersdea48ec2001-05-22 20:40:22 +0000688 /* else it's a small table that's already empty */
689
690 /* Now we can finally clear things. If C had refcounts, we could
691 * assert that the refcount on table is 1 now, i.e. that this function
692 * has unique access to it, so decref side-effects can't alter it.
693 */
694 for (ep = table; fill > 0; ++ep) {
695#ifdef Py_DEBUG
696 assert(i < n);
697 ++i;
698#endif
699 if (ep->me_key) {
700 --fill;
701 Py_DECREF(ep->me_key);
702 Py_XDECREF(ep->me_value);
703 }
704#ifdef Py_DEBUG
705 else
706 assert(ep->me_value == NULL);
707#endif
708 }
709
710 if (table_is_malloced)
711 PyMem_DEL(table);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000712}
713
Tim Peters67830702001-03-21 19:23:56 +0000714/* CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
715 * mutates the dict. One exception: it is safe if the loop merely changes
716 * the values associated with the keys (but doesn't insert new keys or
717 * delete keys), via PyDict_SetItem().
718 */
Guido van Rossum25831651993-05-19 14:50:45 +0000719int
Tim Peters1f5871e2000-07-04 17:44:48 +0000720PyDict_Next(PyObject *op, int *ppos, PyObject **pkey, PyObject **pvalue)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000721{
Guido van Rossum25831651993-05-19 14:50:45 +0000722 int i;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000723 register dictobject *mp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000724 if (!PyDict_Check(op))
Guido van Rossum25831651993-05-19 14:50:45 +0000725 return 0;
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000726 mp = (dictobject *)op;
Guido van Rossum25831651993-05-19 14:50:45 +0000727 i = *ppos;
728 if (i < 0)
729 return 0;
Tim Petersafb6ae82001-06-04 21:00:21 +0000730 while (i <= mp->ma_mask && mp->ma_table[i].me_value == NULL)
Guido van Rossum25831651993-05-19 14:50:45 +0000731 i++;
732 *ppos = i+1;
Tim Petersafb6ae82001-06-04 21:00:21 +0000733 if (i > mp->ma_mask)
Guido van Rossum25831651993-05-19 14:50:45 +0000734 return 0;
735 if (pkey)
736 *pkey = mp->ma_table[i].me_key;
737 if (pvalue)
738 *pvalue = mp->ma_table[i].me_value;
739 return 1;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000740}
741
742/* Methods */
743
744static void
Tim Peters1f5871e2000-07-04 17:44:48 +0000745dict_dealloc(register dictobject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000746{
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000747 register dictentry *ep;
Tim Petersdea48ec2001-05-22 20:40:22 +0000748 int fill = mp->ma_fill;
Guido van Rossumd724b232000-03-13 16:01:29 +0000749 Py_TRASHCAN_SAFE_BEGIN(mp)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000750 PyObject_GC_Fini(mp);
Tim Petersdea48ec2001-05-22 20:40:22 +0000751 for (ep = mp->ma_table; fill > 0; ep++) {
752 if (ep->me_key) {
753 --fill;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000754 Py_DECREF(ep->me_key);
Tim Petersdea48ec2001-05-22 20:40:22 +0000755 Py_XDECREF(ep->me_value);
Guido van Rossum255443b1998-04-10 22:47:14 +0000756 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000757 }
Tim Petersdea48ec2001-05-22 20:40:22 +0000758 if (mp->ma_table != mp->ma_smalltable)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000759 PyMem_DEL(mp->ma_table);
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000760 mp = (dictobject *) PyObject_AS_GC(mp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000761 PyObject_DEL(mp);
Guido van Rossumd724b232000-03-13 16:01:29 +0000762 Py_TRASHCAN_SAFE_END(mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000763}
764
765static int
Tim Peters1f5871e2000-07-04 17:44:48 +0000766dict_print(register dictobject *mp, register FILE *fp, register int flags)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000767{
768 register int i;
769 register int any;
Guido van Rossum255443b1998-04-10 22:47:14 +0000770
771 i = Py_ReprEnter((PyObject*)mp);
772 if (i != 0) {
773 if (i < 0)
774 return i;
775 fprintf(fp, "{...}");
776 return 0;
777 }
778
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000779 fprintf(fp, "{");
780 any = 0;
Tim Petersafb6ae82001-06-04 21:00:21 +0000781 for (i = 0; i <= mp->ma_mask; i++) {
Tim Peters23cf6be2001-06-02 08:02:56 +0000782 dictentry *ep = mp->ma_table + i;
783 PyObject *pvalue = ep->me_value;
784 if (pvalue != NULL) {
785 /* Prevent PyObject_Repr from deleting value during
786 key format */
787 Py_INCREF(pvalue);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000788 if (any++ > 0)
789 fprintf(fp, ", ");
Guido van Rossum255443b1998-04-10 22:47:14 +0000790 if (PyObject_Print((PyObject *)ep->me_key, fp, 0)!=0) {
Tim Peters23cf6be2001-06-02 08:02:56 +0000791 Py_DECREF(pvalue);
Guido van Rossum255443b1998-04-10 22:47:14 +0000792 Py_ReprLeave((PyObject*)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000793 return -1;
Guido van Rossum255443b1998-04-10 22:47:14 +0000794 }
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000795 fprintf(fp, ": ");
Tim Peters19b77cf2001-06-02 08:27:39 +0000796 if (PyObject_Print(pvalue, fp, 0) != 0) {
Tim Peters23cf6be2001-06-02 08:02:56 +0000797 Py_DECREF(pvalue);
Guido van Rossum255443b1998-04-10 22:47:14 +0000798 Py_ReprLeave((PyObject*)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000799 return -1;
Guido van Rossum255443b1998-04-10 22:47:14 +0000800 }
Tim Peters23cf6be2001-06-02 08:02:56 +0000801 Py_DECREF(pvalue);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000802 }
803 }
804 fprintf(fp, "}");
Guido van Rossum255443b1998-04-10 22:47:14 +0000805 Py_ReprLeave((PyObject*)mp);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000806 return 0;
807}
808
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000809static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000810dict_repr(dictobject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000811{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000812 auto PyObject *v;
813 PyObject *sepa, *colon;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000814 register int i;
815 register int any;
Guido van Rossum255443b1998-04-10 22:47:14 +0000816
817 i = Py_ReprEnter((PyObject*)mp);
818 if (i != 0) {
819 if (i > 0)
820 return PyString_FromString("{...}");
821 return NULL;
822 }
823
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000824 v = PyString_FromString("{");
825 sepa = PyString_FromString(", ");
826 colon = PyString_FromString(": ");
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000827 any = 0;
Tim Petersafb6ae82001-06-04 21:00:21 +0000828 for (i = 0; i <= mp->ma_mask && v; i++) {
Tim Peters23cf6be2001-06-02 08:02:56 +0000829 dictentry *ep = mp->ma_table + i;
830 PyObject *pvalue = ep->me_value;
831 if (pvalue != NULL) {
832 /* Prevent PyObject_Repr from deleting value during
833 key format */
834 Py_INCREF(pvalue);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000835 if (any++)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000836 PyString_Concat(&v, sepa);
837 PyString_ConcatAndDel(&v, PyObject_Repr(ep->me_key));
838 PyString_Concat(&v, colon);
Tim Peters23cf6be2001-06-02 08:02:56 +0000839 PyString_ConcatAndDel(&v, PyObject_Repr(pvalue));
840 Py_DECREF(pvalue);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000841 }
842 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000843 PyString_ConcatAndDel(&v, PyString_FromString("}"));
Guido van Rossum255443b1998-04-10 22:47:14 +0000844 Py_ReprLeave((PyObject*)mp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000845 Py_XDECREF(sepa);
846 Py_XDECREF(colon);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000847 return v;
848}
849
850static int
Tim Peters1f5871e2000-07-04 17:44:48 +0000851dict_length(dictobject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000852{
853 return mp->ma_used;
854}
855
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000856static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000857dict_subscript(dictobject *mp, register PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000858{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000859 PyObject *v;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000860 long hash;
Tim Petersdea48ec2001-05-22 20:40:22 +0000861 assert(mp->ma_table != NULL);
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000862#ifdef CACHE_HASH
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000863 if (!PyString_Check(key) ||
864 (hash = ((PyStringObject *) key)->ob_shash) == -1)
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000865#endif
Guido van Rossumca756f21997-01-23 19:39:29 +0000866 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000867 hash = PyObject_Hash(key);
Guido van Rossumca756f21997-01-23 19:39:29 +0000868 if (hash == -1)
869 return NULL;
870 }
Fred Drake1bff34a2000-08-31 19:31:38 +0000871 v = (mp->ma_lookup)(mp, key, hash) -> me_value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000872 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000873 PyErr_SetObject(PyExc_KeyError, key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000874 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000875 Py_INCREF(v);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000876 return v;
877}
878
879static int
Tim Peters1f5871e2000-07-04 17:44:48 +0000880dict_ass_sub(dictobject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000881{
882 if (w == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000883 return PyDict_DelItem((PyObject *)mp, v);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000884 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000885 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000886}
887
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000888static PyMappingMethods dict_as_mapping = {
889 (inquiry)dict_length, /*mp_length*/
890 (binaryfunc)dict_subscript, /*mp_subscript*/
891 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000892};
893
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000894static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000895dict_keys(register dictobject *mp, PyObject *args)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000896{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000897 register PyObject *v;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000898 register int i, j, n;
899
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000900 if (!PyArg_NoArgs(args))
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000901 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000902 again:
903 n = mp->ma_used;
904 v = PyList_New(n);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000905 if (v == NULL)
906 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000907 if (n != mp->ma_used) {
908 /* Durnit. The allocations caused the dict to resize.
909 * Just start over, this shouldn't normally happen.
910 */
911 Py_DECREF(v);
912 goto again;
913 }
Tim Petersafb6ae82001-06-04 21:00:21 +0000914 for (i = 0, j = 0; i <= mp->ma_mask; i++) {
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000915 if (mp->ma_table[i].me_value != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000916 PyObject *key = mp->ma_table[i].me_key;
917 Py_INCREF(key);
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000918 PyList_SET_ITEM(v, j, key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000919 j++;
920 }
921 }
922 return v;
923}
924
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000925static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000926dict_values(register dictobject *mp, PyObject *args)
Guido van Rossum25831651993-05-19 14:50:45 +0000927{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000928 register PyObject *v;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000929 register int i, j, n;
930
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000931 if (!PyArg_NoArgs(args))
Guido van Rossum25831651993-05-19 14:50:45 +0000932 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000933 again:
934 n = mp->ma_used;
935 v = PyList_New(n);
Guido van Rossum25831651993-05-19 14:50:45 +0000936 if (v == NULL)
937 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000938 if (n != mp->ma_used) {
939 /* Durnit. The allocations caused the dict to resize.
940 * Just start over, this shouldn't normally happen.
941 */
942 Py_DECREF(v);
943 goto again;
944 }
Tim Petersafb6ae82001-06-04 21:00:21 +0000945 for (i = 0, j = 0; i <= mp->ma_mask; i++) {
Guido van Rossum25831651993-05-19 14:50:45 +0000946 if (mp->ma_table[i].me_value != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000947 PyObject *value = mp->ma_table[i].me_value;
948 Py_INCREF(value);
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000949 PyList_SET_ITEM(v, j, value);
Guido van Rossum25831651993-05-19 14:50:45 +0000950 j++;
951 }
952 }
953 return v;
954}
955
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000956static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000957dict_items(register dictobject *mp, PyObject *args)
Guido van Rossum25831651993-05-19 14:50:45 +0000958{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000959 register PyObject *v;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000960 register int i, j, n;
961 PyObject *item, *key, *value;
962
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000963 if (!PyArg_NoArgs(args))
Guido van Rossum25831651993-05-19 14:50:45 +0000964 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000965 /* Preallocate the list of tuples, to avoid allocations during
966 * the loop over the items, which could trigger GC, which
967 * could resize the dict. :-(
968 */
969 again:
970 n = mp->ma_used;
971 v = PyList_New(n);
Guido van Rossum25831651993-05-19 14:50:45 +0000972 if (v == NULL)
973 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000974 for (i = 0; i < n; i++) {
975 item = PyTuple_New(2);
976 if (item == NULL) {
977 Py_DECREF(v);
978 return NULL;
979 }
980 PyList_SET_ITEM(v, i, item);
981 }
982 if (n != mp->ma_used) {
983 /* Durnit. The allocations caused the dict to resize.
984 * Just start over, this shouldn't normally happen.
985 */
986 Py_DECREF(v);
987 goto again;
988 }
989 /* Nothing we do below makes any function calls. */
Tim Petersafb6ae82001-06-04 21:00:21 +0000990 for (i = 0, j = 0; i <= mp->ma_mask; i++) {
Guido van Rossum25831651993-05-19 14:50:45 +0000991 if (mp->ma_table[i].me_value != NULL) {
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000992 key = mp->ma_table[i].me_key;
993 value = mp->ma_table[i].me_value;
994 item = PyList_GET_ITEM(v, j);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000995 Py_INCREF(key);
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000996 PyTuple_SET_ITEM(item, 0, key);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000997 Py_INCREF(value);
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000998 PyTuple_SET_ITEM(item, 1, value);
Guido van Rossum25831651993-05-19 14:50:45 +0000999 j++;
1000 }
1001 }
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001002 assert(j == n);
Guido van Rossum25831651993-05-19 14:50:45 +00001003 return v;
1004}
1005
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001006static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001007dict_update(register dictobject *mp, PyObject *args)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001008{
1009 register int i;
1010 dictobject *other;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001011 dictentry *entry;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001012 if (!PyArg_Parse(args, "O!", &PyDict_Type, &other))
1013 return NULL;
Jeremy Hylton1fb60882001-01-03 22:34:59 +00001014 if (other == mp || other->ma_used == 0)
1015 goto done; /* a.update(a) or a.update({}); nothing to do */
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001016 /* Do one big resize at the start, rather than incrementally
1017 resizing as we insert new items. Expect that there will be
1018 no (or few) overlapping keys. */
Tim Petersafb6ae82001-06-04 21:00:21 +00001019 if ((mp->ma_fill + other->ma_used)*3 >= (mp->ma_mask+1)*2) {
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001020 if (dictresize(mp, (mp->ma_used + other->ma_used)*3/2) != 0)
1021 return NULL;
1022 }
Tim Petersafb6ae82001-06-04 21:00:21 +00001023 for (i = 0; i <= other->ma_mask; i++) {
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001024 entry = &other->ma_table[i];
1025 if (entry->me_value != NULL) {
1026 Py_INCREF(entry->me_key);
1027 Py_INCREF(entry->me_value);
1028 insertdict(mp, entry->me_key, entry->me_hash,
1029 entry->me_value);
1030 }
1031 }
1032 done:
1033 Py_INCREF(Py_None);
1034 return Py_None;
1035}
1036
1037static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001038dict_copy(register dictobject *mp, PyObject *args)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001039{
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001040 if (!PyArg_Parse(args, ""))
1041 return NULL;
1042 return PyDict_Copy((PyObject*)mp);
1043}
1044
1045PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001046PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001047{
1048 register dictobject *mp;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001049 register int i;
1050 dictobject *copy;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001051 dictentry *entry;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001052
1053 if (o == NULL || !PyDict_Check(o)) {
1054 PyErr_BadInternalCall();
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001055 return NULL;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001056 }
1057 mp = (dictobject *)o;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001058 copy = (dictobject *)PyDict_New();
1059 if (copy == NULL)
1060 return NULL;
1061 if (mp->ma_used > 0) {
1062 if (dictresize(copy, mp->ma_used*3/2) != 0)
1063 return NULL;
Tim Petersafb6ae82001-06-04 21:00:21 +00001064 for (i = 0; i <= mp->ma_mask; i++) {
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001065 entry = &mp->ma_table[i];
1066 if (entry->me_value != NULL) {
1067 Py_INCREF(entry->me_key);
1068 Py_INCREF(entry->me_value);
1069 insertdict(copy, entry->me_key, entry->me_hash,
1070 entry->me_value);
1071 }
1072 }
1073 }
1074 return (PyObject *)copy;
1075}
1076
Guido van Rossum4199fac1993-11-05 10:18:44 +00001077int
Tim Peters1f5871e2000-07-04 17:44:48 +00001078PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00001079{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001080 if (mp == NULL || !PyDict_Check(mp)) {
1081 PyErr_BadInternalCall();
Guido van Rossumb376a4a1993-11-23 17:53:17 +00001082 return 0;
Guido van Rossum4199fac1993-11-05 10:18:44 +00001083 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001084 return ((dictobject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00001085}
1086
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001087PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001088PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001089{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001090 if (mp == NULL || !PyDict_Check(mp)) {
1091 PyErr_BadInternalCall();
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001092 return NULL;
1093 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001094 return dict_keys((dictobject *)mp, (PyObject *)NULL);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001095}
1096
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001097PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001098PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001099{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001100 if (mp == NULL || !PyDict_Check(mp)) {
1101 PyErr_BadInternalCall();
Guido van Rossum25831651993-05-19 14:50:45 +00001102 return NULL;
1103 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001104 return dict_values((dictobject *)mp, (PyObject *)NULL);
Guido van Rossum25831651993-05-19 14:50:45 +00001105}
1106
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001107PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001108PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001109{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001110 if (mp == NULL || !PyDict_Check(mp)) {
1111 PyErr_BadInternalCall();
Guido van Rossum25831651993-05-19 14:50:45 +00001112 return NULL;
1113 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001114 return dict_items((dictobject *)mp, (PyObject *)NULL);
Guido van Rossum25831651993-05-19 14:50:45 +00001115}
1116
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001117/* Subroutine which returns the smallest key in a for which b's value
1118 is different or absent. The value is returned too, through the
Tim Peters95bf9392001-05-10 08:32:44 +00001119 pval argument. Both are NULL if no key in a is found for which b's status
1120 differs. The refcounts on (and only on) non-NULL *pval and function return
1121 values must be decremented by the caller (characterize() increments them
1122 to ensure that mutating comparison and PyDict_GetItem calls can't delete
1123 them before the caller is done looking at them). */
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001124
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001125static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001126characterize(dictobject *a, dictobject *b, PyObject **pval)
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001127{
Tim Peters95bf9392001-05-10 08:32:44 +00001128 PyObject *akey = NULL; /* smallest key in a s.t. a[akey] != b[akey] */
1129 PyObject *aval = NULL; /* a[akey] */
Guido van Rossumb9324202001-01-18 00:39:02 +00001130 int i, cmp;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001131
Tim Petersafb6ae82001-06-04 21:00:21 +00001132 for (i = 0; i <= a->ma_mask; i++) {
Tim Peters95bf9392001-05-10 08:32:44 +00001133 PyObject *thiskey, *thisaval, *thisbval;
1134 if (a->ma_table[i].me_value == NULL)
1135 continue;
1136 thiskey = a->ma_table[i].me_key;
1137 Py_INCREF(thiskey); /* keep alive across compares */
1138 if (akey != NULL) {
1139 cmp = PyObject_RichCompareBool(akey, thiskey, Py_LT);
1140 if (cmp < 0) {
1141 Py_DECREF(thiskey);
1142 goto Fail;
1143 }
1144 if (cmp > 0 ||
Tim Petersafb6ae82001-06-04 21:00:21 +00001145 i > a->ma_mask ||
Tim Peters95bf9392001-05-10 08:32:44 +00001146 a->ma_table[i].me_value == NULL)
1147 {
1148 /* Not the *smallest* a key; or maybe it is
1149 * but the compare shrunk the dict so we can't
1150 * find its associated value anymore; or
1151 * maybe it is but the compare deleted the
1152 * a[thiskey] entry.
1153 */
1154 Py_DECREF(thiskey);
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001155 continue;
Guido van Rossumb9324202001-01-18 00:39:02 +00001156 }
Tim Peters95bf9392001-05-10 08:32:44 +00001157 }
1158
1159 /* Compare a[thiskey] to b[thiskey]; cmp <- true iff equal. */
1160 thisaval = a->ma_table[i].me_value;
1161 assert(thisaval);
1162 Py_INCREF(thisaval); /* keep alive */
1163 thisbval = PyDict_GetItem((PyObject *)b, thiskey);
1164 if (thisbval == NULL)
1165 cmp = 0;
1166 else {
1167 /* both dicts have thiskey: same values? */
1168 cmp = PyObject_RichCompareBool(
1169 thisaval, thisbval, Py_EQ);
1170 if (cmp < 0) {
1171 Py_DECREF(thiskey);
1172 Py_DECREF(thisaval);
1173 goto Fail;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001174 }
1175 }
Tim Peters95bf9392001-05-10 08:32:44 +00001176 if (cmp == 0) {
1177 /* New winner. */
1178 Py_XDECREF(akey);
1179 Py_XDECREF(aval);
1180 akey = thiskey;
1181 aval = thisaval;
1182 }
1183 else {
1184 Py_DECREF(thiskey);
1185 Py_DECREF(thisaval);
1186 }
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001187 }
Tim Peters95bf9392001-05-10 08:32:44 +00001188 *pval = aval;
1189 return akey;
1190
1191Fail:
1192 Py_XDECREF(akey);
1193 Py_XDECREF(aval);
1194 *pval = NULL;
1195 return NULL;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001196}
1197
1198static int
Tim Peters1f5871e2000-07-04 17:44:48 +00001199dict_compare(dictobject *a, dictobject *b)
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001200{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001201 PyObject *adiff, *bdiff, *aval, *bval;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001202 int res;
1203
1204 /* Compare lengths first */
1205 if (a->ma_used < b->ma_used)
1206 return -1; /* a is shorter */
1207 else if (a->ma_used > b->ma_used)
1208 return 1; /* b is shorter */
Tim Peters95bf9392001-05-10 08:32:44 +00001209
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001210 /* Same length -- check all keys */
Tim Peters95bf9392001-05-10 08:32:44 +00001211 bdiff = bval = NULL;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001212 adiff = characterize(a, b, &aval);
Tim Peters95bf9392001-05-10 08:32:44 +00001213 if (adiff == NULL) {
1214 assert(!aval);
Tim Peters3918fb22001-05-10 18:58:31 +00001215 /* Either an error, or a is a subset with the same length so
Tim Peters95bf9392001-05-10 08:32:44 +00001216 * must be equal.
1217 */
1218 res = PyErr_Occurred() ? -1 : 0;
1219 goto Finished;
1220 }
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001221 bdiff = characterize(b, a, &bval);
Tim Peters95bf9392001-05-10 08:32:44 +00001222 if (bdiff == NULL && PyErr_Occurred()) {
1223 assert(!bval);
1224 res = -1;
1225 goto Finished;
1226 }
1227 res = 0;
1228 if (bdiff) {
1229 /* bdiff == NULL "should be" impossible now, but perhaps
1230 * the last comparison done by the characterize() on a had
1231 * the side effect of making the dicts equal!
1232 */
1233 res = PyObject_Compare(adiff, bdiff);
1234 }
1235 if (res == 0 && bval != NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001236 res = PyObject_Compare(aval, bval);
Tim Peters95bf9392001-05-10 08:32:44 +00001237
1238Finished:
1239 Py_XDECREF(adiff);
1240 Py_XDECREF(bdiff);
1241 Py_XDECREF(aval);
1242 Py_XDECREF(bval);
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001243 return res;
1244}
1245
Tim Peterse63415e2001-05-08 04:38:29 +00001246/* Return 1 if dicts equal, 0 if not, -1 if error.
1247 * Gets out as soon as any difference is detected.
1248 * Uses only Py_EQ comparison.
1249 */
1250static int
1251dict_equal(dictobject *a, dictobject *b)
1252{
1253 int i;
1254
1255 if (a->ma_used != b->ma_used)
1256 /* can't be equal if # of entries differ */
1257 return 0;
Tim Peterseb28ef22001-06-02 05:27:19 +00001258
Tim Peterse63415e2001-05-08 04:38:29 +00001259 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Tim Petersafb6ae82001-06-04 21:00:21 +00001260 for (i = 0; i <= a->ma_mask; i++) {
Tim Peterse63415e2001-05-08 04:38:29 +00001261 PyObject *aval = a->ma_table[i].me_value;
1262 if (aval != NULL) {
1263 int cmp;
1264 PyObject *bval;
1265 PyObject *key = a->ma_table[i].me_key;
1266 /* temporarily bump aval's refcount to ensure it stays
1267 alive until we're done with it */
1268 Py_INCREF(aval);
1269 bval = PyDict_GetItem((PyObject *)b, key);
1270 if (bval == NULL) {
1271 Py_DECREF(aval);
1272 return 0;
1273 }
1274 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
1275 Py_DECREF(aval);
1276 if (cmp <= 0) /* error or not equal */
1277 return cmp;
1278 }
1279 }
1280 return 1;
1281 }
1282
1283static PyObject *
1284dict_richcompare(PyObject *v, PyObject *w, int op)
1285{
1286 int cmp;
1287 PyObject *res;
1288
1289 if (!PyDict_Check(v) || !PyDict_Check(w)) {
1290 res = Py_NotImplemented;
1291 }
1292 else if (op == Py_EQ || op == Py_NE) {
1293 cmp = dict_equal((dictobject *)v, (dictobject *)w);
1294 if (cmp < 0)
1295 return NULL;
1296 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
1297 }
Tim Peters4fa58bf2001-05-10 21:45:19 +00001298 else
1299 res = Py_NotImplemented;
Tim Peterse63415e2001-05-08 04:38:29 +00001300 Py_INCREF(res);
1301 return res;
1302 }
1303
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001304static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001305dict_has_key(register dictobject *mp, PyObject *args)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001306{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001307 PyObject *key;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001308 long hash;
1309 register long ok;
Fred Drake52fccfd2000-02-23 15:47:16 +00001310 if (!PyArg_ParseTuple(args, "O:has_key", &key))
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001311 return NULL;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +00001312#ifdef CACHE_HASH
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001313 if (!PyString_Check(key) ||
1314 (hash = ((PyStringObject *) key)->ob_shash) == -1)
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +00001315#endif
Guido van Rossumca756f21997-01-23 19:39:29 +00001316 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001317 hash = PyObject_Hash(key);
Guido van Rossumca756f21997-01-23 19:39:29 +00001318 if (hash == -1)
1319 return NULL;
1320 }
Tim Petersdea48ec2001-05-22 20:40:22 +00001321 ok = (mp->ma_lookup)(mp, key, hash)->me_value != NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001322 return PyInt_FromLong(ok);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001323}
1324
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001325static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001326dict_get(register dictobject *mp, PyObject *args)
Barry Warsawc38c5da1997-10-06 17:49:20 +00001327{
1328 PyObject *key;
Barry Warsaw320ac331997-10-20 17:26:25 +00001329 PyObject *failobj = Py_None;
Barry Warsawc38c5da1997-10-06 17:49:20 +00001330 PyObject *val = NULL;
1331 long hash;
1332
Fred Drake52fccfd2000-02-23 15:47:16 +00001333 if (!PyArg_ParseTuple(args, "O|O:get", &key, &failobj))
Barry Warsawc38c5da1997-10-06 17:49:20 +00001334 return NULL;
1335
Barry Warsawc38c5da1997-10-06 17:49:20 +00001336#ifdef CACHE_HASH
1337 if (!PyString_Check(key) ||
1338 (hash = ((PyStringObject *) key)->ob_shash) == -1)
1339#endif
1340 {
1341 hash = PyObject_Hash(key);
1342 if (hash == -1)
1343 return NULL;
1344 }
Fred Drake1bff34a2000-08-31 19:31:38 +00001345 val = (mp->ma_lookup)(mp, key, hash)->me_value;
Barry Warsaw320ac331997-10-20 17:26:25 +00001346
Barry Warsawc38c5da1997-10-06 17:49:20 +00001347 if (val == NULL)
1348 val = failobj;
1349 Py_INCREF(val);
1350 return val;
1351}
1352
1353
1354static PyObject *
Guido van Rossum164452c2000-08-08 16:12:54 +00001355dict_setdefault(register dictobject *mp, PyObject *args)
1356{
1357 PyObject *key;
1358 PyObject *failobj = Py_None;
1359 PyObject *val = NULL;
1360 long hash;
1361
1362 if (!PyArg_ParseTuple(args, "O|O:setdefault", &key, &failobj))
1363 return NULL;
Guido van Rossum164452c2000-08-08 16:12:54 +00001364
1365#ifdef CACHE_HASH
1366 if (!PyString_Check(key) ||
1367 (hash = ((PyStringObject *) key)->ob_shash) == -1)
1368#endif
1369 {
1370 hash = PyObject_Hash(key);
1371 if (hash == -1)
1372 return NULL;
1373 }
Fred Drake1bff34a2000-08-31 19:31:38 +00001374 val = (mp->ma_lookup)(mp, key, hash)->me_value;
Guido van Rossum164452c2000-08-08 16:12:54 +00001375 if (val == NULL) {
1376 val = failobj;
1377 if (PyDict_SetItem((PyObject*)mp, key, failobj))
1378 val = NULL;
1379 }
1380 Py_XINCREF(val);
1381 return val;
1382}
1383
1384
1385static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001386dict_clear(register dictobject *mp, PyObject *args)
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00001387{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001388 if (!PyArg_NoArgs(args))
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00001389 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001390 PyDict_Clear((PyObject *)mp);
1391 Py_INCREF(Py_None);
1392 return Py_None;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00001393}
1394
Guido van Rossumba6ab842000-12-12 22:02:18 +00001395static PyObject *
1396dict_popitem(dictobject *mp, PyObject *args)
1397{
1398 int i = 0;
1399 dictentry *ep;
1400 PyObject *res;
1401
1402 if (!PyArg_NoArgs(args))
1403 return NULL;
Tim Petersf4b33f62001-06-02 05:42:29 +00001404 /* Allocate the result tuple before checking the size. Believe it
1405 * or not, this allocation could trigger a garbage collection which
1406 * could empty the dict, so if we checked the size first and that
1407 * happened, the result would be an infinite loop (searching for an
1408 * entry that no longer exists). Note that the usual popitem()
1409 * idiom is "while d: k, v = d.popitem()". so needing to throw the
1410 * tuple away if the dict *is* empty isn't a significant
1411 * inefficiency -- possible, but unlikely in practice.
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001412 */
1413 res = PyTuple_New(2);
1414 if (res == NULL)
1415 return NULL;
Guido van Rossume04eaec2001-04-16 00:02:32 +00001416 if (mp->ma_used == 0) {
1417 Py_DECREF(res);
1418 PyErr_SetString(PyExc_KeyError,
1419 "popitem(): dictionary is empty");
1420 return NULL;
1421 }
Guido van Rossumba6ab842000-12-12 22:02:18 +00001422 /* Set ep to "the first" dict entry with a value. We abuse the hash
1423 * field of slot 0 to hold a search finger:
1424 * If slot 0 has a value, use slot 0.
1425 * Else slot 0 is being used to hold a search finger,
1426 * and we use its hash value as the first index to look.
1427 */
1428 ep = &mp->ma_table[0];
1429 if (ep->me_value == NULL) {
1430 i = (int)ep->me_hash;
Tim Petersdea48ec2001-05-22 20:40:22 +00001431 /* The hash field may be a real hash value, or it may be a
1432 * legit search finger, or it may be a once-legit search
1433 * finger that's out of bounds now because it wrapped around
1434 * or the table shrunk -- simply make sure it's in bounds now.
Guido van Rossumba6ab842000-12-12 22:02:18 +00001435 */
Tim Petersafb6ae82001-06-04 21:00:21 +00001436 if (i > mp->ma_mask || i < 1)
Guido van Rossumba6ab842000-12-12 22:02:18 +00001437 i = 1; /* skip slot 0 */
1438 while ((ep = &mp->ma_table[i])->me_value == NULL) {
1439 i++;
Tim Petersafb6ae82001-06-04 21:00:21 +00001440 if (i > mp->ma_mask)
Guido van Rossumba6ab842000-12-12 22:02:18 +00001441 i = 1;
1442 }
1443 }
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001444 PyTuple_SET_ITEM(res, 0, ep->me_key);
1445 PyTuple_SET_ITEM(res, 1, ep->me_value);
1446 Py_INCREF(dummy);
1447 ep->me_key = dummy;
1448 ep->me_value = NULL;
1449 mp->ma_used--;
1450 assert(mp->ma_table[0].me_value == NULL);
1451 mp->ma_table[0].me_hash = i + 1; /* next place to start */
Guido van Rossumba6ab842000-12-12 22:02:18 +00001452 return res;
1453}
1454
Jeremy Hylton8caad492000-06-23 14:18:11 +00001455static int
1456dict_traverse(PyObject *op, visitproc visit, void *arg)
1457{
1458 int i = 0, err;
1459 PyObject *pk;
1460 PyObject *pv;
1461
1462 while (PyDict_Next(op, &i, &pk, &pv)) {
1463 err = visit(pk, arg);
1464 if (err)
1465 return err;
1466 err = visit(pv, arg);
1467 if (err)
1468 return err;
1469 }
1470 return 0;
1471}
1472
1473static int
1474dict_tp_clear(PyObject *op)
1475{
1476 PyDict_Clear(op);
1477 return 0;
1478}
1479
Tim Petersf7f88b12000-12-13 23:18:45 +00001480
Guido van Rossum09e563a2001-05-01 12:10:21 +00001481staticforward PyObject *dictiter_new(dictobject *, binaryfunc);
1482
1483static PyObject *
1484select_key(PyObject *key, PyObject *value)
1485{
1486 Py_INCREF(key);
1487 return key;
1488}
1489
1490static PyObject *
1491select_value(PyObject *key, PyObject *value)
1492{
1493 Py_INCREF(value);
1494 return value;
1495}
1496
1497static PyObject *
1498select_item(PyObject *key, PyObject *value)
1499{
1500 PyObject *res = PyTuple_New(2);
1501
1502 if (res != NULL) {
1503 Py_INCREF(key);
1504 Py_INCREF(value);
1505 PyTuple_SET_ITEM(res, 0, key);
1506 PyTuple_SET_ITEM(res, 1, value);
1507 }
1508 return res;
1509}
1510
1511static PyObject *
1512dict_iterkeys(dictobject *dict, PyObject *args)
1513{
1514 if (!PyArg_ParseTuple(args, ""))
1515 return NULL;
1516 return dictiter_new(dict, select_key);
1517}
1518
1519static PyObject *
1520dict_itervalues(dictobject *dict, PyObject *args)
1521{
1522 if (!PyArg_ParseTuple(args, ""))
1523 return NULL;
1524 return dictiter_new(dict, select_value);
1525}
1526
1527static PyObject *
1528dict_iteritems(dictobject *dict, PyObject *args)
1529{
1530 if (!PyArg_ParseTuple(args, ""))
1531 return NULL;
1532 return dictiter_new(dict, select_item);
1533}
1534
1535
Tim Petersf7f88b12000-12-13 23:18:45 +00001536static char has_key__doc__[] =
1537"D.has_key(k) -> 1 if D has a key k, else 0";
1538
1539static char get__doc__[] =
1540"D.get(k[,d]) -> D[k] if D.has_key(k), else d. d defaults to None.";
1541
1542static char setdefault_doc__[] =
1543"D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if not D.has_key(k)";
1544
1545static char popitem__doc__[] =
1546"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
15472-tuple; but raise KeyError if D is empty";
1548
1549static char keys__doc__[] =
1550"D.keys() -> list of D's keys";
1551
1552static char items__doc__[] =
1553"D.items() -> list of D's (key, value) pairs, as 2-tuples";
1554
1555static char values__doc__[] =
1556"D.values() -> list of D's values";
1557
1558static char update__doc__[] =
1559"D.update(E) -> None. Update D from E: for k in E.keys(): D[k] = E[k]";
1560
1561static char clear__doc__[] =
1562"D.clear() -> None. Remove all items from D.";
1563
1564static char copy__doc__[] =
1565"D.copy() -> a shallow copy of D";
1566
Guido van Rossum09e563a2001-05-01 12:10:21 +00001567static char iterkeys__doc__[] =
1568"D.iterkeys() -> an iterator over the keys of D";
1569
1570static char itervalues__doc__[] =
1571"D.itervalues() -> an iterator over the values of D";
1572
1573static char iteritems__doc__[] =
1574"D.iteritems() -> an iterator over the (key, value) items of D";
1575
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001576static PyMethodDef mapp_methods[] = {
Tim Petersf7f88b12000-12-13 23:18:45 +00001577 {"has_key", (PyCFunction)dict_has_key, METH_VARARGS,
1578 has_key__doc__},
1579 {"get", (PyCFunction)dict_get, METH_VARARGS,
1580 get__doc__},
1581 {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS,
1582 setdefault_doc__},
1583 {"popitem", (PyCFunction)dict_popitem, METH_OLDARGS,
1584 popitem__doc__},
1585 {"keys", (PyCFunction)dict_keys, METH_OLDARGS,
1586 keys__doc__},
1587 {"items", (PyCFunction)dict_items, METH_OLDARGS,
1588 items__doc__},
1589 {"values", (PyCFunction)dict_values, METH_OLDARGS,
1590 values__doc__},
1591 {"update", (PyCFunction)dict_update, METH_OLDARGS,
1592 update__doc__},
1593 {"clear", (PyCFunction)dict_clear, METH_OLDARGS,
1594 clear__doc__},
1595 {"copy", (PyCFunction)dict_copy, METH_OLDARGS,
1596 copy__doc__},
Guido van Rossum09e563a2001-05-01 12:10:21 +00001597 {"iterkeys", (PyCFunction)dict_iterkeys, METH_VARARGS,
1598 iterkeys__doc__},
1599 {"itervalues", (PyCFunction)dict_itervalues, METH_VARARGS,
1600 itervalues__doc__},
1601 {"iteritems", (PyCFunction)dict_iteritems, METH_VARARGS,
1602 iteritems__doc__},
Tim Petersf7f88b12000-12-13 23:18:45 +00001603 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001604};
1605
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001606static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001607dict_getattr(dictobject *mp, char *name)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001608{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001609 return Py_FindMethod(mapp_methods, (PyObject *)mp, name);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001610}
1611
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001612static int
1613dict_contains(dictobject *mp, PyObject *key)
1614{
1615 long hash;
1616
1617#ifdef CACHE_HASH
1618 if (!PyString_Check(key) ||
1619 (hash = ((PyStringObject *) key)->ob_shash) == -1)
1620#endif
1621 {
1622 hash = PyObject_Hash(key);
1623 if (hash == -1)
1624 return -1;
1625 }
Tim Petersdea48ec2001-05-22 20:40:22 +00001626 return (mp->ma_lookup)(mp, key, hash)->me_value != NULL;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001627}
1628
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001629/* Hack to implement "key in dict" */
1630static PySequenceMethods dict_as_sequence = {
1631 0, /* sq_length */
1632 0, /* sq_concat */
1633 0, /* sq_repeat */
1634 0, /* sq_item */
1635 0, /* sq_slice */
1636 0, /* sq_ass_item */
1637 0, /* sq_ass_slice */
1638 (objobjproc)dict_contains, /* sq_contains */
1639 0, /* sq_inplace_concat */
1640 0, /* sq_inplace_repeat */
1641};
1642
Guido van Rossum09e563a2001-05-01 12:10:21 +00001643static PyObject *
1644dict_iter(dictobject *dict)
1645{
1646 return dictiter_new(dict, select_key);
1647}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001648
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001649PyTypeObject PyDict_Type = {
1650 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001651 0,
Guido van Rossum9bfef441993-03-29 10:43:31 +00001652 "dictionary",
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001653 sizeof(dictobject) + PyGC_HEAD_SIZE,
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001654 0,
Guido van Rossumb9324202001-01-18 00:39:02 +00001655 (destructor)dict_dealloc, /* tp_dealloc */
1656 (printfunc)dict_print, /* tp_print */
1657 (getattrfunc)dict_getattr, /* tp_getattr */
1658 0, /* tp_setattr */
Tim Peters4fa58bf2001-05-10 21:45:19 +00001659 (cmpfunc)dict_compare, /* tp_compare */
Guido van Rossumb9324202001-01-18 00:39:02 +00001660 (reprfunc)dict_repr, /* tp_repr */
1661 0, /* tp_as_number */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001662 &dict_as_sequence, /* tp_as_sequence */
Guido van Rossumb9324202001-01-18 00:39:02 +00001663 &dict_as_mapping, /* tp_as_mapping */
1664 0, /* tp_hash */
1665 0, /* tp_call */
1666 0, /* tp_str */
1667 0, /* tp_getattro */
1668 0, /* tp_setattro */
1669 0, /* tp_as_buffer */
1670 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /* tp_flags */
1671 0, /* tp_doc */
1672 (traverseproc)dict_traverse, /* tp_traverse */
1673 (inquiry)dict_tp_clear, /* tp_clear */
Tim Peterse63415e2001-05-08 04:38:29 +00001674 dict_richcompare, /* tp_richcompare */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001675 0, /* tp_weaklistoffset */
Guido van Rossum09e563a2001-05-01 12:10:21 +00001676 (getiterfunc)dict_iter, /* tp_iter */
Guido van Rossum213c7a62001-04-23 14:08:49 +00001677 0, /* tp_iternext */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001678};
1679
Guido van Rossum3cca2451997-05-16 14:23:33 +00001680/* For backward compatibility with old dictionary interface */
1681
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001682PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001683PyDict_GetItemString(PyObject *v, char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001684{
Guido van Rossum3cca2451997-05-16 14:23:33 +00001685 PyObject *kv, *rv;
1686 kv = PyString_FromString(key);
1687 if (kv == NULL)
1688 return NULL;
Guido van Rossum3cca2451997-05-16 14:23:33 +00001689 rv = PyDict_GetItem(v, kv);
1690 Py_DECREF(kv);
1691 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001692}
1693
1694int
Tim Peters1f5871e2000-07-04 17:44:48 +00001695PyDict_SetItemString(PyObject *v, char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001696{
Guido van Rossum3cca2451997-05-16 14:23:33 +00001697 PyObject *kv;
1698 int err;
1699 kv = PyString_FromString(key);
1700 if (kv == NULL)
Guido van Rossum037b2201997-05-20 18:35:19 +00001701 return -1;
Guido van Rossum4f3bf1e1997-09-29 23:31:11 +00001702 PyString_InternInPlace(&kv); /* XXX Should we really? */
Guido van Rossum3cca2451997-05-16 14:23:33 +00001703 err = PyDict_SetItem(v, kv, item);
1704 Py_DECREF(kv);
1705 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001706}
1707
1708int
Tim Peters1f5871e2000-07-04 17:44:48 +00001709PyDict_DelItemString(PyObject *v, char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001710{
Guido van Rossum3cca2451997-05-16 14:23:33 +00001711 PyObject *kv;
1712 int err;
1713 kv = PyString_FromString(key);
1714 if (kv == NULL)
Guido van Rossum037b2201997-05-20 18:35:19 +00001715 return -1;
Guido van Rossum3cca2451997-05-16 14:23:33 +00001716 err = PyDict_DelItem(v, kv);
1717 Py_DECREF(kv);
1718 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001719}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001720
1721/* Dictionary iterator type */
1722
1723extern PyTypeObject PyDictIter_Type; /* Forward */
1724
1725typedef struct {
1726 PyObject_HEAD
1727 dictobject *di_dict;
Guido van Rossumb1f35bf2001-05-02 15:13:44 +00001728 int di_used;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001729 int di_pos;
Guido van Rossum09e563a2001-05-01 12:10:21 +00001730 binaryfunc di_select;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001731} dictiterobject;
1732
1733static PyObject *
Guido van Rossum09e563a2001-05-01 12:10:21 +00001734dictiter_new(dictobject *dict, binaryfunc select)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001735{
1736 dictiterobject *di;
1737 di = PyObject_NEW(dictiterobject, &PyDictIter_Type);
1738 if (di == NULL)
1739 return NULL;
1740 Py_INCREF(dict);
1741 di->di_dict = dict;
Guido van Rossumb1f35bf2001-05-02 15:13:44 +00001742 di->di_used = dict->ma_used;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001743 di->di_pos = 0;
Guido van Rossum09e563a2001-05-01 12:10:21 +00001744 di->di_select = select;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001745 return (PyObject *)di;
1746}
1747
1748static void
1749dictiter_dealloc(dictiterobject *di)
1750{
1751 Py_DECREF(di->di_dict);
1752 PyObject_DEL(di);
1753}
1754
1755static PyObject *
1756dictiter_next(dictiterobject *di, PyObject *args)
1757{
Guido van Rossum09e563a2001-05-01 12:10:21 +00001758 PyObject *key, *value;
Guido van Rossum213c7a62001-04-23 14:08:49 +00001759
Guido van Rossumb1f35bf2001-05-02 15:13:44 +00001760 if (di->di_used != di->di_dict->ma_used) {
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001761 PyErr_SetString(PyExc_RuntimeError,
1762 "dictionary changed size during iteration");
1763 return NULL;
1764 }
Guido van Rossum09e563a2001-05-01 12:10:21 +00001765 if (PyDict_Next((PyObject *)(di->di_dict), &di->di_pos, &key, &value)) {
1766 return (*di->di_select)(key, value);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001767 }
1768 PyErr_SetObject(PyExc_StopIteration, Py_None);
1769 return NULL;
1770}
1771
1772static PyObject *
1773dictiter_getiter(PyObject *it)
1774{
1775 Py_INCREF(it);
1776 return it;
1777}
1778
1779static PyMethodDef dictiter_methods[] = {
1780 {"next", (PyCFunction)dictiter_next, METH_VARARGS,
1781 "it.next() -- get the next value, or raise StopIteration"},
1782 {NULL, NULL} /* sentinel */
1783};
1784
1785static PyObject *
Guido van Rossum213c7a62001-04-23 14:08:49 +00001786dictiter_getattr(dictiterobject *di, char *name)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001787{
Guido van Rossum213c7a62001-04-23 14:08:49 +00001788 return Py_FindMethod(dictiter_methods, (PyObject *)di, name);
1789}
1790
1791static PyObject *dictiter_iternext(dictiterobject *di)
1792{
Guido van Rossum09e563a2001-05-01 12:10:21 +00001793 PyObject *key, *value;
Guido van Rossum213c7a62001-04-23 14:08:49 +00001794
Guido van Rossumb1f35bf2001-05-02 15:13:44 +00001795 if (di->di_used != di->di_dict->ma_used) {
Guido van Rossum213c7a62001-04-23 14:08:49 +00001796 PyErr_SetString(PyExc_RuntimeError,
1797 "dictionary changed size during iteration");
1798 return NULL;
1799 }
Guido van Rossum09e563a2001-05-01 12:10:21 +00001800 if (PyDict_Next((PyObject *)(di->di_dict), &di->di_pos, &key, &value)) {
1801 return (*di->di_select)(key, value);
Guido van Rossum213c7a62001-04-23 14:08:49 +00001802 }
1803 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001804}
1805
1806PyTypeObject PyDictIter_Type = {
1807 PyObject_HEAD_INIT(&PyType_Type)
1808 0, /* ob_size */
1809 "dictionary-iterator", /* tp_name */
1810 sizeof(dictiterobject), /* tp_basicsize */
1811 0, /* tp_itemsize */
1812 /* methods */
1813 (destructor)dictiter_dealloc, /* tp_dealloc */
1814 0, /* tp_print */
1815 (getattrfunc)dictiter_getattr, /* tp_getattr */
1816 0, /* tp_setattr */
1817 0, /* tp_compare */
1818 0, /* tp_repr */
1819 0, /* tp_as_number */
1820 0, /* tp_as_sequence */
1821 0, /* tp_as_mapping */
1822 0, /* tp_hash */
1823 0, /* tp_call */
1824 0, /* tp_str */
1825 0, /* tp_getattro */
1826 0, /* tp_setattro */
1827 0, /* tp_as_buffer */
1828 Py_TPFLAGS_DEFAULT, /* tp_flags */
1829 0, /* tp_doc */
1830 0, /* tp_traverse */
1831 0, /* tp_clear */
1832 0, /* tp_richcompare */
1833 0, /* tp_weaklistoffset */
1834 (getiterfunc)dictiter_getiter, /* tp_iter */
Guido van Rossum213c7a62001-04-23 14:08:49 +00001835 (iternextfunc)dictiter_iternext, /* tp_iternext */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001836};