blob: d8c93bce8d56c5954e46aced531931f80a7df713 [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{
Tim Petersc6057842001-06-16 07:52:53 +0000812 int i;
Tim Petersa7259592001-06-16 05:11:17 +0000813 PyObject *s, *temp, *colon = NULL;
814 PyObject *pieces = NULL, *result = NULL;
815 PyObject *key, *value;
Guido van Rossum255443b1998-04-10 22:47:14 +0000816
Tim Petersa7259592001-06-16 05:11:17 +0000817 i = Py_ReprEnter((PyObject *)mp);
Guido van Rossum255443b1998-04-10 22:47:14 +0000818 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000819 return i > 0 ? PyString_FromString("{...}") : NULL;
Guido van Rossum255443b1998-04-10 22:47:14 +0000820 }
821
Tim Petersa7259592001-06-16 05:11:17 +0000822 if (mp->ma_used == 0) {
823 result = PyString_FromString("{}");
824 goto Done;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000825 }
Tim Petersa7259592001-06-16 05:11:17 +0000826
827 pieces = PyList_New(0);
828 if (pieces == NULL)
829 goto Done;
830
831 colon = PyString_FromString(": ");
832 if (colon == NULL)
833 goto Done;
834
835 /* Do repr() on each key+value pair, and insert ": " between them.
836 Note that repr may mutate the dict. */
Tim Petersc6057842001-06-16 07:52:53 +0000837 i = 0;
838 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
Tim Petersa7259592001-06-16 05:11:17 +0000839 int status;
840 /* Prevent repr from deleting value during key format. */
841 Py_INCREF(value);
842 s = PyObject_Repr(key);
843 PyString_Concat(&s, colon);
844 PyString_ConcatAndDel(&s, PyObject_Repr(value));
845 Py_DECREF(value);
846 if (s == NULL)
847 goto Done;
848 status = PyList_Append(pieces, s);
849 Py_DECREF(s); /* append created a new ref */
850 if (status < 0)
851 goto Done;
852 }
853
854 /* Add "{}" decorations to the first and last items. */
855 assert(PyList_GET_SIZE(pieces) > 0);
856 s = PyString_FromString("{");
857 if (s == NULL)
858 goto Done;
859 temp = PyList_GET_ITEM(pieces, 0);
860 PyString_ConcatAndDel(&s, temp);
861 PyList_SET_ITEM(pieces, 0, s);
862 if (s == NULL)
863 goto Done;
864
865 s = PyString_FromString("}");
866 if (s == NULL)
867 goto Done;
868 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
869 PyString_ConcatAndDel(&temp, s);
870 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
871 if (temp == NULL)
872 goto Done;
873
874 /* Paste them all together with ", " between. */
875 s = PyString_FromString(", ");
876 if (s == NULL)
877 goto Done;
878 result = _PyString_Join(s, pieces);
879 Py_DECREF(s);
880
881Done:
882 Py_XDECREF(pieces);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000883 Py_XDECREF(colon);
Tim Petersa7259592001-06-16 05:11:17 +0000884 Py_ReprLeave((PyObject *)mp);
885 return result;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000886}
887
888static int
Tim Peters1f5871e2000-07-04 17:44:48 +0000889dict_length(dictobject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000890{
891 return mp->ma_used;
892}
893
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000894static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000895dict_subscript(dictobject *mp, register PyObject *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000896{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000897 PyObject *v;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000898 long hash;
Tim Petersdea48ec2001-05-22 20:40:22 +0000899 assert(mp->ma_table != NULL);
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000900#ifdef CACHE_HASH
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000901 if (!PyString_Check(key) ||
902 (hash = ((PyStringObject *) key)->ob_shash) == -1)
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000903#endif
Guido van Rossumca756f21997-01-23 19:39:29 +0000904 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000905 hash = PyObject_Hash(key);
Guido van Rossumca756f21997-01-23 19:39:29 +0000906 if (hash == -1)
907 return NULL;
908 }
Fred Drake1bff34a2000-08-31 19:31:38 +0000909 v = (mp->ma_lookup)(mp, key, hash) -> me_value;
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000910 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000911 PyErr_SetObject(PyExc_KeyError, key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000912 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000913 Py_INCREF(v);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000914 return v;
915}
916
917static int
Tim Peters1f5871e2000-07-04 17:44:48 +0000918dict_ass_sub(dictobject *mp, PyObject *v, PyObject *w)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000919{
920 if (w == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000921 return PyDict_DelItem((PyObject *)mp, v);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000922 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000923 return PyDict_SetItem((PyObject *)mp, v, w);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000924}
925
Guido van Rossuma9e7a811997-05-13 21:02:11 +0000926static PyMappingMethods dict_as_mapping = {
927 (inquiry)dict_length, /*mp_length*/
928 (binaryfunc)dict_subscript, /*mp_subscript*/
929 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000930};
931
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000932static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000933dict_keys(register dictobject *mp, PyObject *args)
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000934{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000935 register PyObject *v;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000936 register int i, j, n;
937
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000938 if (!PyArg_NoArgs(args))
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000939 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000940 again:
941 n = mp->ma_used;
942 v = PyList_New(n);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000943 if (v == NULL)
944 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000945 if (n != mp->ma_used) {
946 /* Durnit. The allocations caused the dict to resize.
947 * Just start over, this shouldn't normally happen.
948 */
949 Py_DECREF(v);
950 goto again;
951 }
Tim Petersafb6ae82001-06-04 21:00:21 +0000952 for (i = 0, j = 0; i <= mp->ma_mask; i++) {
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000953 if (mp->ma_table[i].me_value != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000954 PyObject *key = mp->ma_table[i].me_key;
955 Py_INCREF(key);
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000956 PyList_SET_ITEM(v, j, key);
Guido van Rossum4b1302b1993-03-27 18:11:32 +0000957 j++;
958 }
959 }
960 return v;
961}
962
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000963static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000964dict_values(register dictobject *mp, PyObject *args)
Guido van Rossum25831651993-05-19 14:50:45 +0000965{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000966 register PyObject *v;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000967 register int i, j, n;
968
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000969 if (!PyArg_NoArgs(args))
Guido van Rossum25831651993-05-19 14:50:45 +0000970 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000971 again:
972 n = mp->ma_used;
973 v = PyList_New(n);
Guido van Rossum25831651993-05-19 14:50:45 +0000974 if (v == NULL)
975 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000976 if (n != mp->ma_used) {
977 /* Durnit. The allocations caused the dict to resize.
978 * Just start over, this shouldn't normally happen.
979 */
980 Py_DECREF(v);
981 goto again;
982 }
Tim Petersafb6ae82001-06-04 21:00:21 +0000983 for (i = 0, j = 0; i <= mp->ma_mask; i++) {
Guido van Rossum25831651993-05-19 14:50:45 +0000984 if (mp->ma_table[i].me_value != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000985 PyObject *value = mp->ma_table[i].me_value;
986 Py_INCREF(value);
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000987 PyList_SET_ITEM(v, j, value);
Guido van Rossum25831651993-05-19 14:50:45 +0000988 j++;
989 }
990 }
991 return v;
992}
993
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000994static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +0000995dict_items(register dictobject *mp, PyObject *args)
Guido van Rossum25831651993-05-19 14:50:45 +0000996{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000997 register PyObject *v;
Guido van Rossuma4dd0112001-04-15 22:16:26 +0000998 register int i, j, n;
999 PyObject *item, *key, *value;
1000
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001001 if (!PyArg_NoArgs(args))
Guido van Rossum25831651993-05-19 14:50:45 +00001002 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001003 /* Preallocate the list of tuples, to avoid allocations during
1004 * the loop over the items, which could trigger GC, which
1005 * could resize the dict. :-(
1006 */
1007 again:
1008 n = mp->ma_used;
1009 v = PyList_New(n);
Guido van Rossum25831651993-05-19 14:50:45 +00001010 if (v == NULL)
1011 return NULL;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001012 for (i = 0; i < n; i++) {
1013 item = PyTuple_New(2);
1014 if (item == NULL) {
1015 Py_DECREF(v);
1016 return NULL;
1017 }
1018 PyList_SET_ITEM(v, i, item);
1019 }
1020 if (n != mp->ma_used) {
1021 /* Durnit. The allocations caused the dict to resize.
1022 * Just start over, this shouldn't normally happen.
1023 */
1024 Py_DECREF(v);
1025 goto again;
1026 }
1027 /* Nothing we do below makes any function calls. */
Tim Petersafb6ae82001-06-04 21:00:21 +00001028 for (i = 0, j = 0; i <= mp->ma_mask; i++) {
Guido van Rossum25831651993-05-19 14:50:45 +00001029 if (mp->ma_table[i].me_value != NULL) {
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001030 key = mp->ma_table[i].me_key;
1031 value = mp->ma_table[i].me_value;
1032 item = PyList_GET_ITEM(v, j);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001033 Py_INCREF(key);
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001034 PyTuple_SET_ITEM(item, 0, key);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001035 Py_INCREF(value);
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001036 PyTuple_SET_ITEM(item, 1, value);
Guido van Rossum25831651993-05-19 14:50:45 +00001037 j++;
1038 }
1039 }
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001040 assert(j == n);
Guido van Rossum25831651993-05-19 14:50:45 +00001041 return v;
1042}
1043
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001044static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001045dict_update(register dictobject *mp, PyObject *args)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001046{
1047 register int i;
1048 dictobject *other;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001049 dictentry *entry;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001050 if (!PyArg_Parse(args, "O!", &PyDict_Type, &other))
1051 return NULL;
Jeremy Hylton1fb60882001-01-03 22:34:59 +00001052 if (other == mp || other->ma_used == 0)
1053 goto done; /* a.update(a) or a.update({}); nothing to do */
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001054 /* Do one big resize at the start, rather than incrementally
1055 resizing as we insert new items. Expect that there will be
1056 no (or few) overlapping keys. */
Tim Petersafb6ae82001-06-04 21:00:21 +00001057 if ((mp->ma_fill + other->ma_used)*3 >= (mp->ma_mask+1)*2) {
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001058 if (dictresize(mp, (mp->ma_used + other->ma_used)*3/2) != 0)
1059 return NULL;
1060 }
Tim Petersafb6ae82001-06-04 21:00:21 +00001061 for (i = 0; i <= other->ma_mask; i++) {
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001062 entry = &other->ma_table[i];
1063 if (entry->me_value != NULL) {
1064 Py_INCREF(entry->me_key);
1065 Py_INCREF(entry->me_value);
1066 insertdict(mp, entry->me_key, entry->me_hash,
1067 entry->me_value);
1068 }
1069 }
1070 done:
1071 Py_INCREF(Py_None);
1072 return Py_None;
1073}
1074
1075static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001076dict_copy(register dictobject *mp, PyObject *args)
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001077{
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001078 if (!PyArg_Parse(args, ""))
1079 return NULL;
1080 return PyDict_Copy((PyObject*)mp);
1081}
1082
1083PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001084PyDict_Copy(PyObject *o)
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001085{
1086 register dictobject *mp;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001087 register int i;
1088 dictobject *copy;
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001089 dictentry *entry;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001090
1091 if (o == NULL || !PyDict_Check(o)) {
1092 PyErr_BadInternalCall();
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001093 return NULL;
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00001094 }
1095 mp = (dictobject *)o;
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001096 copy = (dictobject *)PyDict_New();
1097 if (copy == NULL)
1098 return NULL;
1099 if (mp->ma_used > 0) {
1100 if (dictresize(copy, mp->ma_used*3/2) != 0)
1101 return NULL;
Tim Petersafb6ae82001-06-04 21:00:21 +00001102 for (i = 0; i <= mp->ma_mask; i++) {
Guido van Rossume3f5b9c1997-05-28 19:15:28 +00001103 entry = &mp->ma_table[i];
1104 if (entry->me_value != NULL) {
1105 Py_INCREF(entry->me_key);
1106 Py_INCREF(entry->me_value);
1107 insertdict(copy, entry->me_key, entry->me_hash,
1108 entry->me_value);
1109 }
1110 }
1111 }
1112 return (PyObject *)copy;
1113}
1114
Guido van Rossum4199fac1993-11-05 10:18:44 +00001115int
Tim Peters1f5871e2000-07-04 17:44:48 +00001116PyDict_Size(PyObject *mp)
Guido van Rossum4199fac1993-11-05 10:18:44 +00001117{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001118 if (mp == NULL || !PyDict_Check(mp)) {
1119 PyErr_BadInternalCall();
Guido van Rossumb376a4a1993-11-23 17:53:17 +00001120 return 0;
Guido van Rossum4199fac1993-11-05 10:18:44 +00001121 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001122 return ((dictobject *)mp)->ma_used;
Guido van Rossum4199fac1993-11-05 10:18:44 +00001123}
1124
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001125PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001126PyDict_Keys(PyObject *mp)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001127{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001128 if (mp == NULL || !PyDict_Check(mp)) {
1129 PyErr_BadInternalCall();
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001130 return NULL;
1131 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001132 return dict_keys((dictobject *)mp, (PyObject *)NULL);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001133}
1134
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001135PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001136PyDict_Values(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001137{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001138 if (mp == NULL || !PyDict_Check(mp)) {
1139 PyErr_BadInternalCall();
Guido van Rossum25831651993-05-19 14:50:45 +00001140 return NULL;
1141 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001142 return dict_values((dictobject *)mp, (PyObject *)NULL);
Guido van Rossum25831651993-05-19 14:50:45 +00001143}
1144
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001145PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001146PyDict_Items(PyObject *mp)
Guido van Rossum25831651993-05-19 14:50:45 +00001147{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001148 if (mp == NULL || !PyDict_Check(mp)) {
1149 PyErr_BadInternalCall();
Guido van Rossum25831651993-05-19 14:50:45 +00001150 return NULL;
1151 }
Guido van Rossuma9e7a811997-05-13 21:02:11 +00001152 return dict_items((dictobject *)mp, (PyObject *)NULL);
Guido van Rossum25831651993-05-19 14:50:45 +00001153}
1154
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001155/* Subroutine which returns the smallest key in a for which b's value
1156 is different or absent. The value is returned too, through the
Tim Peters95bf9392001-05-10 08:32:44 +00001157 pval argument. Both are NULL if no key in a is found for which b's status
1158 differs. The refcounts on (and only on) non-NULL *pval and function return
1159 values must be decremented by the caller (characterize() increments them
1160 to ensure that mutating comparison and PyDict_GetItem calls can't delete
1161 them before the caller is done looking at them). */
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001162
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001163static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001164characterize(dictobject *a, dictobject *b, PyObject **pval)
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001165{
Tim Peters95bf9392001-05-10 08:32:44 +00001166 PyObject *akey = NULL; /* smallest key in a s.t. a[akey] != b[akey] */
1167 PyObject *aval = NULL; /* a[akey] */
Guido van Rossumb9324202001-01-18 00:39:02 +00001168 int i, cmp;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001169
Tim Petersafb6ae82001-06-04 21:00:21 +00001170 for (i = 0; i <= a->ma_mask; i++) {
Tim Peters95bf9392001-05-10 08:32:44 +00001171 PyObject *thiskey, *thisaval, *thisbval;
1172 if (a->ma_table[i].me_value == NULL)
1173 continue;
1174 thiskey = a->ma_table[i].me_key;
1175 Py_INCREF(thiskey); /* keep alive across compares */
1176 if (akey != NULL) {
1177 cmp = PyObject_RichCompareBool(akey, thiskey, Py_LT);
1178 if (cmp < 0) {
1179 Py_DECREF(thiskey);
1180 goto Fail;
1181 }
1182 if (cmp > 0 ||
Tim Petersafb6ae82001-06-04 21:00:21 +00001183 i > a->ma_mask ||
Tim Peters95bf9392001-05-10 08:32:44 +00001184 a->ma_table[i].me_value == NULL)
1185 {
1186 /* Not the *smallest* a key; or maybe it is
1187 * but the compare shrunk the dict so we can't
1188 * find its associated value anymore; or
1189 * maybe it is but the compare deleted the
1190 * a[thiskey] entry.
1191 */
1192 Py_DECREF(thiskey);
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001193 continue;
Guido van Rossumb9324202001-01-18 00:39:02 +00001194 }
Tim Peters95bf9392001-05-10 08:32:44 +00001195 }
1196
1197 /* Compare a[thiskey] to b[thiskey]; cmp <- true iff equal. */
1198 thisaval = a->ma_table[i].me_value;
1199 assert(thisaval);
1200 Py_INCREF(thisaval); /* keep alive */
1201 thisbval = PyDict_GetItem((PyObject *)b, thiskey);
1202 if (thisbval == NULL)
1203 cmp = 0;
1204 else {
1205 /* both dicts have thiskey: same values? */
1206 cmp = PyObject_RichCompareBool(
1207 thisaval, thisbval, Py_EQ);
1208 if (cmp < 0) {
1209 Py_DECREF(thiskey);
1210 Py_DECREF(thisaval);
1211 goto Fail;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001212 }
1213 }
Tim Peters95bf9392001-05-10 08:32:44 +00001214 if (cmp == 0) {
1215 /* New winner. */
1216 Py_XDECREF(akey);
1217 Py_XDECREF(aval);
1218 akey = thiskey;
1219 aval = thisaval;
1220 }
1221 else {
1222 Py_DECREF(thiskey);
1223 Py_DECREF(thisaval);
1224 }
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001225 }
Tim Peters95bf9392001-05-10 08:32:44 +00001226 *pval = aval;
1227 return akey;
1228
1229Fail:
1230 Py_XDECREF(akey);
1231 Py_XDECREF(aval);
1232 *pval = NULL;
1233 return NULL;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001234}
1235
1236static int
Tim Peters1f5871e2000-07-04 17:44:48 +00001237dict_compare(dictobject *a, dictobject *b)
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001238{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001239 PyObject *adiff, *bdiff, *aval, *bval;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001240 int res;
1241
1242 /* Compare lengths first */
1243 if (a->ma_used < b->ma_used)
1244 return -1; /* a is shorter */
1245 else if (a->ma_used > b->ma_used)
1246 return 1; /* b is shorter */
Tim Peters95bf9392001-05-10 08:32:44 +00001247
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001248 /* Same length -- check all keys */
Tim Peters95bf9392001-05-10 08:32:44 +00001249 bdiff = bval = NULL;
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001250 adiff = characterize(a, b, &aval);
Tim Peters95bf9392001-05-10 08:32:44 +00001251 if (adiff == NULL) {
1252 assert(!aval);
Tim Peters3918fb22001-05-10 18:58:31 +00001253 /* Either an error, or a is a subset with the same length so
Tim Peters95bf9392001-05-10 08:32:44 +00001254 * must be equal.
1255 */
1256 res = PyErr_Occurred() ? -1 : 0;
1257 goto Finished;
1258 }
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001259 bdiff = characterize(b, a, &bval);
Tim Peters95bf9392001-05-10 08:32:44 +00001260 if (bdiff == NULL && PyErr_Occurred()) {
1261 assert(!bval);
1262 res = -1;
1263 goto Finished;
1264 }
1265 res = 0;
1266 if (bdiff) {
1267 /* bdiff == NULL "should be" impossible now, but perhaps
1268 * the last comparison done by the characterize() on a had
1269 * the side effect of making the dicts equal!
1270 */
1271 res = PyObject_Compare(adiff, bdiff);
1272 }
1273 if (res == 0 && bval != NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001274 res = PyObject_Compare(aval, bval);
Tim Peters95bf9392001-05-10 08:32:44 +00001275
1276Finished:
1277 Py_XDECREF(adiff);
1278 Py_XDECREF(bdiff);
1279 Py_XDECREF(aval);
1280 Py_XDECREF(bval);
Guido van Rossuma0a69b81996-12-05 21:55:55 +00001281 return res;
1282}
1283
Tim Peterse63415e2001-05-08 04:38:29 +00001284/* Return 1 if dicts equal, 0 if not, -1 if error.
1285 * Gets out as soon as any difference is detected.
1286 * Uses only Py_EQ comparison.
1287 */
1288static int
1289dict_equal(dictobject *a, dictobject *b)
1290{
1291 int i;
1292
1293 if (a->ma_used != b->ma_used)
1294 /* can't be equal if # of entries differ */
1295 return 0;
Tim Peterseb28ef22001-06-02 05:27:19 +00001296
Tim Peterse63415e2001-05-08 04:38:29 +00001297 /* Same # of entries -- check all of 'em. Exit early on any diff. */
Tim Petersafb6ae82001-06-04 21:00:21 +00001298 for (i = 0; i <= a->ma_mask; i++) {
Tim Peterse63415e2001-05-08 04:38:29 +00001299 PyObject *aval = a->ma_table[i].me_value;
1300 if (aval != NULL) {
1301 int cmp;
1302 PyObject *bval;
1303 PyObject *key = a->ma_table[i].me_key;
1304 /* temporarily bump aval's refcount to ensure it stays
1305 alive until we're done with it */
1306 Py_INCREF(aval);
1307 bval = PyDict_GetItem((PyObject *)b, key);
1308 if (bval == NULL) {
1309 Py_DECREF(aval);
1310 return 0;
1311 }
1312 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
1313 Py_DECREF(aval);
1314 if (cmp <= 0) /* error or not equal */
1315 return cmp;
1316 }
1317 }
1318 return 1;
1319 }
1320
1321static PyObject *
1322dict_richcompare(PyObject *v, PyObject *w, int op)
1323{
1324 int cmp;
1325 PyObject *res;
1326
1327 if (!PyDict_Check(v) || !PyDict_Check(w)) {
1328 res = Py_NotImplemented;
1329 }
1330 else if (op == Py_EQ || op == Py_NE) {
1331 cmp = dict_equal((dictobject *)v, (dictobject *)w);
1332 if (cmp < 0)
1333 return NULL;
1334 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
1335 }
Tim Peters4fa58bf2001-05-10 21:45:19 +00001336 else
1337 res = Py_NotImplemented;
Tim Peterse63415e2001-05-08 04:38:29 +00001338 Py_INCREF(res);
1339 return res;
1340 }
1341
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001342static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001343dict_has_key(register dictobject *mp, PyObject *args)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001344{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001345 PyObject *key;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001346 long hash;
1347 register long ok;
Fred Drake52fccfd2000-02-23 15:47:16 +00001348 if (!PyArg_ParseTuple(args, "O:has_key", &key))
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001349 return NULL;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +00001350#ifdef CACHE_HASH
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001351 if (!PyString_Check(key) ||
1352 (hash = ((PyStringObject *) key)->ob_shash) == -1)
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +00001353#endif
Guido van Rossumca756f21997-01-23 19:39:29 +00001354 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001355 hash = PyObject_Hash(key);
Guido van Rossumca756f21997-01-23 19:39:29 +00001356 if (hash == -1)
1357 return NULL;
1358 }
Tim Petersdea48ec2001-05-22 20:40:22 +00001359 ok = (mp->ma_lookup)(mp, key, hash)->me_value != NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001360 return PyInt_FromLong(ok);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001361}
1362
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001363static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001364dict_get(register dictobject *mp, PyObject *args)
Barry Warsawc38c5da1997-10-06 17:49:20 +00001365{
1366 PyObject *key;
Barry Warsaw320ac331997-10-20 17:26:25 +00001367 PyObject *failobj = Py_None;
Barry Warsawc38c5da1997-10-06 17:49:20 +00001368 PyObject *val = NULL;
1369 long hash;
1370
Fred Drake52fccfd2000-02-23 15:47:16 +00001371 if (!PyArg_ParseTuple(args, "O|O:get", &key, &failobj))
Barry Warsawc38c5da1997-10-06 17:49:20 +00001372 return NULL;
1373
Barry Warsawc38c5da1997-10-06 17:49:20 +00001374#ifdef CACHE_HASH
1375 if (!PyString_Check(key) ||
1376 (hash = ((PyStringObject *) key)->ob_shash) == -1)
1377#endif
1378 {
1379 hash = PyObject_Hash(key);
1380 if (hash == -1)
1381 return NULL;
1382 }
Fred Drake1bff34a2000-08-31 19:31:38 +00001383 val = (mp->ma_lookup)(mp, key, hash)->me_value;
Barry Warsaw320ac331997-10-20 17:26:25 +00001384
Barry Warsawc38c5da1997-10-06 17:49:20 +00001385 if (val == NULL)
1386 val = failobj;
1387 Py_INCREF(val);
1388 return val;
1389}
1390
1391
1392static PyObject *
Guido van Rossum164452c2000-08-08 16:12:54 +00001393dict_setdefault(register dictobject *mp, PyObject *args)
1394{
1395 PyObject *key;
1396 PyObject *failobj = Py_None;
1397 PyObject *val = NULL;
1398 long hash;
1399
1400 if (!PyArg_ParseTuple(args, "O|O:setdefault", &key, &failobj))
1401 return NULL;
Guido van Rossum164452c2000-08-08 16:12:54 +00001402
1403#ifdef CACHE_HASH
1404 if (!PyString_Check(key) ||
1405 (hash = ((PyStringObject *) key)->ob_shash) == -1)
1406#endif
1407 {
1408 hash = PyObject_Hash(key);
1409 if (hash == -1)
1410 return NULL;
1411 }
Fred Drake1bff34a2000-08-31 19:31:38 +00001412 val = (mp->ma_lookup)(mp, key, hash)->me_value;
Guido van Rossum164452c2000-08-08 16:12:54 +00001413 if (val == NULL) {
1414 val = failobj;
1415 if (PyDict_SetItem((PyObject*)mp, key, failobj))
1416 val = NULL;
1417 }
1418 Py_XINCREF(val);
1419 return val;
1420}
1421
1422
1423static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001424dict_clear(register dictobject *mp, PyObject *args)
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00001425{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001426 if (!PyArg_NoArgs(args))
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00001427 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001428 PyDict_Clear((PyObject *)mp);
1429 Py_INCREF(Py_None);
1430 return Py_None;
Guido van Rossumfb8f1ca1997-03-21 21:55:12 +00001431}
1432
Guido van Rossumba6ab842000-12-12 22:02:18 +00001433static PyObject *
1434dict_popitem(dictobject *mp, PyObject *args)
1435{
1436 int i = 0;
1437 dictentry *ep;
1438 PyObject *res;
1439
1440 if (!PyArg_NoArgs(args))
1441 return NULL;
Tim Petersf4b33f62001-06-02 05:42:29 +00001442 /* Allocate the result tuple before checking the size. Believe it
1443 * or not, this allocation could trigger a garbage collection which
1444 * could empty the dict, so if we checked the size first and that
1445 * happened, the result would be an infinite loop (searching for an
1446 * entry that no longer exists). Note that the usual popitem()
1447 * idiom is "while d: k, v = d.popitem()". so needing to throw the
1448 * tuple away if the dict *is* empty isn't a significant
1449 * inefficiency -- possible, but unlikely in practice.
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001450 */
1451 res = PyTuple_New(2);
1452 if (res == NULL)
1453 return NULL;
Guido van Rossume04eaec2001-04-16 00:02:32 +00001454 if (mp->ma_used == 0) {
1455 Py_DECREF(res);
1456 PyErr_SetString(PyExc_KeyError,
1457 "popitem(): dictionary is empty");
1458 return NULL;
1459 }
Guido van Rossumba6ab842000-12-12 22:02:18 +00001460 /* Set ep to "the first" dict entry with a value. We abuse the hash
1461 * field of slot 0 to hold a search finger:
1462 * If slot 0 has a value, use slot 0.
1463 * Else slot 0 is being used to hold a search finger,
1464 * and we use its hash value as the first index to look.
1465 */
1466 ep = &mp->ma_table[0];
1467 if (ep->me_value == NULL) {
1468 i = (int)ep->me_hash;
Tim Petersdea48ec2001-05-22 20:40:22 +00001469 /* The hash field may be a real hash value, or it may be a
1470 * legit search finger, or it may be a once-legit search
1471 * finger that's out of bounds now because it wrapped around
1472 * or the table shrunk -- simply make sure it's in bounds now.
Guido van Rossumba6ab842000-12-12 22:02:18 +00001473 */
Tim Petersafb6ae82001-06-04 21:00:21 +00001474 if (i > mp->ma_mask || i < 1)
Guido van Rossumba6ab842000-12-12 22:02:18 +00001475 i = 1; /* skip slot 0 */
1476 while ((ep = &mp->ma_table[i])->me_value == NULL) {
1477 i++;
Tim Petersafb6ae82001-06-04 21:00:21 +00001478 if (i > mp->ma_mask)
Guido van Rossumba6ab842000-12-12 22:02:18 +00001479 i = 1;
1480 }
1481 }
Guido van Rossuma4dd0112001-04-15 22:16:26 +00001482 PyTuple_SET_ITEM(res, 0, ep->me_key);
1483 PyTuple_SET_ITEM(res, 1, ep->me_value);
1484 Py_INCREF(dummy);
1485 ep->me_key = dummy;
1486 ep->me_value = NULL;
1487 mp->ma_used--;
1488 assert(mp->ma_table[0].me_value == NULL);
1489 mp->ma_table[0].me_hash = i + 1; /* next place to start */
Guido van Rossumba6ab842000-12-12 22:02:18 +00001490 return res;
1491}
1492
Jeremy Hylton8caad492000-06-23 14:18:11 +00001493static int
1494dict_traverse(PyObject *op, visitproc visit, void *arg)
1495{
1496 int i = 0, err;
1497 PyObject *pk;
1498 PyObject *pv;
1499
1500 while (PyDict_Next(op, &i, &pk, &pv)) {
1501 err = visit(pk, arg);
1502 if (err)
1503 return err;
1504 err = visit(pv, arg);
1505 if (err)
1506 return err;
1507 }
1508 return 0;
1509}
1510
1511static int
1512dict_tp_clear(PyObject *op)
1513{
1514 PyDict_Clear(op);
1515 return 0;
1516}
1517
Tim Petersf7f88b12000-12-13 23:18:45 +00001518
Guido van Rossum09e563a2001-05-01 12:10:21 +00001519staticforward PyObject *dictiter_new(dictobject *, binaryfunc);
1520
1521static PyObject *
1522select_key(PyObject *key, PyObject *value)
1523{
1524 Py_INCREF(key);
1525 return key;
1526}
1527
1528static PyObject *
1529select_value(PyObject *key, PyObject *value)
1530{
1531 Py_INCREF(value);
1532 return value;
1533}
1534
1535static PyObject *
1536select_item(PyObject *key, PyObject *value)
1537{
1538 PyObject *res = PyTuple_New(2);
1539
1540 if (res != NULL) {
1541 Py_INCREF(key);
1542 Py_INCREF(value);
1543 PyTuple_SET_ITEM(res, 0, key);
1544 PyTuple_SET_ITEM(res, 1, value);
1545 }
1546 return res;
1547}
1548
1549static PyObject *
1550dict_iterkeys(dictobject *dict, PyObject *args)
1551{
1552 if (!PyArg_ParseTuple(args, ""))
1553 return NULL;
1554 return dictiter_new(dict, select_key);
1555}
1556
1557static PyObject *
1558dict_itervalues(dictobject *dict, PyObject *args)
1559{
1560 if (!PyArg_ParseTuple(args, ""))
1561 return NULL;
1562 return dictiter_new(dict, select_value);
1563}
1564
1565static PyObject *
1566dict_iteritems(dictobject *dict, PyObject *args)
1567{
1568 if (!PyArg_ParseTuple(args, ""))
1569 return NULL;
1570 return dictiter_new(dict, select_item);
1571}
1572
1573
Tim Petersf7f88b12000-12-13 23:18:45 +00001574static char has_key__doc__[] =
1575"D.has_key(k) -> 1 if D has a key k, else 0";
1576
1577static char get__doc__[] =
1578"D.get(k[,d]) -> D[k] if D.has_key(k), else d. d defaults to None.";
1579
1580static char setdefault_doc__[] =
1581"D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if not D.has_key(k)";
1582
1583static char popitem__doc__[] =
1584"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
15852-tuple; but raise KeyError if D is empty";
1586
1587static char keys__doc__[] =
1588"D.keys() -> list of D's keys";
1589
1590static char items__doc__[] =
1591"D.items() -> list of D's (key, value) pairs, as 2-tuples";
1592
1593static char values__doc__[] =
1594"D.values() -> list of D's values";
1595
1596static char update__doc__[] =
1597"D.update(E) -> None. Update D from E: for k in E.keys(): D[k] = E[k]";
1598
1599static char clear__doc__[] =
1600"D.clear() -> None. Remove all items from D.";
1601
1602static char copy__doc__[] =
1603"D.copy() -> a shallow copy of D";
1604
Guido van Rossum09e563a2001-05-01 12:10:21 +00001605static char iterkeys__doc__[] =
1606"D.iterkeys() -> an iterator over the keys of D";
1607
1608static char itervalues__doc__[] =
1609"D.itervalues() -> an iterator over the values of D";
1610
1611static char iteritems__doc__[] =
1612"D.iteritems() -> an iterator over the (key, value) items of D";
1613
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001614static PyMethodDef mapp_methods[] = {
Tim Petersf7f88b12000-12-13 23:18:45 +00001615 {"has_key", (PyCFunction)dict_has_key, METH_VARARGS,
1616 has_key__doc__},
1617 {"get", (PyCFunction)dict_get, METH_VARARGS,
1618 get__doc__},
1619 {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS,
1620 setdefault_doc__},
1621 {"popitem", (PyCFunction)dict_popitem, METH_OLDARGS,
1622 popitem__doc__},
1623 {"keys", (PyCFunction)dict_keys, METH_OLDARGS,
1624 keys__doc__},
1625 {"items", (PyCFunction)dict_items, METH_OLDARGS,
1626 items__doc__},
1627 {"values", (PyCFunction)dict_values, METH_OLDARGS,
1628 values__doc__},
1629 {"update", (PyCFunction)dict_update, METH_OLDARGS,
1630 update__doc__},
1631 {"clear", (PyCFunction)dict_clear, METH_OLDARGS,
1632 clear__doc__},
1633 {"copy", (PyCFunction)dict_copy, METH_OLDARGS,
1634 copy__doc__},
Guido van Rossum09e563a2001-05-01 12:10:21 +00001635 {"iterkeys", (PyCFunction)dict_iterkeys, METH_VARARGS,
1636 iterkeys__doc__},
1637 {"itervalues", (PyCFunction)dict_itervalues, METH_VARARGS,
1638 itervalues__doc__},
1639 {"iteritems", (PyCFunction)dict_iteritems, METH_VARARGS,
1640 iteritems__doc__},
Tim Petersf7f88b12000-12-13 23:18:45 +00001641 {NULL, NULL} /* sentinel */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001642};
1643
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001644static PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001645dict_getattr(dictobject *mp, char *name)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001646{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001647 return Py_FindMethod(mapp_methods, (PyObject *)mp, name);
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001648}
1649
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001650static int
1651dict_contains(dictobject *mp, PyObject *key)
1652{
1653 long hash;
1654
1655#ifdef CACHE_HASH
1656 if (!PyString_Check(key) ||
1657 (hash = ((PyStringObject *) key)->ob_shash) == -1)
1658#endif
1659 {
1660 hash = PyObject_Hash(key);
1661 if (hash == -1)
1662 return -1;
1663 }
Tim Petersdea48ec2001-05-22 20:40:22 +00001664 return (mp->ma_lookup)(mp, key, hash)->me_value != NULL;
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001665}
1666
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001667/* Hack to implement "key in dict" */
1668static PySequenceMethods dict_as_sequence = {
1669 0, /* sq_length */
1670 0, /* sq_concat */
1671 0, /* sq_repeat */
1672 0, /* sq_item */
1673 0, /* sq_slice */
1674 0, /* sq_ass_item */
1675 0, /* sq_ass_slice */
1676 (objobjproc)dict_contains, /* sq_contains */
1677 0, /* sq_inplace_concat */
1678 0, /* sq_inplace_repeat */
1679};
1680
Guido van Rossum09e563a2001-05-01 12:10:21 +00001681static PyObject *
1682dict_iter(dictobject *dict)
1683{
1684 return dictiter_new(dict, select_key);
1685}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001686
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001687PyTypeObject PyDict_Type = {
1688 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001689 0,
Guido van Rossum9bfef441993-03-29 10:43:31 +00001690 "dictionary",
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001691 sizeof(dictobject) + PyGC_HEAD_SIZE,
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001692 0,
Guido van Rossumb9324202001-01-18 00:39:02 +00001693 (destructor)dict_dealloc, /* tp_dealloc */
1694 (printfunc)dict_print, /* tp_print */
1695 (getattrfunc)dict_getattr, /* tp_getattr */
1696 0, /* tp_setattr */
Tim Peters4fa58bf2001-05-10 21:45:19 +00001697 (cmpfunc)dict_compare, /* tp_compare */
Guido van Rossumb9324202001-01-18 00:39:02 +00001698 (reprfunc)dict_repr, /* tp_repr */
1699 0, /* tp_as_number */
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001700 &dict_as_sequence, /* tp_as_sequence */
Guido van Rossumb9324202001-01-18 00:39:02 +00001701 &dict_as_mapping, /* tp_as_mapping */
1702 0, /* tp_hash */
1703 0, /* tp_call */
1704 0, /* tp_str */
1705 0, /* tp_getattro */
1706 0, /* tp_setattro */
1707 0, /* tp_as_buffer */
1708 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /* tp_flags */
1709 0, /* tp_doc */
1710 (traverseproc)dict_traverse, /* tp_traverse */
1711 (inquiry)dict_tp_clear, /* tp_clear */
Tim Peterse63415e2001-05-08 04:38:29 +00001712 dict_richcompare, /* tp_richcompare */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001713 0, /* tp_weaklistoffset */
Guido van Rossum09e563a2001-05-01 12:10:21 +00001714 (getiterfunc)dict_iter, /* tp_iter */
Guido van Rossum213c7a62001-04-23 14:08:49 +00001715 0, /* tp_iternext */
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001716};
1717
Guido van Rossum3cca2451997-05-16 14:23:33 +00001718/* For backward compatibility with old dictionary interface */
1719
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001720PyObject *
Tim Peters1f5871e2000-07-04 17:44:48 +00001721PyDict_GetItemString(PyObject *v, char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001722{
Guido van Rossum3cca2451997-05-16 14:23:33 +00001723 PyObject *kv, *rv;
1724 kv = PyString_FromString(key);
1725 if (kv == NULL)
1726 return NULL;
Guido van Rossum3cca2451997-05-16 14:23:33 +00001727 rv = PyDict_GetItem(v, kv);
1728 Py_DECREF(kv);
1729 return rv;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001730}
1731
1732int
Tim Peters1f5871e2000-07-04 17:44:48 +00001733PyDict_SetItemString(PyObject *v, char *key, PyObject *item)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001734{
Guido van Rossum3cca2451997-05-16 14:23:33 +00001735 PyObject *kv;
1736 int err;
1737 kv = PyString_FromString(key);
1738 if (kv == NULL)
Guido van Rossum037b2201997-05-20 18:35:19 +00001739 return -1;
Guido van Rossum4f3bf1e1997-09-29 23:31:11 +00001740 PyString_InternInPlace(&kv); /* XXX Should we really? */
Guido van Rossum3cca2451997-05-16 14:23:33 +00001741 err = PyDict_SetItem(v, kv, item);
1742 Py_DECREF(kv);
1743 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001744}
1745
1746int
Tim Peters1f5871e2000-07-04 17:44:48 +00001747PyDict_DelItemString(PyObject *v, char *key)
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001748{
Guido van Rossum3cca2451997-05-16 14:23:33 +00001749 PyObject *kv;
1750 int err;
1751 kv = PyString_FromString(key);
1752 if (kv == NULL)
Guido van Rossum037b2201997-05-20 18:35:19 +00001753 return -1;
Guido van Rossum3cca2451997-05-16 14:23:33 +00001754 err = PyDict_DelItem(v, kv);
1755 Py_DECREF(kv);
1756 return err;
Guido van Rossum4b1302b1993-03-27 18:11:32 +00001757}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001758
1759/* Dictionary iterator type */
1760
1761extern PyTypeObject PyDictIter_Type; /* Forward */
1762
1763typedef struct {
1764 PyObject_HEAD
1765 dictobject *di_dict;
Guido van Rossumb1f35bf2001-05-02 15:13:44 +00001766 int di_used;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001767 int di_pos;
Guido van Rossum09e563a2001-05-01 12:10:21 +00001768 binaryfunc di_select;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001769} dictiterobject;
1770
1771static PyObject *
Guido van Rossum09e563a2001-05-01 12:10:21 +00001772dictiter_new(dictobject *dict, binaryfunc select)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001773{
1774 dictiterobject *di;
1775 di = PyObject_NEW(dictiterobject, &PyDictIter_Type);
1776 if (di == NULL)
1777 return NULL;
1778 Py_INCREF(dict);
1779 di->di_dict = dict;
Guido van Rossumb1f35bf2001-05-02 15:13:44 +00001780 di->di_used = dict->ma_used;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001781 di->di_pos = 0;
Guido van Rossum09e563a2001-05-01 12:10:21 +00001782 di->di_select = select;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001783 return (PyObject *)di;
1784}
1785
1786static void
1787dictiter_dealloc(dictiterobject *di)
1788{
1789 Py_DECREF(di->di_dict);
1790 PyObject_DEL(di);
1791}
1792
1793static PyObject *
1794dictiter_next(dictiterobject *di, PyObject *args)
1795{
Guido van Rossum09e563a2001-05-01 12:10:21 +00001796 PyObject *key, *value;
Guido van Rossum213c7a62001-04-23 14:08:49 +00001797
Guido van Rossumb1f35bf2001-05-02 15:13:44 +00001798 if (di->di_used != di->di_dict->ma_used) {
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001799 PyErr_SetString(PyExc_RuntimeError,
1800 "dictionary changed size during iteration");
1801 return NULL;
1802 }
Guido van Rossum09e563a2001-05-01 12:10:21 +00001803 if (PyDict_Next((PyObject *)(di->di_dict), &di->di_pos, &key, &value)) {
1804 return (*di->di_select)(key, value);
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001805 }
1806 PyErr_SetObject(PyExc_StopIteration, Py_None);
1807 return NULL;
1808}
1809
1810static PyObject *
1811dictiter_getiter(PyObject *it)
1812{
1813 Py_INCREF(it);
1814 return it;
1815}
1816
1817static PyMethodDef dictiter_methods[] = {
1818 {"next", (PyCFunction)dictiter_next, METH_VARARGS,
1819 "it.next() -- get the next value, or raise StopIteration"},
1820 {NULL, NULL} /* sentinel */
1821};
1822
1823static PyObject *
Guido van Rossum213c7a62001-04-23 14:08:49 +00001824dictiter_getattr(dictiterobject *di, char *name)
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001825{
Guido van Rossum213c7a62001-04-23 14:08:49 +00001826 return Py_FindMethod(dictiter_methods, (PyObject *)di, name);
1827}
1828
1829static PyObject *dictiter_iternext(dictiterobject *di)
1830{
Guido van Rossum09e563a2001-05-01 12:10:21 +00001831 PyObject *key, *value;
Guido van Rossum213c7a62001-04-23 14:08:49 +00001832
Guido van Rossumb1f35bf2001-05-02 15:13:44 +00001833 if (di->di_used != di->di_dict->ma_used) {
Guido van Rossum213c7a62001-04-23 14:08:49 +00001834 PyErr_SetString(PyExc_RuntimeError,
1835 "dictionary changed size during iteration");
1836 return NULL;
1837 }
Guido van Rossum09e563a2001-05-01 12:10:21 +00001838 if (PyDict_Next((PyObject *)(di->di_dict), &di->di_pos, &key, &value)) {
1839 return (*di->di_select)(key, value);
Guido van Rossum213c7a62001-04-23 14:08:49 +00001840 }
1841 return NULL;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001842}
1843
1844PyTypeObject PyDictIter_Type = {
1845 PyObject_HEAD_INIT(&PyType_Type)
1846 0, /* ob_size */
1847 "dictionary-iterator", /* tp_name */
1848 sizeof(dictiterobject), /* tp_basicsize */
1849 0, /* tp_itemsize */
1850 /* methods */
1851 (destructor)dictiter_dealloc, /* tp_dealloc */
1852 0, /* tp_print */
1853 (getattrfunc)dictiter_getattr, /* tp_getattr */
1854 0, /* tp_setattr */
1855 0, /* tp_compare */
1856 0, /* tp_repr */
1857 0, /* tp_as_number */
1858 0, /* tp_as_sequence */
1859 0, /* tp_as_mapping */
1860 0, /* tp_hash */
1861 0, /* tp_call */
1862 0, /* tp_str */
1863 0, /* tp_getattro */
1864 0, /* tp_setattro */
1865 0, /* tp_as_buffer */
1866 Py_TPFLAGS_DEFAULT, /* tp_flags */
1867 0, /* tp_doc */
1868 0, /* tp_traverse */
1869 0, /* tp_clear */
1870 0, /* tp_richcompare */
1871 0, /* tp_weaklistoffset */
1872 (getiterfunc)dictiter_getiter, /* tp_iter */
Guido van Rossum213c7a62001-04-23 14:08:49 +00001873 (iternextfunc)dictiter_iternext, /* tp_iternext */
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001874};