]> git.proxmox.com Git - mirror_edk2.git/blame - AppPkg/Applications/Python/Python-2.7.2/Objects/dictobject.c
EmbeddedPkg: Extend NvVarStoreFormattedLib LIBRARY_CLASS
[mirror_edk2.git] / AppPkg / Applications / Python / Python-2.7.2 / Objects / dictobject.c
CommitLineData
4710c53d 1\r
2/* Dictionary object implementation using a hash table */\r
3\r
4/* The distribution includes a separate file, Objects/dictnotes.txt,\r
5 describing explorations into dictionary design and optimization.\r
6 It covers typical dictionary use patterns, the parameters for\r
7 tuning dictionaries, and several ideas for possible optimizations.\r
8*/\r
9\r
10#include "Python.h"\r
11\r
12\r
13/* Set a key error with the specified argument, wrapping it in a\r
14 * tuple automatically so that tuple keys are not unpacked as the\r
15 * exception arguments. */\r
16static void\r
17set_key_error(PyObject *arg)\r
18{\r
19 PyObject *tup;\r
20 tup = PyTuple_Pack(1, arg);\r
21 if (!tup)\r
22 return; /* caller will expect error to be set anyway */\r
23 PyErr_SetObject(PyExc_KeyError, tup);\r
24 Py_DECREF(tup);\r
25}\r
26\r
27/* Define this out if you don't want conversion statistics on exit. */\r
28#undef SHOW_CONVERSION_COUNTS\r
29\r
30/* See large comment block below. This must be >= 1. */\r
31#define PERTURB_SHIFT 5\r
32\r
33/*\r
34Major subtleties ahead: Most hash schemes depend on having a "good" hash\r
35function, in the sense of simulating randomness. Python doesn't: its most\r
36important hash functions (for strings and ints) are very regular in common\r
37cases:\r
38\r
39>>> map(hash, (0, 1, 2, 3))\r
40[0, 1, 2, 3]\r
41>>> map(hash, ("namea", "nameb", "namec", "named"))\r
42[-1658398457, -1658398460, -1658398459, -1658398462]\r
43>>>\r
44\r
45This isn't necessarily bad! To the contrary, in a table of size 2**i, taking\r
46the low-order i bits as the initial table index is extremely fast, and there\r
47are no collisions at all for dicts indexed by a contiguous range of ints.\r
48The same is approximately true when keys are "consecutive" strings. So this\r
49gives better-than-random behavior in common cases, and that's very desirable.\r
50\r
51OTOH, when collisions occur, the tendency to fill contiguous slices of the\r
52hash table makes a good collision resolution strategy crucial. Taking only\r
53the last i bits of the hash code is also vulnerable: for example, consider\r
54[i << 16 for i in range(20000)] as a set of keys. Since ints are their own\r
55hash codes, and this fits in a dict of size 2**15, the last 15 bits of every\r
56hash code are all 0: they *all* map to the same table index.\r
57\r
58But catering to unusual cases should not slow the usual ones, so we just take\r
59the last i bits anyway. It's up to collision resolution to do the rest. If\r
60we *usually* find the key we're looking for on the first try (and, it turns\r
61out, we usually do -- the table load factor is kept under 2/3, so the odds\r
62are solidly in our favor), then it makes best sense to keep the initial index\r
63computation dirt cheap.\r
64\r
65The first half of collision resolution is to visit table indices via this\r
66recurrence:\r
67\r
68 j = ((5*j) + 1) mod 2**i\r
69\r
70For any initial j in range(2**i), repeating that 2**i times generates each\r
71int in range(2**i) exactly once (see any text on random-number generation for\r
72proof). By itself, this doesn't help much: like linear probing (setting\r
73j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed\r
74order. This would be bad, except that's not the only thing we do, and it's\r
75actually *good* in the common cases where hash keys are consecutive. In an\r
76example that's really too small to make this entirely clear, for a table of\r
77size 2**3 the order of indices is:\r
78\r
79 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]\r
80\r
81If two things come in at index 5, the first place we look after is index 2,\r
82not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.\r
83Linear probing is deadly in this case because there the fixed probe order\r
84is the *same* as the order consecutive keys are likely to arrive. But it's\r
85extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,\r
86and certain that consecutive hash codes do not.\r
87\r
88The other half of the strategy is to get the other bits of the hash code\r
89into play. This is done by initializing a (unsigned) vrbl "perturb" to the\r
90full hash code, and changing the recurrence to:\r
91\r
92 j = (5*j) + 1 + perturb;\r
93 perturb >>= PERTURB_SHIFT;\r
94 use j % 2**i as the next table index;\r
95\r
96Now the probe sequence depends (eventually) on every bit in the hash code,\r
97and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,\r
98because it quickly magnifies small differences in the bits that didn't affect\r
99the initial index. Note that because perturb is unsigned, if the recurrence\r
100is executed often enough perturb eventually becomes and remains 0. At that\r
101point (very rarely reached) the recurrence is on (just) 5*j+1 again, and\r
102that's certain to find an empty slot eventually (since it generates every int\r
103in range(2**i), and we make sure there's always at least one empty slot).\r
104\r
105Selecting a good value for PERTURB_SHIFT is a balancing act. You want it\r
106small so that the high bits of the hash code continue to affect the probe\r
107sequence across iterations; but you want it large so that in really bad cases\r
108the high-order hash bits have an effect on early iterations. 5 was "the\r
109best" in minimizing total collisions across experiments Tim Peters ran (on\r
110both normal and pathological cases), but 4 and 6 weren't significantly worse.\r
111\r
112Historical: Reimer Behrends contributed the idea of using a polynomial-based\r
113approach, using repeated multiplication by x in GF(2**n) where an irreducible\r
114polynomial for each table size was chosen such that x was a primitive root.\r
115Christian Tismer later extended that to use division by x instead, as an\r
116efficient way to get the high bits of the hash code into play. This scheme\r
117also gave excellent collision statistics, but was more expensive: two\r
118if-tests were required inside the loop; computing "the next" index took about\r
119the same number of operations but without as much potential parallelism\r
120(e.g., computing 5*j can go on at the same time as computing 1+perturb in the\r
121above, and then shifting perturb can be done while the table index is being\r
122masked); and the PyDictObject struct required a member to hold the table's\r
123polynomial. In Tim's experiments the current scheme ran faster, produced\r
124equally good collision statistics, needed less code & used less memory.\r
125\r
126Theoretical Python 2.5 headache: hash codes are only C "long", but\r
127sizeof(Py_ssize_t) > sizeof(long) may be possible. In that case, and if a\r
128dict is genuinely huge, then only the slots directly reachable via indexing\r
129by a C long can be the first slot in a probe sequence. The probe sequence\r
130will still eventually reach every slot in the table, but the collision rate\r
131on initial probes may be much higher than this scheme was designed for.\r
132Getting a hash code as fat as Py_ssize_t is the only real cure. But in\r
133practice, this probably won't make a lick of difference for many years (at\r
134which point everyone will have terabytes of RAM on 64-bit boxes).\r
135*/\r
136\r
137/* Object used as dummy key to fill deleted entries */\r
138static PyObject *dummy = NULL; /* Initialized by first call to newPyDictObject() */\r
139\r
140#ifdef Py_REF_DEBUG\r
141PyObject *\r
142_PyDict_Dummy(void)\r
143{\r
144 return dummy;\r
145}\r
146#endif\r
147\r
148/* forward declarations */\r
149static PyDictEntry *\r
150lookdict_string(PyDictObject *mp, PyObject *key, long hash);\r
151\r
152#ifdef SHOW_CONVERSION_COUNTS\r
153static long created = 0L;\r
154static long converted = 0L;\r
155\r
156static void\r
157show_counts(void)\r
158{\r
159 fprintf(stderr, "created %ld string dicts\n", created);\r
160 fprintf(stderr, "converted %ld to normal dicts\n", converted);\r
161 fprintf(stderr, "%.2f%% conversion rate\n", (100.0*converted)/created);\r
162}\r
163#endif\r
164\r
165/* Debug statistic to compare allocations with reuse through the free list */\r
166#undef SHOW_ALLOC_COUNT\r
167#ifdef SHOW_ALLOC_COUNT\r
168static size_t count_alloc = 0;\r
169static size_t count_reuse = 0;\r
170\r
171static void\r
172show_alloc(void)\r
173{\r
174 fprintf(stderr, "Dict allocations: %" PY_FORMAT_SIZE_T "d\n",\r
175 count_alloc);\r
176 fprintf(stderr, "Dict reuse through freelist: %" PY_FORMAT_SIZE_T\r
177 "d\n", count_reuse);\r
178 fprintf(stderr, "%.2f%% reuse rate\n\n",\r
179 (100.0*count_reuse/(count_alloc+count_reuse)));\r
180}\r
181#endif\r
182\r
183/* Debug statistic to count GC tracking of dicts */\r
184#ifdef SHOW_TRACK_COUNT\r
185static Py_ssize_t count_untracked = 0;\r
186static Py_ssize_t count_tracked = 0;\r
187\r
188static void\r
189show_track(void)\r
190{\r
191 fprintf(stderr, "Dicts created: %" PY_FORMAT_SIZE_T "d\n",\r
192 count_tracked + count_untracked);\r
193 fprintf(stderr, "Dicts tracked by the GC: %" PY_FORMAT_SIZE_T\r
194 "d\n", count_tracked);\r
195 fprintf(stderr, "%.2f%% dict tracking rate\n\n",\r
196 (100.0*count_tracked/(count_untracked+count_tracked)));\r
197}\r
198#endif\r
199\r
200\r
201/* Initialization macros.\r
202 There are two ways to create a dict: PyDict_New() is the main C API\r
203 function, and the tp_new slot maps to dict_new(). In the latter case we\r
204 can save a little time over what PyDict_New does because it's guaranteed\r
205 that the PyDictObject struct is already zeroed out.\r
206 Everyone except dict_new() should use EMPTY_TO_MINSIZE (unless they have\r
207 an excellent reason not to).\r
208*/\r
209\r
210#define INIT_NONZERO_DICT_SLOTS(mp) do { \\r
211 (mp)->ma_table = (mp)->ma_smalltable; \\r
212 (mp)->ma_mask = PyDict_MINSIZE - 1; \\r
213 } while(0)\r
214\r
215#define EMPTY_TO_MINSIZE(mp) do { \\r
216 memset((mp)->ma_smalltable, 0, sizeof((mp)->ma_smalltable)); \\r
217 (mp)->ma_used = (mp)->ma_fill = 0; \\r
218 INIT_NONZERO_DICT_SLOTS(mp); \\r
219 } while(0)\r
220\r
221/* Dictionary reuse scheme to save calls to malloc, free, and memset */\r
222#ifndef PyDict_MAXFREELIST\r
223#define PyDict_MAXFREELIST 80\r
224#endif\r
225static PyDictObject *free_list[PyDict_MAXFREELIST];\r
226static int numfree = 0;\r
227\r
228void\r
229PyDict_Fini(void)\r
230{\r
231 PyDictObject *op;\r
232\r
233 while (numfree) {\r
234 op = free_list[--numfree];\r
235 assert(PyDict_CheckExact(op));\r
236 PyObject_GC_Del(op);\r
237 }\r
238}\r
239\r
240PyObject *\r
241PyDict_New(void)\r
242{\r
243 register PyDictObject *mp;\r
244 if (dummy == NULL) { /* Auto-initialize dummy */\r
245 dummy = PyString_FromString("<dummy key>");\r
246 if (dummy == NULL)\r
247 return NULL;\r
248#ifdef SHOW_CONVERSION_COUNTS\r
249 Py_AtExit(show_counts);\r
250#endif\r
251#ifdef SHOW_ALLOC_COUNT\r
252 Py_AtExit(show_alloc);\r
253#endif\r
254#ifdef SHOW_TRACK_COUNT\r
255 Py_AtExit(show_track);\r
256#endif\r
257 }\r
258 if (numfree) {\r
259 mp = free_list[--numfree];\r
260 assert (mp != NULL);\r
261 assert (Py_TYPE(mp) == &PyDict_Type);\r
262 _Py_NewReference((PyObject *)mp);\r
263 if (mp->ma_fill) {\r
264 EMPTY_TO_MINSIZE(mp);\r
265 } else {\r
266 /* At least set ma_table and ma_mask; these are wrong\r
267 if an empty but presized dict is added to freelist */\r
268 INIT_NONZERO_DICT_SLOTS(mp);\r
269 }\r
270 assert (mp->ma_used == 0);\r
271 assert (mp->ma_table == mp->ma_smalltable);\r
272 assert (mp->ma_mask == PyDict_MINSIZE - 1);\r
273#ifdef SHOW_ALLOC_COUNT\r
274 count_reuse++;\r
275#endif\r
276 } else {\r
277 mp = PyObject_GC_New(PyDictObject, &PyDict_Type);\r
278 if (mp == NULL)\r
279 return NULL;\r
280 EMPTY_TO_MINSIZE(mp);\r
281#ifdef SHOW_ALLOC_COUNT\r
282 count_alloc++;\r
283#endif\r
284 }\r
285 mp->ma_lookup = lookdict_string;\r
286#ifdef SHOW_TRACK_COUNT\r
287 count_untracked++;\r
288#endif\r
289#ifdef SHOW_CONVERSION_COUNTS\r
290 ++created;\r
291#endif\r
292 return (PyObject *)mp;\r
293}\r
294\r
295/*\r
296The basic lookup function used by all operations.\r
297This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.\r
298Open addressing is preferred over chaining since the link overhead for\r
299chaining would be substantial (100% with typical malloc overhead).\r
300\r
301The initial probe index is computed as hash mod the table size. Subsequent\r
302probe indices are computed as explained earlier.\r
303\r
304All arithmetic on hash should ignore overflow.\r
305\r
306(The details in this version are due to Tim Peters, building on many past\r
307contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and\r
308Christian Tismer).\r
309\r
310lookdict() is general-purpose, and may return NULL if (and only if) a\r
311comparison raises an exception (this was new in Python 2.5).\r
312lookdict_string() below is specialized to string keys, comparison of which can\r
313never raise an exception; that function can never return NULL. For both, when\r
314the key isn't found a PyDictEntry* is returned for which the me_value field is\r
315NULL; this is the slot in the dict at which the key would have been found, and\r
316the caller can (if it wishes) add the <key, value> pair to the returned\r
317PyDictEntry*.\r
318*/\r
319static PyDictEntry *\r
320lookdict(PyDictObject *mp, PyObject *key, register long hash)\r
321{\r
322 register size_t i;\r
323 register size_t perturb;\r
324 register PyDictEntry *freeslot;\r
325 register size_t mask = (size_t)mp->ma_mask;\r
326 PyDictEntry *ep0 = mp->ma_table;\r
327 register PyDictEntry *ep;\r
328 register int cmp;\r
329 PyObject *startkey;\r
330\r
331 i = (size_t)hash & mask;\r
332 ep = &ep0[i];\r
333 if (ep->me_key == NULL || ep->me_key == key)\r
334 return ep;\r
335\r
336 if (ep->me_key == dummy)\r
337 freeslot = ep;\r
338 else {\r
339 if (ep->me_hash == hash) {\r
340 startkey = ep->me_key;\r
341 Py_INCREF(startkey);\r
342 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);\r
343 Py_DECREF(startkey);\r
344 if (cmp < 0)\r
345 return NULL;\r
346 if (ep0 == mp->ma_table && ep->me_key == startkey) {\r
347 if (cmp > 0)\r
348 return ep;\r
349 }\r
350 else {\r
351 /* The compare did major nasty stuff to the\r
352 * dict: start over.\r
353 * XXX A clever adversary could prevent this\r
354 * XXX from terminating.\r
355 */\r
356 return lookdict(mp, key, hash);\r
357 }\r
358 }\r
359 freeslot = NULL;\r
360 }\r
361\r
362 /* In the loop, me_key == dummy is by far (factor of 100s) the\r
363 least likely outcome, so test for that last. */\r
364 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {\r
365 i = (i << 2) + i + perturb + 1;\r
366 ep = &ep0[i & mask];\r
367 if (ep->me_key == NULL)\r
368 return freeslot == NULL ? ep : freeslot;\r
369 if (ep->me_key == key)\r
370 return ep;\r
371 if (ep->me_hash == hash && ep->me_key != dummy) {\r
372 startkey = ep->me_key;\r
373 Py_INCREF(startkey);\r
374 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);\r
375 Py_DECREF(startkey);\r
376 if (cmp < 0)\r
377 return NULL;\r
378 if (ep0 == mp->ma_table && ep->me_key == startkey) {\r
379 if (cmp > 0)\r
380 return ep;\r
381 }\r
382 else {\r
383 /* The compare did major nasty stuff to the\r
384 * dict: start over.\r
385 * XXX A clever adversary could prevent this\r
386 * XXX from terminating.\r
387 */\r
388 return lookdict(mp, key, hash);\r
389 }\r
390 }\r
391 else if (ep->me_key == dummy && freeslot == NULL)\r
392 freeslot = ep;\r
393 }\r
394 assert(0); /* NOT REACHED */\r
395 return 0;\r
396}\r
397\r
398/*\r
399 * Hacked up version of lookdict which can assume keys are always strings;\r
400 * this assumption allows testing for errors during PyObject_RichCompareBool()\r
401 * to be dropped; string-string comparisons never raise exceptions. This also\r
402 * means we don't need to go through PyObject_RichCompareBool(); we can always\r
403 * use _PyString_Eq() directly.\r
404 *\r
405 * This is valuable because dicts with only string keys are very common.\r
406 */\r
407static PyDictEntry *\r
408lookdict_string(PyDictObject *mp, PyObject *key, register long hash)\r
409{\r
410 register size_t i;\r
411 register size_t perturb;\r
412 register PyDictEntry *freeslot;\r
413 register size_t mask = (size_t)mp->ma_mask;\r
414 PyDictEntry *ep0 = mp->ma_table;\r
415 register PyDictEntry *ep;\r
416\r
417 /* Make sure this function doesn't have to handle non-string keys,\r
418 including subclasses of str; e.g., one reason to subclass\r
419 strings is to override __eq__, and for speed we don't cater to\r
420 that here. */\r
421 if (!PyString_CheckExact(key)) {\r
422#ifdef SHOW_CONVERSION_COUNTS\r
423 ++converted;\r
424#endif\r
425 mp->ma_lookup = lookdict;\r
426 return lookdict(mp, key, hash);\r
427 }\r
428 i = hash & mask;\r
429 ep = &ep0[i];\r
430 if (ep->me_key == NULL || ep->me_key == key)\r
431 return ep;\r
432 if (ep->me_key == dummy)\r
433 freeslot = ep;\r
434 else {\r
435 if (ep->me_hash == hash && _PyString_Eq(ep->me_key, key))\r
436 return ep;\r
437 freeslot = NULL;\r
438 }\r
439\r
440 /* In the loop, me_key == dummy is by far (factor of 100s) the\r
441 least likely outcome, so test for that last. */\r
442 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {\r
443 i = (i << 2) + i + perturb + 1;\r
444 ep = &ep0[i & mask];\r
445 if (ep->me_key == NULL)\r
446 return freeslot == NULL ? ep : freeslot;\r
447 if (ep->me_key == key\r
448 || (ep->me_hash == hash\r
449 && ep->me_key != dummy\r
450 && _PyString_Eq(ep->me_key, key)))\r
451 return ep;\r
452 if (ep->me_key == dummy && freeslot == NULL)\r
453 freeslot = ep;\r
454 }\r
455 assert(0); /* NOT REACHED */\r
456 return 0;\r
457}\r
458\r
459#ifdef SHOW_TRACK_COUNT\r
460#define INCREASE_TRACK_COUNT \\r
461 (count_tracked++, count_untracked--);\r
462#define DECREASE_TRACK_COUNT \\r
463 (count_tracked--, count_untracked++);\r
464#else\r
465#define INCREASE_TRACK_COUNT\r
466#define DECREASE_TRACK_COUNT\r
467#endif\r
468\r
469#define MAINTAIN_TRACKING(mp, key, value) \\r
470 do { \\r
471 if (!_PyObject_GC_IS_TRACKED(mp)) { \\r
472 if (_PyObject_GC_MAY_BE_TRACKED(key) || \\r
473 _PyObject_GC_MAY_BE_TRACKED(value)) { \\r
474 _PyObject_GC_TRACK(mp); \\r
475 INCREASE_TRACK_COUNT \\r
476 } \\r
477 } \\r
478 } while(0)\r
479\r
480void\r
481_PyDict_MaybeUntrack(PyObject *op)\r
482{\r
483 PyDictObject *mp;\r
484 PyObject *value;\r
485 Py_ssize_t mask, i;\r
486 PyDictEntry *ep;\r
487\r
488 if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))\r
489 return;\r
490\r
491 mp = (PyDictObject *) op;\r
492 ep = mp->ma_table;\r
493 mask = mp->ma_mask;\r
494 for (i = 0; i <= mask; i++) {\r
495 if ((value = ep[i].me_value) == NULL)\r
496 continue;\r
497 if (_PyObject_GC_MAY_BE_TRACKED(value) ||\r
498 _PyObject_GC_MAY_BE_TRACKED(ep[i].me_key))\r
499 return;\r
500 }\r
501 DECREASE_TRACK_COUNT\r
502 _PyObject_GC_UNTRACK(op);\r
503}\r
504\r
505\r
506/*\r
507Internal routine to insert a new item into the table.\r
508Used both by the internal resize routine and by the public insert routine.\r
509Eats a reference to key and one to value.\r
510Returns -1 if an error occurred, or 0 on success.\r
511*/\r
512static int\r
513insertdict(register PyDictObject *mp, PyObject *key, long hash, PyObject *value)\r
514{\r
515 PyObject *old_value;\r
516 register PyDictEntry *ep;\r
517 typedef PyDictEntry *(*lookupfunc)(PyDictObject *, PyObject *, long);\r
518\r
519 assert(mp->ma_lookup != NULL);\r
520 ep = mp->ma_lookup(mp, key, hash);\r
521 if (ep == NULL) {\r
522 Py_DECREF(key);\r
523 Py_DECREF(value);\r
524 return -1;\r
525 }\r
526 MAINTAIN_TRACKING(mp, key, value);\r
527 if (ep->me_value != NULL) {\r
528 old_value = ep->me_value;\r
529 ep->me_value = value;\r
530 Py_DECREF(old_value); /* which **CAN** re-enter */\r
531 Py_DECREF(key);\r
532 }\r
533 else {\r
534 if (ep->me_key == NULL)\r
535 mp->ma_fill++;\r
536 else {\r
537 assert(ep->me_key == dummy);\r
538 Py_DECREF(dummy);\r
539 }\r
540 ep->me_key = key;\r
541 ep->me_hash = (Py_ssize_t)hash;\r
542 ep->me_value = value;\r
543 mp->ma_used++;\r
544 }\r
545 return 0;\r
546}\r
547\r
548/*\r
549Internal routine used by dictresize() to insert an item which is\r
550known to be absent from the dict. This routine also assumes that\r
551the dict contains no deleted entries. Besides the performance benefit,\r
552using insertdict() in dictresize() is dangerous (SF bug #1456209).\r
553Note that no refcounts are changed by this routine; if needed, the caller\r
554is responsible for incref'ing `key` and `value`.\r
555*/\r
556static void\r
557insertdict_clean(register PyDictObject *mp, PyObject *key, long hash,\r
558 PyObject *value)\r
559{\r
560 register size_t i;\r
561 register size_t perturb;\r
562 register size_t mask = (size_t)mp->ma_mask;\r
563 PyDictEntry *ep0 = mp->ma_table;\r
564 register PyDictEntry *ep;\r
565\r
566 MAINTAIN_TRACKING(mp, key, value);\r
567 i = hash & mask;\r
568 ep = &ep0[i];\r
569 for (perturb = hash; ep->me_key != NULL; perturb >>= PERTURB_SHIFT) {\r
570 i = (i << 2) + i + perturb + 1;\r
571 ep = &ep0[i & mask];\r
572 }\r
573 assert(ep->me_value == NULL);\r
574 mp->ma_fill++;\r
575 ep->me_key = key;\r
576 ep->me_hash = (Py_ssize_t)hash;\r
577 ep->me_value = value;\r
578 mp->ma_used++;\r
579}\r
580\r
581/*\r
582Restructure the table by allocating a new table and reinserting all\r
583items again. When entries have been deleted, the new table may\r
584actually be smaller than the old one.\r
585*/\r
586static int\r
587dictresize(PyDictObject *mp, Py_ssize_t minused)\r
588{\r
589 Py_ssize_t newsize;\r
590 PyDictEntry *oldtable, *newtable, *ep;\r
591 Py_ssize_t i;\r
592 int is_oldtable_malloced;\r
593 PyDictEntry small_copy[PyDict_MINSIZE];\r
594\r
595 assert(minused >= 0);\r
596\r
597 /* Find the smallest table size > minused. */\r
598 for (newsize = PyDict_MINSIZE;\r
599 newsize <= minused && newsize > 0;\r
600 newsize <<= 1)\r
601 ;\r
602 if (newsize <= 0) {\r
603 PyErr_NoMemory();\r
604 return -1;\r
605 }\r
606\r
607 /* Get space for a new table. */\r
608 oldtable = mp->ma_table;\r
609 assert(oldtable != NULL);\r
610 is_oldtable_malloced = oldtable != mp->ma_smalltable;\r
611\r
612 if (newsize == PyDict_MINSIZE) {\r
613 /* A large table is shrinking, or we can't get any smaller. */\r
614 newtable = mp->ma_smalltable;\r
615 if (newtable == oldtable) {\r
616 if (mp->ma_fill == mp->ma_used) {\r
617 /* No dummies, so no point doing anything. */\r
618 return 0;\r
619 }\r
620 /* We're not going to resize it, but rebuild the\r
621 table anyway to purge old dummy entries.\r
622 Subtle: This is *necessary* if fill==size,\r
623 as lookdict needs at least one virgin slot to\r
624 terminate failing searches. If fill < size, it's\r
625 merely desirable, as dummies slow searches. */\r
626 assert(mp->ma_fill > mp->ma_used);\r
627 memcpy(small_copy, oldtable, sizeof(small_copy));\r
628 oldtable = small_copy;\r
629 }\r
630 }\r
631 else {\r
632 newtable = PyMem_NEW(PyDictEntry, newsize);\r
633 if (newtable == NULL) {\r
634 PyErr_NoMemory();\r
635 return -1;\r
636 }\r
637 }\r
638\r
639 /* Make the dict empty, using the new table. */\r
640 assert(newtable != oldtable);\r
641 mp->ma_table = newtable;\r
642 mp->ma_mask = newsize - 1;\r
643 memset(newtable, 0, sizeof(PyDictEntry) * newsize);\r
644 mp->ma_used = 0;\r
645 i = mp->ma_fill;\r
646 mp->ma_fill = 0;\r
647\r
648 /* Copy the data over; this is refcount-neutral for active entries;\r
649 dummy entries aren't copied over, of course */\r
650 for (ep = oldtable; i > 0; ep++) {\r
651 if (ep->me_value != NULL) { /* active entry */\r
652 --i;\r
653 insertdict_clean(mp, ep->me_key, (long)ep->me_hash,\r
654 ep->me_value);\r
655 }\r
656 else if (ep->me_key != NULL) { /* dummy entry */\r
657 --i;\r
658 assert(ep->me_key == dummy);\r
659 Py_DECREF(ep->me_key);\r
660 }\r
661 /* else key == value == NULL: nothing to do */\r
662 }\r
663\r
664 if (is_oldtable_malloced)\r
665 PyMem_DEL(oldtable);\r
666 return 0;\r
667}\r
668\r
669/* Create a new dictionary pre-sized to hold an estimated number of elements.\r
670 Underestimates are okay because the dictionary will resize as necessary.\r
671 Overestimates just mean the dictionary will be more sparse than usual.\r
672*/\r
673\r
674PyObject *\r
675_PyDict_NewPresized(Py_ssize_t minused)\r
676{\r
677 PyObject *op = PyDict_New();\r
678\r
679 if (minused>5 && op != NULL && dictresize((PyDictObject *)op, minused) == -1) {\r
680 Py_DECREF(op);\r
681 return NULL;\r
682 }\r
683 return op;\r
684}\r
685\r
686/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors\r
687 * that may occur (originally dicts supported only string keys, and exceptions\r
688 * weren't possible). So, while the original intent was that a NULL return\r
689 * meant the key wasn't present, in reality it can mean that, or that an error\r
690 * (suppressed) occurred while computing the key's hash, or that some error\r
691 * (suppressed) occurred when comparing keys in the dict's internal probe\r
692 * sequence. A nasty example of the latter is when a Python-coded comparison\r
693 * function hits a stack-depth error, which can cause this to return NULL\r
694 * even if the key is present.\r
695 */\r
696PyObject *\r
697PyDict_GetItem(PyObject *op, PyObject *key)\r
698{\r
699 long hash;\r
700 PyDictObject *mp = (PyDictObject *)op;\r
701 PyDictEntry *ep;\r
702 PyThreadState *tstate;\r
703 if (!PyDict_Check(op))\r
704 return NULL;\r
705 if (!PyString_CheckExact(key) ||\r
706 (hash = ((PyStringObject *) key)->ob_shash) == -1)\r
707 {\r
708 hash = PyObject_Hash(key);\r
709 if (hash == -1) {\r
710 PyErr_Clear();\r
711 return NULL;\r
712 }\r
713 }\r
714\r
715 /* We can arrive here with a NULL tstate during initialization: try\r
716 running "python -Wi" for an example related to string interning.\r
717 Let's just hope that no exception occurs then... This must be\r
718 _PyThreadState_Current and not PyThreadState_GET() because in debug\r
719 mode, the latter complains if tstate is NULL. */\r
720 tstate = _PyThreadState_Current;\r
721 if (tstate != NULL && tstate->curexc_type != NULL) {\r
722 /* preserve the existing exception */\r
723 PyObject *err_type, *err_value, *err_tb;\r
724 PyErr_Fetch(&err_type, &err_value, &err_tb);\r
725 ep = (mp->ma_lookup)(mp, key, hash);\r
726 /* ignore errors */\r
727 PyErr_Restore(err_type, err_value, err_tb);\r
728 if (ep == NULL)\r
729 return NULL;\r
730 }\r
731 else {\r
732 ep = (mp->ma_lookup)(mp, key, hash);\r
733 if (ep == NULL) {\r
734 PyErr_Clear();\r
735 return NULL;\r
736 }\r
737 }\r
738 return ep->me_value;\r
739}\r
740\r
741/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the\r
742 * dictionary if it's merely replacing the value for an existing key.\r
743 * This means that it's safe to loop over a dictionary with PyDict_Next()\r
744 * and occasionally replace a value -- but you can't insert new keys or\r
745 * remove them.\r
746 */\r
747int\r
748PyDict_SetItem(register PyObject *op, PyObject *key, PyObject *value)\r
749{\r
750 register PyDictObject *mp;\r
751 register long hash;\r
752 register Py_ssize_t n_used;\r
753\r
754 if (!PyDict_Check(op)) {\r
755 PyErr_BadInternalCall();\r
756 return -1;\r
757 }\r
758 assert(key);\r
759 assert(value);\r
760 mp = (PyDictObject *)op;\r
761 if (PyString_CheckExact(key)) {\r
762 hash = ((PyStringObject *)key)->ob_shash;\r
763 if (hash == -1)\r
764 hash = PyObject_Hash(key);\r
765 }\r
766 else {\r
767 hash = PyObject_Hash(key);\r
768 if (hash == -1)\r
769 return -1;\r
770 }\r
771 assert(mp->ma_fill <= mp->ma_mask); /* at least one empty slot */\r
772 n_used = mp->ma_used;\r
773 Py_INCREF(value);\r
774 Py_INCREF(key);\r
775 if (insertdict(mp, key, hash, value) != 0)\r
776 return -1;\r
777 /* If we added a key, we can safely resize. Otherwise just return!\r
778 * If fill >= 2/3 size, adjust size. Normally, this doubles or\r
779 * quaduples the size, but it's also possible for the dict to shrink\r
780 * (if ma_fill is much larger than ma_used, meaning a lot of dict\r
781 * keys have been * deleted).\r
782 *\r
783 * Quadrupling the size improves average dictionary sparseness\r
784 * (reducing collisions) at the cost of some memory and iteration\r
785 * speed (which loops over every possible entry). It also halves\r
786 * the number of expensive resize operations in a growing dictionary.\r
787 *\r
788 * Very large dictionaries (over 50K items) use doubling instead.\r
789 * This may help applications with severe memory constraints.\r
790 */\r
791 if (!(mp->ma_used > n_used && mp->ma_fill*3 >= (mp->ma_mask+1)*2))\r
792 return 0;\r
793 return dictresize(mp, (mp->ma_used > 50000 ? 2 : 4) * mp->ma_used);\r
794}\r
795\r
796int\r
797PyDict_DelItem(PyObject *op, PyObject *key)\r
798{\r
799 register PyDictObject *mp;\r
800 register long hash;\r
801 register PyDictEntry *ep;\r
802 PyObject *old_value, *old_key;\r
803\r
804 if (!PyDict_Check(op)) {\r
805 PyErr_BadInternalCall();\r
806 return -1;\r
807 }\r
808 assert(key);\r
809 if (!PyString_CheckExact(key) ||\r
810 (hash = ((PyStringObject *) key)->ob_shash) == -1) {\r
811 hash = PyObject_Hash(key);\r
812 if (hash == -1)\r
813 return -1;\r
814 }\r
815 mp = (PyDictObject *)op;\r
816 ep = (mp->ma_lookup)(mp, key, hash);\r
817 if (ep == NULL)\r
818 return -1;\r
819 if (ep->me_value == NULL) {\r
820 set_key_error(key);\r
821 return -1;\r
822 }\r
823 old_key = ep->me_key;\r
824 Py_INCREF(dummy);\r
825 ep->me_key = dummy;\r
826 old_value = ep->me_value;\r
827 ep->me_value = NULL;\r
828 mp->ma_used--;\r
829 Py_DECREF(old_value);\r
830 Py_DECREF(old_key);\r
831 return 0;\r
832}\r
833\r
834void\r
835PyDict_Clear(PyObject *op)\r
836{\r
837 PyDictObject *mp;\r
838 PyDictEntry *ep, *table;\r
839 int table_is_malloced;\r
840 Py_ssize_t fill;\r
841 PyDictEntry small_copy[PyDict_MINSIZE];\r
842#ifdef Py_DEBUG\r
843 Py_ssize_t i, n;\r
844#endif\r
845\r
846 if (!PyDict_Check(op))\r
847 return;\r
848 mp = (PyDictObject *)op;\r
849#ifdef Py_DEBUG\r
850 n = mp->ma_mask + 1;\r
851 i = 0;\r
852#endif\r
853\r
854 table = mp->ma_table;\r
855 assert(table != NULL);\r
856 table_is_malloced = table != mp->ma_smalltable;\r
857\r
858 /* This is delicate. During the process of clearing the dict,\r
859 * decrefs can cause the dict to mutate. To avoid fatal confusion\r
860 * (voice of experience), we have to make the dict empty before\r
861 * clearing the slots, and never refer to anything via mp->xxx while\r
862 * clearing.\r
863 */\r
864 fill = mp->ma_fill;\r
865 if (table_is_malloced)\r
866 EMPTY_TO_MINSIZE(mp);\r
867\r
868 else if (fill > 0) {\r
869 /* It's a small table with something that needs to be cleared.\r
870 * Afraid the only safe way is to copy the dict entries into\r
871 * another small table first.\r
872 */\r
873 memcpy(small_copy, table, sizeof(small_copy));\r
874 table = small_copy;\r
875 EMPTY_TO_MINSIZE(mp);\r
876 }\r
877 /* else it's a small table that's already empty */\r
878\r
879 /* Now we can finally clear things. If C had refcounts, we could\r
880 * assert that the refcount on table is 1 now, i.e. that this function\r
881 * has unique access to it, so decref side-effects can't alter it.\r
882 */\r
883 for (ep = table; fill > 0; ++ep) {\r
884#ifdef Py_DEBUG\r
885 assert(i < n);\r
886 ++i;\r
887#endif\r
888 if (ep->me_key) {\r
889 --fill;\r
890 Py_DECREF(ep->me_key);\r
891 Py_XDECREF(ep->me_value);\r
892 }\r
893#ifdef Py_DEBUG\r
894 else\r
895 assert(ep->me_value == NULL);\r
896#endif\r
897 }\r
898\r
899 if (table_is_malloced)\r
900 PyMem_DEL(table);\r
901}\r
902\r
903/*\r
904 * Iterate over a dict. Use like so:\r
905 *\r
906 * Py_ssize_t i;\r
907 * PyObject *key, *value;\r
908 * i = 0; # important! i should not otherwise be changed by you\r
909 * while (PyDict_Next(yourdict, &i, &key, &value)) {\r
910 * Refer to borrowed references in key and value.\r
911 * }\r
912 *\r
913 * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that\r
914 * mutates the dict. One exception: it is safe if the loop merely changes\r
915 * the values associated with the keys (but doesn't insert new keys or\r
916 * delete keys), via PyDict_SetItem().\r
917 */\r
918int\r
919PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)\r
920{\r
921 register Py_ssize_t i;\r
922 register Py_ssize_t mask;\r
923 register PyDictEntry *ep;\r
924\r
925 if (!PyDict_Check(op))\r
926 return 0;\r
927 i = *ppos;\r
928 if (i < 0)\r
929 return 0;\r
930 ep = ((PyDictObject *)op)->ma_table;\r
931 mask = ((PyDictObject *)op)->ma_mask;\r
932 while (i <= mask && ep[i].me_value == NULL)\r
933 i++;\r
934 *ppos = i+1;\r
935 if (i > mask)\r
936 return 0;\r
937 if (pkey)\r
938 *pkey = ep[i].me_key;\r
939 if (pvalue)\r
940 *pvalue = ep[i].me_value;\r
941 return 1;\r
942}\r
943\r
944/* Internal version of PyDict_Next that returns a hash value in addition to the key and value.*/\r
945int\r
946_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue, long *phash)\r
947{\r
948 register Py_ssize_t i;\r
949 register Py_ssize_t mask;\r
950 register PyDictEntry *ep;\r
951\r
952 if (!PyDict_Check(op))\r
953 return 0;\r
954 i = *ppos;\r
955 if (i < 0)\r
956 return 0;\r
957 ep = ((PyDictObject *)op)->ma_table;\r
958 mask = ((PyDictObject *)op)->ma_mask;\r
959 while (i <= mask && ep[i].me_value == NULL)\r
960 i++;\r
961 *ppos = i+1;\r
962 if (i > mask)\r
963 return 0;\r
964 *phash = (long)(ep[i].me_hash);\r
965 if (pkey)\r
966 *pkey = ep[i].me_key;\r
967 if (pvalue)\r
968 *pvalue = ep[i].me_value;\r
969 return 1;\r
970}\r
971\r
972/* Methods */\r
973\r
974static void\r
975dict_dealloc(register PyDictObject *mp)\r
976{\r
977 register PyDictEntry *ep;\r
978 Py_ssize_t fill = mp->ma_fill;\r
979 PyObject_GC_UnTrack(mp);\r
980 Py_TRASHCAN_SAFE_BEGIN(mp)\r
981 for (ep = mp->ma_table; fill > 0; ep++) {\r
982 if (ep->me_key) {\r
983 --fill;\r
984 Py_DECREF(ep->me_key);\r
985 Py_XDECREF(ep->me_value);\r
986 }\r
987 }\r
988 if (mp->ma_table != mp->ma_smalltable)\r
989 PyMem_DEL(mp->ma_table);\r
990 if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)\r
991 free_list[numfree++] = mp;\r
992 else\r
993 Py_TYPE(mp)->tp_free((PyObject *)mp);\r
994 Py_TRASHCAN_SAFE_END(mp)\r
995}\r
996\r
997static int\r
998dict_print(register PyDictObject *mp, register FILE *fp, register int flags)\r
999{\r
1000 register Py_ssize_t i;\r
1001 register Py_ssize_t any;\r
1002 int status;\r
1003\r
1004 status = Py_ReprEnter((PyObject*)mp);\r
1005 if (status != 0) {\r
1006 if (status < 0)\r
1007 return status;\r
1008 Py_BEGIN_ALLOW_THREADS\r
1009 fprintf(fp, "{...}");\r
1010 Py_END_ALLOW_THREADS\r
1011 return 0;\r
1012 }\r
1013\r
1014 Py_BEGIN_ALLOW_THREADS\r
1015 fprintf(fp, "{");\r
1016 Py_END_ALLOW_THREADS\r
1017 any = 0;\r
1018 for (i = 0; i <= mp->ma_mask; i++) {\r
1019 PyDictEntry *ep = mp->ma_table + i;\r
1020 PyObject *pvalue = ep->me_value;\r
1021 if (pvalue != NULL) {\r
1022 /* Prevent PyObject_Repr from deleting value during\r
1023 key format */\r
1024 Py_INCREF(pvalue);\r
1025 if (any++ > 0) {\r
1026 Py_BEGIN_ALLOW_THREADS\r
1027 fprintf(fp, ", ");\r
1028 Py_END_ALLOW_THREADS\r
1029 }\r
1030 if (PyObject_Print((PyObject *)ep->me_key, fp, 0)!=0) {\r
1031 Py_DECREF(pvalue);\r
1032 Py_ReprLeave((PyObject*)mp);\r
1033 return -1;\r
1034 }\r
1035 Py_BEGIN_ALLOW_THREADS\r
1036 fprintf(fp, ": ");\r
1037 Py_END_ALLOW_THREADS\r
1038 if (PyObject_Print(pvalue, fp, 0) != 0) {\r
1039 Py_DECREF(pvalue);\r
1040 Py_ReprLeave((PyObject*)mp);\r
1041 return -1;\r
1042 }\r
1043 Py_DECREF(pvalue);\r
1044 }\r
1045 }\r
1046 Py_BEGIN_ALLOW_THREADS\r
1047 fprintf(fp, "}");\r
1048 Py_END_ALLOW_THREADS\r
1049 Py_ReprLeave((PyObject*)mp);\r
1050 return 0;\r
1051}\r
1052\r
1053static PyObject *\r
1054dict_repr(PyDictObject *mp)\r
1055{\r
1056 Py_ssize_t i;\r
1057 PyObject *s, *temp, *colon = NULL;\r
1058 PyObject *pieces = NULL, *result = NULL;\r
1059 PyObject *key, *value;\r
1060\r
1061 i = Py_ReprEnter((PyObject *)mp);\r
1062 if (i != 0) {\r
1063 return i > 0 ? PyString_FromString("{...}") : NULL;\r
1064 }\r
1065\r
1066 if (mp->ma_used == 0) {\r
1067 result = PyString_FromString("{}");\r
1068 goto Done;\r
1069 }\r
1070\r
1071 pieces = PyList_New(0);\r
1072 if (pieces == NULL)\r
1073 goto Done;\r
1074\r
1075 colon = PyString_FromString(": ");\r
1076 if (colon == NULL)\r
1077 goto Done;\r
1078\r
1079 /* Do repr() on each key+value pair, and insert ": " between them.\r
1080 Note that repr may mutate the dict. */\r
1081 i = 0;\r
1082 while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {\r
1083 int status;\r
1084 /* Prevent repr from deleting value during key format. */\r
1085 Py_INCREF(value);\r
1086 s = PyObject_Repr(key);\r
1087 PyString_Concat(&s, colon);\r
1088 PyString_ConcatAndDel(&s, PyObject_Repr(value));\r
1089 Py_DECREF(value);\r
1090 if (s == NULL)\r
1091 goto Done;\r
1092 status = PyList_Append(pieces, s);\r
1093 Py_DECREF(s); /* append created a new ref */\r
1094 if (status < 0)\r
1095 goto Done;\r
1096 }\r
1097\r
1098 /* Add "{}" decorations to the first and last items. */\r
1099 assert(PyList_GET_SIZE(pieces) > 0);\r
1100 s = PyString_FromString("{");\r
1101 if (s == NULL)\r
1102 goto Done;\r
1103 temp = PyList_GET_ITEM(pieces, 0);\r
1104 PyString_ConcatAndDel(&s, temp);\r
1105 PyList_SET_ITEM(pieces, 0, s);\r
1106 if (s == NULL)\r
1107 goto Done;\r
1108\r
1109 s = PyString_FromString("}");\r
1110 if (s == NULL)\r
1111 goto Done;\r
1112 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);\r
1113 PyString_ConcatAndDel(&temp, s);\r
1114 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);\r
1115 if (temp == NULL)\r
1116 goto Done;\r
1117\r
1118 /* Paste them all together with ", " between. */\r
1119 s = PyString_FromString(", ");\r
1120 if (s == NULL)\r
1121 goto Done;\r
1122 result = _PyString_Join(s, pieces);\r
1123 Py_DECREF(s);\r
1124\r
1125Done:\r
1126 Py_XDECREF(pieces);\r
1127 Py_XDECREF(colon);\r
1128 Py_ReprLeave((PyObject *)mp);\r
1129 return result;\r
1130}\r
1131\r
1132static Py_ssize_t\r
1133dict_length(PyDictObject *mp)\r
1134{\r
1135 return mp->ma_used;\r
1136}\r
1137\r
1138static PyObject *\r
1139dict_subscript(PyDictObject *mp, register PyObject *key)\r
1140{\r
1141 PyObject *v;\r
1142 long hash;\r
1143 PyDictEntry *ep;\r
1144 assert(mp->ma_table != NULL);\r
1145 if (!PyString_CheckExact(key) ||\r
1146 (hash = ((PyStringObject *) key)->ob_shash) == -1) {\r
1147 hash = PyObject_Hash(key);\r
1148 if (hash == -1)\r
1149 return NULL;\r
1150 }\r
1151 ep = (mp->ma_lookup)(mp, key, hash);\r
1152 if (ep == NULL)\r
1153 return NULL;\r
1154 v = ep->me_value;\r
1155 if (v == NULL) {\r
1156 if (!PyDict_CheckExact(mp)) {\r
1157 /* Look up __missing__ method if we're a subclass. */\r
1158 PyObject *missing, *res;\r
1159 static PyObject *missing_str = NULL;\r
1160 missing = _PyObject_LookupSpecial((PyObject *)mp,\r
1161 "__missing__",\r
1162 &missing_str);\r
1163 if (missing != NULL) {\r
1164 res = PyObject_CallFunctionObjArgs(missing,\r
1165 key, NULL);\r
1166 Py_DECREF(missing);\r
1167 return res;\r
1168 }\r
1169 else if (PyErr_Occurred())\r
1170 return NULL;\r
1171 }\r
1172 set_key_error(key);\r
1173 return NULL;\r
1174 }\r
1175 else\r
1176 Py_INCREF(v);\r
1177 return v;\r
1178}\r
1179\r
1180static int\r
1181dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)\r
1182{\r
1183 if (w == NULL)\r
1184 return PyDict_DelItem((PyObject *)mp, v);\r
1185 else\r
1186 return PyDict_SetItem((PyObject *)mp, v, w);\r
1187}\r
1188\r
1189static PyMappingMethods dict_as_mapping = {\r
1190 (lenfunc)dict_length, /*mp_length*/\r
1191 (binaryfunc)dict_subscript, /*mp_subscript*/\r
1192 (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/\r
1193};\r
1194\r
1195static PyObject *\r
1196dict_keys(register PyDictObject *mp)\r
1197{\r
1198 register PyObject *v;\r
1199 register Py_ssize_t i, j;\r
1200 PyDictEntry *ep;\r
1201 Py_ssize_t mask, n;\r
1202\r
1203 again:\r
1204 n = mp->ma_used;\r
1205 v = PyList_New(n);\r
1206 if (v == NULL)\r
1207 return NULL;\r
1208 if (n != mp->ma_used) {\r
1209 /* Durnit. The allocations caused the dict to resize.\r
1210 * Just start over, this shouldn't normally happen.\r
1211 */\r
1212 Py_DECREF(v);\r
1213 goto again;\r
1214 }\r
1215 ep = mp->ma_table;\r
1216 mask = mp->ma_mask;\r
1217 for (i = 0, j = 0; i <= mask; i++) {\r
1218 if (ep[i].me_value != NULL) {\r
1219 PyObject *key = ep[i].me_key;\r
1220 Py_INCREF(key);\r
1221 PyList_SET_ITEM(v, j, key);\r
1222 j++;\r
1223 }\r
1224 }\r
1225 assert(j == n);\r
1226 return v;\r
1227}\r
1228\r
1229static PyObject *\r
1230dict_values(register PyDictObject *mp)\r
1231{\r
1232 register PyObject *v;\r
1233 register Py_ssize_t i, j;\r
1234 PyDictEntry *ep;\r
1235 Py_ssize_t mask, n;\r
1236\r
1237 again:\r
1238 n = mp->ma_used;\r
1239 v = PyList_New(n);\r
1240 if (v == NULL)\r
1241 return NULL;\r
1242 if (n != mp->ma_used) {\r
1243 /* Durnit. The allocations caused the dict to resize.\r
1244 * Just start over, this shouldn't normally happen.\r
1245 */\r
1246 Py_DECREF(v);\r
1247 goto again;\r
1248 }\r
1249 ep = mp->ma_table;\r
1250 mask = mp->ma_mask;\r
1251 for (i = 0, j = 0; i <= mask; i++) {\r
1252 if (ep[i].me_value != NULL) {\r
1253 PyObject *value = ep[i].me_value;\r
1254 Py_INCREF(value);\r
1255 PyList_SET_ITEM(v, j, value);\r
1256 j++;\r
1257 }\r
1258 }\r
1259 assert(j == n);\r
1260 return v;\r
1261}\r
1262\r
1263static PyObject *\r
1264dict_items(register PyDictObject *mp)\r
1265{\r
1266 register PyObject *v;\r
1267 register Py_ssize_t i, j, n;\r
1268 Py_ssize_t mask;\r
1269 PyObject *item, *key, *value;\r
1270 PyDictEntry *ep;\r
1271\r
1272 /* Preallocate the list of tuples, to avoid allocations during\r
1273 * the loop over the items, which could trigger GC, which\r
1274 * could resize the dict. :-(\r
1275 */\r
1276 again:\r
1277 n = mp->ma_used;\r
1278 v = PyList_New(n);\r
1279 if (v == NULL)\r
1280 return NULL;\r
1281 for (i = 0; i < n; i++) {\r
1282 item = PyTuple_New(2);\r
1283 if (item == NULL) {\r
1284 Py_DECREF(v);\r
1285 return NULL;\r
1286 }\r
1287 PyList_SET_ITEM(v, i, item);\r
1288 }\r
1289 if (n != mp->ma_used) {\r
1290 /* Durnit. The allocations caused the dict to resize.\r
1291 * Just start over, this shouldn't normally happen.\r
1292 */\r
1293 Py_DECREF(v);\r
1294 goto again;\r
1295 }\r
1296 /* Nothing we do below makes any function calls. */\r
1297 ep = mp->ma_table;\r
1298 mask = mp->ma_mask;\r
1299 for (i = 0, j = 0; i <= mask; i++) {\r
1300 if ((value=ep[i].me_value) != NULL) {\r
1301 key = ep[i].me_key;\r
1302 item = PyList_GET_ITEM(v, j);\r
1303 Py_INCREF(key);\r
1304 PyTuple_SET_ITEM(item, 0, key);\r
1305 Py_INCREF(value);\r
1306 PyTuple_SET_ITEM(item, 1, value);\r
1307 j++;\r
1308 }\r
1309 }\r
1310 assert(j == n);\r
1311 return v;\r
1312}\r
1313\r
1314static PyObject *\r
1315dict_fromkeys(PyObject *cls, PyObject *args)\r
1316{\r
1317 PyObject *seq;\r
1318 PyObject *value = Py_None;\r
1319 PyObject *it; /* iter(seq) */\r
1320 PyObject *key;\r
1321 PyObject *d;\r
1322 int status;\r
1323\r
1324 if (!PyArg_UnpackTuple(args, "fromkeys", 1, 2, &seq, &value))\r
1325 return NULL;\r
1326\r
1327 d = PyObject_CallObject(cls, NULL);\r
1328 if (d == NULL)\r
1329 return NULL;\r
1330\r
1331 if (PyDict_CheckExact(d) && PyDict_CheckExact(seq)) {\r
1332 PyDictObject *mp = (PyDictObject *)d;\r
1333 PyObject *oldvalue;\r
1334 Py_ssize_t pos = 0;\r
1335 PyObject *key;\r
1336 long hash;\r
1337\r
1338 if (dictresize(mp, Py_SIZE(seq)))\r
1339 return NULL;\r
1340\r
1341 while (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash)) {\r
1342 Py_INCREF(key);\r
1343 Py_INCREF(value);\r
1344 if (insertdict(mp, key, hash, value))\r
1345 return NULL;\r
1346 }\r
1347 return d;\r
1348 }\r
1349\r
1350 if (PyDict_CheckExact(d) && PyAnySet_CheckExact(seq)) {\r
1351 PyDictObject *mp = (PyDictObject *)d;\r
1352 Py_ssize_t pos = 0;\r
1353 PyObject *key;\r
1354 long hash;\r
1355\r
1356 if (dictresize(mp, PySet_GET_SIZE(seq)))\r
1357 return NULL;\r
1358\r
1359 while (_PySet_NextEntry(seq, &pos, &key, &hash)) {\r
1360 Py_INCREF(key);\r
1361 Py_INCREF(value);\r
1362 if (insertdict(mp, key, hash, value))\r
1363 return NULL;\r
1364 }\r
1365 return d;\r
1366 }\r
1367\r
1368 it = PyObject_GetIter(seq);\r
1369 if (it == NULL){\r
1370 Py_DECREF(d);\r
1371 return NULL;\r
1372 }\r
1373\r
1374 if (PyDict_CheckExact(d)) {\r
1375 while ((key = PyIter_Next(it)) != NULL) {\r
1376 status = PyDict_SetItem(d, key, value);\r
1377 Py_DECREF(key);\r
1378 if (status < 0)\r
1379 goto Fail;\r
1380 }\r
1381 } else {\r
1382 while ((key = PyIter_Next(it)) != NULL) {\r
1383 status = PyObject_SetItem(d, key, value);\r
1384 Py_DECREF(key);\r
1385 if (status < 0)\r
1386 goto Fail;\r
1387 }\r
1388 }\r
1389\r
1390 if (PyErr_Occurred())\r
1391 goto Fail;\r
1392 Py_DECREF(it);\r
1393 return d;\r
1394\r
1395Fail:\r
1396 Py_DECREF(it);\r
1397 Py_DECREF(d);\r
1398 return NULL;\r
1399}\r
1400\r
1401static int\r
1402dict_update_common(PyObject *self, PyObject *args, PyObject *kwds, char *methname)\r
1403{\r
1404 PyObject *arg = NULL;\r
1405 int result = 0;\r
1406\r
1407 if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))\r
1408 result = -1;\r
1409\r
1410 else if (arg != NULL) {\r
1411 if (PyObject_HasAttrString(arg, "keys"))\r
1412 result = PyDict_Merge(self, arg, 1);\r
1413 else\r
1414 result = PyDict_MergeFromSeq2(self, arg, 1);\r
1415 }\r
1416 if (result == 0 && kwds != NULL)\r
1417 result = PyDict_Merge(self, kwds, 1);\r
1418 return result;\r
1419}\r
1420\r
1421static PyObject *\r
1422dict_update(PyObject *self, PyObject *args, PyObject *kwds)\r
1423{\r
1424 if (dict_update_common(self, args, kwds, "update") != -1)\r
1425 Py_RETURN_NONE;\r
1426 return NULL;\r
1427}\r
1428\r
1429/* Update unconditionally replaces existing items.\r
1430 Merge has a 3rd argument 'override'; if set, it acts like Update,\r
1431 otherwise it leaves existing items unchanged.\r
1432\r
1433 PyDict_{Update,Merge} update/merge from a mapping object.\r
1434\r
1435 PyDict_MergeFromSeq2 updates/merges from any iterable object\r
1436 producing iterable objects of length 2.\r
1437*/\r
1438\r
1439int\r
1440PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)\r
1441{\r
1442 PyObject *it; /* iter(seq2) */\r
1443 Py_ssize_t i; /* index into seq2 of current element */\r
1444 PyObject *item; /* seq2[i] */\r
1445 PyObject *fast; /* item as a 2-tuple or 2-list */\r
1446\r
1447 assert(d != NULL);\r
1448 assert(PyDict_Check(d));\r
1449 assert(seq2 != NULL);\r
1450\r
1451 it = PyObject_GetIter(seq2);\r
1452 if (it == NULL)\r
1453 return -1;\r
1454\r
1455 for (i = 0; ; ++i) {\r
1456 PyObject *key, *value;\r
1457 Py_ssize_t n;\r
1458\r
1459 fast = NULL;\r
1460 item = PyIter_Next(it);\r
1461 if (item == NULL) {\r
1462 if (PyErr_Occurred())\r
1463 goto Fail;\r
1464 break;\r
1465 }\r
1466\r
1467 /* Convert item to sequence, and verify length 2. */\r
1468 fast = PySequence_Fast(item, "");\r
1469 if (fast == NULL) {\r
1470 if (PyErr_ExceptionMatches(PyExc_TypeError))\r
1471 PyErr_Format(PyExc_TypeError,\r
1472 "cannot convert dictionary update "\r
1473 "sequence element #%zd to a sequence",\r
1474 i);\r
1475 goto Fail;\r
1476 }\r
1477 n = PySequence_Fast_GET_SIZE(fast);\r
1478 if (n != 2) {\r
1479 PyErr_Format(PyExc_ValueError,\r
1480 "dictionary update sequence element #%zd "\r
1481 "has length %zd; 2 is required",\r
1482 i, n);\r
1483 goto Fail;\r
1484 }\r
1485\r
1486 /* Update/merge with this (key, value) pair. */\r
1487 key = PySequence_Fast_GET_ITEM(fast, 0);\r
1488 value = PySequence_Fast_GET_ITEM(fast, 1);\r
1489 if (override || PyDict_GetItem(d, key) == NULL) {\r
1490 int status = PyDict_SetItem(d, key, value);\r
1491 if (status < 0)\r
1492 goto Fail;\r
1493 }\r
1494 Py_DECREF(fast);\r
1495 Py_DECREF(item);\r
1496 }\r
1497\r
1498 i = 0;\r
1499 goto Return;\r
1500Fail:\r
1501 Py_XDECREF(item);\r
1502 Py_XDECREF(fast);\r
1503 i = -1;\r
1504Return:\r
1505 Py_DECREF(it);\r
1506 return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);\r
1507}\r
1508\r
1509int\r
1510PyDict_Update(PyObject *a, PyObject *b)\r
1511{\r
1512 return PyDict_Merge(a, b, 1);\r
1513}\r
1514\r
1515int\r
1516PyDict_Merge(PyObject *a, PyObject *b, int override)\r
1517{\r
1518 register PyDictObject *mp, *other;\r
1519 register Py_ssize_t i;\r
1520 PyDictEntry *entry;\r
1521\r
1522 /* We accept for the argument either a concrete dictionary object,\r
1523 * or an abstract "mapping" object. For the former, we can do\r
1524 * things quite efficiently. For the latter, we only require that\r
1525 * PyMapping_Keys() and PyObject_GetItem() be supported.\r
1526 */\r
1527 if (a == NULL || !PyDict_Check(a) || b == NULL) {\r
1528 PyErr_BadInternalCall();\r
1529 return -1;\r
1530 }\r
1531 mp = (PyDictObject*)a;\r
1532 if (PyDict_Check(b)) {\r
1533 other = (PyDictObject*)b;\r
1534 if (other == mp || other->ma_used == 0)\r
1535 /* a.update(a) or a.update({}); nothing to do */\r
1536 return 0;\r
1537 if (mp->ma_used == 0)\r
1538 /* Since the target dict is empty, PyDict_GetItem()\r
1539 * always returns NULL. Setting override to 1\r
1540 * skips the unnecessary test.\r
1541 */\r
1542 override = 1;\r
1543 /* Do one big resize at the start, rather than\r
1544 * incrementally resizing as we insert new items. Expect\r
1545 * that there will be no (or few) overlapping keys.\r
1546 */\r
1547 if ((mp->ma_fill + other->ma_used)*3 >= (mp->ma_mask+1)*2) {\r
1548 if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0)\r
1549 return -1;\r
1550 }\r
1551 for (i = 0; i <= other->ma_mask; i++) {\r
1552 entry = &other->ma_table[i];\r
1553 if (entry->me_value != NULL &&\r
1554 (override ||\r
1555 PyDict_GetItem(a, entry->me_key) == NULL)) {\r
1556 Py_INCREF(entry->me_key);\r
1557 Py_INCREF(entry->me_value);\r
1558 if (insertdict(mp, entry->me_key,\r
1559 (long)entry->me_hash,\r
1560 entry->me_value) != 0)\r
1561 return -1;\r
1562 }\r
1563 }\r
1564 }\r
1565 else {\r
1566 /* Do it the generic, slower way */\r
1567 PyObject *keys = PyMapping_Keys(b);\r
1568 PyObject *iter;\r
1569 PyObject *key, *value;\r
1570 int status;\r
1571\r
1572 if (keys == NULL)\r
1573 /* Docstring says this is equivalent to E.keys() so\r
1574 * if E doesn't have a .keys() method we want\r
1575 * AttributeError to percolate up. Might as well\r
1576 * do the same for any other error.\r
1577 */\r
1578 return -1;\r
1579\r
1580 iter = PyObject_GetIter(keys);\r
1581 Py_DECREF(keys);\r
1582 if (iter == NULL)\r
1583 return -1;\r
1584\r
1585 for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {\r
1586 if (!override && PyDict_GetItem(a, key) != NULL) {\r
1587 Py_DECREF(key);\r
1588 continue;\r
1589 }\r
1590 value = PyObject_GetItem(b, key);\r
1591 if (value == NULL) {\r
1592 Py_DECREF(iter);\r
1593 Py_DECREF(key);\r
1594 return -1;\r
1595 }\r
1596 status = PyDict_SetItem(a, key, value);\r
1597 Py_DECREF(key);\r
1598 Py_DECREF(value);\r
1599 if (status < 0) {\r
1600 Py_DECREF(iter);\r
1601 return -1;\r
1602 }\r
1603 }\r
1604 Py_DECREF(iter);\r
1605 if (PyErr_Occurred())\r
1606 /* Iterator completed, via error */\r
1607 return -1;\r
1608 }\r
1609 return 0;\r
1610}\r
1611\r
1612static PyObject *\r
1613dict_copy(register PyDictObject *mp)\r
1614{\r
1615 return PyDict_Copy((PyObject*)mp);\r
1616}\r
1617\r
1618PyObject *\r
1619PyDict_Copy(PyObject *o)\r
1620{\r
1621 PyObject *copy;\r
1622\r
1623 if (o == NULL || !PyDict_Check(o)) {\r
1624 PyErr_BadInternalCall();\r
1625 return NULL;\r
1626 }\r
1627 copy = PyDict_New();\r
1628 if (copy == NULL)\r
1629 return NULL;\r
1630 if (PyDict_Merge(copy, o, 1) == 0)\r
1631 return copy;\r
1632 Py_DECREF(copy);\r
1633 return NULL;\r
1634}\r
1635\r
1636Py_ssize_t\r
1637PyDict_Size(PyObject *mp)\r
1638{\r
1639 if (mp == NULL || !PyDict_Check(mp)) {\r
1640 PyErr_BadInternalCall();\r
1641 return -1;\r
1642 }\r
1643 return ((PyDictObject *)mp)->ma_used;\r
1644}\r
1645\r
1646PyObject *\r
1647PyDict_Keys(PyObject *mp)\r
1648{\r
1649 if (mp == NULL || !PyDict_Check(mp)) {\r
1650 PyErr_BadInternalCall();\r
1651 return NULL;\r
1652 }\r
1653 return dict_keys((PyDictObject *)mp);\r
1654}\r
1655\r
1656PyObject *\r
1657PyDict_Values(PyObject *mp)\r
1658{\r
1659 if (mp == NULL || !PyDict_Check(mp)) {\r
1660 PyErr_BadInternalCall();\r
1661 return NULL;\r
1662 }\r
1663 return dict_values((PyDictObject *)mp);\r
1664}\r
1665\r
1666PyObject *\r
1667PyDict_Items(PyObject *mp)\r
1668{\r
1669 if (mp == NULL || !PyDict_Check(mp)) {\r
1670 PyErr_BadInternalCall();\r
1671 return NULL;\r
1672 }\r
1673 return dict_items((PyDictObject *)mp);\r
1674}\r
1675\r
1676/* Subroutine which returns the smallest key in a for which b's value\r
1677 is different or absent. The value is returned too, through the\r
1678 pval argument. Both are NULL if no key in a is found for which b's status\r
1679 differs. The refcounts on (and only on) non-NULL *pval and function return\r
1680 values must be decremented by the caller (characterize() increments them\r
1681 to ensure that mutating comparison and PyDict_GetItem calls can't delete\r
1682 them before the caller is done looking at them). */\r
1683\r
1684static PyObject *\r
1685characterize(PyDictObject *a, PyDictObject *b, PyObject **pval)\r
1686{\r
1687 PyObject *akey = NULL; /* smallest key in a s.t. a[akey] != b[akey] */\r
1688 PyObject *aval = NULL; /* a[akey] */\r
1689 Py_ssize_t i;\r
1690 int cmp;\r
1691\r
1692 for (i = 0; i <= a->ma_mask; i++) {\r
1693 PyObject *thiskey, *thisaval, *thisbval;\r
1694 if (a->ma_table[i].me_value == NULL)\r
1695 continue;\r
1696 thiskey = a->ma_table[i].me_key;\r
1697 Py_INCREF(thiskey); /* keep alive across compares */\r
1698 if (akey != NULL) {\r
1699 cmp = PyObject_RichCompareBool(akey, thiskey, Py_LT);\r
1700 if (cmp < 0) {\r
1701 Py_DECREF(thiskey);\r
1702 goto Fail;\r
1703 }\r
1704 if (cmp > 0 ||\r
1705 i > a->ma_mask ||\r
1706 a->ma_table[i].me_value == NULL)\r
1707 {\r
1708 /* Not the *smallest* a key; or maybe it is\r
1709 * but the compare shrunk the dict so we can't\r
1710 * find its associated value anymore; or\r
1711 * maybe it is but the compare deleted the\r
1712 * a[thiskey] entry.\r
1713 */\r
1714 Py_DECREF(thiskey);\r
1715 continue;\r
1716 }\r
1717 }\r
1718\r
1719 /* Compare a[thiskey] to b[thiskey]; cmp <- true iff equal. */\r
1720 thisaval = a->ma_table[i].me_value;\r
1721 assert(thisaval);\r
1722 Py_INCREF(thisaval); /* keep alive */\r
1723 thisbval = PyDict_GetItem((PyObject *)b, thiskey);\r
1724 if (thisbval == NULL)\r
1725 cmp = 0;\r
1726 else {\r
1727 /* both dicts have thiskey: same values? */\r
1728 cmp = PyObject_RichCompareBool(\r
1729 thisaval, thisbval, Py_EQ);\r
1730 if (cmp < 0) {\r
1731 Py_DECREF(thiskey);\r
1732 Py_DECREF(thisaval);\r
1733 goto Fail;\r
1734 }\r
1735 }\r
1736 if (cmp == 0) {\r
1737 /* New winner. */\r
1738 Py_XDECREF(akey);\r
1739 Py_XDECREF(aval);\r
1740 akey = thiskey;\r
1741 aval = thisaval;\r
1742 }\r
1743 else {\r
1744 Py_DECREF(thiskey);\r
1745 Py_DECREF(thisaval);\r
1746 }\r
1747 }\r
1748 *pval = aval;\r
1749 return akey;\r
1750\r
1751Fail:\r
1752 Py_XDECREF(akey);\r
1753 Py_XDECREF(aval);\r
1754 *pval = NULL;\r
1755 return NULL;\r
1756}\r
1757\r
1758static int\r
1759dict_compare(PyDictObject *a, PyDictObject *b)\r
1760{\r
1761 PyObject *adiff, *bdiff, *aval, *bval;\r
1762 int res;\r
1763\r
1764 /* Compare lengths first */\r
1765 if (a->ma_used < b->ma_used)\r
1766 return -1; /* a is shorter */\r
1767 else if (a->ma_used > b->ma_used)\r
1768 return 1; /* b is shorter */\r
1769\r
1770 /* Same length -- check all keys */\r
1771 bdiff = bval = NULL;\r
1772 adiff = characterize(a, b, &aval);\r
1773 if (adiff == NULL) {\r
1774 assert(!aval);\r
1775 /* Either an error, or a is a subset with the same length so\r
1776 * must be equal.\r
1777 */\r
1778 res = PyErr_Occurred() ? -1 : 0;\r
1779 goto Finished;\r
1780 }\r
1781 bdiff = characterize(b, a, &bval);\r
1782 if (bdiff == NULL && PyErr_Occurred()) {\r
1783 assert(!bval);\r
1784 res = -1;\r
1785 goto Finished;\r
1786 }\r
1787 res = 0;\r
1788 if (bdiff) {\r
1789 /* bdiff == NULL "should be" impossible now, but perhaps\r
1790 * the last comparison done by the characterize() on a had\r
1791 * the side effect of making the dicts equal!\r
1792 */\r
1793 res = PyObject_Compare(adiff, bdiff);\r
1794 }\r
1795 if (res == 0 && bval != NULL)\r
1796 res = PyObject_Compare(aval, bval);\r
1797\r
1798Finished:\r
1799 Py_XDECREF(adiff);\r
1800 Py_XDECREF(bdiff);\r
1801 Py_XDECREF(aval);\r
1802 Py_XDECREF(bval);\r
1803 return res;\r
1804}\r
1805\r
1806/* Return 1 if dicts equal, 0 if not, -1 if error.\r
1807 * Gets out as soon as any difference is detected.\r
1808 * Uses only Py_EQ comparison.\r
1809 */\r
1810static int\r
1811dict_equal(PyDictObject *a, PyDictObject *b)\r
1812{\r
1813 Py_ssize_t i;\r
1814\r
1815 if (a->ma_used != b->ma_used)\r
1816 /* can't be equal if # of entries differ */\r
1817 return 0;\r
1818\r
1819 /* Same # of entries -- check all of 'em. Exit early on any diff. */\r
1820 for (i = 0; i <= a->ma_mask; i++) {\r
1821 PyObject *aval = a->ma_table[i].me_value;\r
1822 if (aval != NULL) {\r
1823 int cmp;\r
1824 PyObject *bval;\r
1825 PyObject *key = a->ma_table[i].me_key;\r
1826 /* temporarily bump aval's refcount to ensure it stays\r
1827 alive until we're done with it */\r
1828 Py_INCREF(aval);\r
1829 /* ditto for key */\r
1830 Py_INCREF(key);\r
1831 bval = PyDict_GetItem((PyObject *)b, key);\r
1832 Py_DECREF(key);\r
1833 if (bval == NULL) {\r
1834 Py_DECREF(aval);\r
1835 return 0;\r
1836 }\r
1837 cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);\r
1838 Py_DECREF(aval);\r
1839 if (cmp <= 0) /* error or not equal */\r
1840 return cmp;\r
1841 }\r
1842 }\r
1843 return 1;\r
1844 }\r
1845\r
1846static PyObject *\r
1847dict_richcompare(PyObject *v, PyObject *w, int op)\r
1848{\r
1849 int cmp;\r
1850 PyObject *res;\r
1851\r
1852 if (!PyDict_Check(v) || !PyDict_Check(w)) {\r
1853 res = Py_NotImplemented;\r
1854 }\r
1855 else if (op == Py_EQ || op == Py_NE) {\r
1856 cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);\r
1857 if (cmp < 0)\r
1858 return NULL;\r
1859 res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;\r
1860 }\r
1861 else {\r
1862 /* Py3K warning if comparison isn't == or != */\r
1863 if (PyErr_WarnPy3k("dict inequality comparisons not supported "\r
1864 "in 3.x", 1) < 0) {\r
1865 return NULL;\r
1866 }\r
1867 res = Py_NotImplemented;\r
1868 }\r
1869 Py_INCREF(res);\r
1870 return res;\r
1871 }\r
1872\r
1873static PyObject *\r
1874dict_contains(register PyDictObject *mp, PyObject *key)\r
1875{\r
1876 long hash;\r
1877 PyDictEntry *ep;\r
1878\r
1879 if (!PyString_CheckExact(key) ||\r
1880 (hash = ((PyStringObject *) key)->ob_shash) == -1) {\r
1881 hash = PyObject_Hash(key);\r
1882 if (hash == -1)\r
1883 return NULL;\r
1884 }\r
1885 ep = (mp->ma_lookup)(mp, key, hash);\r
1886 if (ep == NULL)\r
1887 return NULL;\r
1888 return PyBool_FromLong(ep->me_value != NULL);\r
1889}\r
1890\r
1891static PyObject *\r
1892dict_has_key(register PyDictObject *mp, PyObject *key)\r
1893{\r
1894 if (PyErr_WarnPy3k("dict.has_key() not supported in 3.x; "\r
1895 "use the in operator", 1) < 0)\r
1896 return NULL;\r
1897 return dict_contains(mp, key);\r
1898}\r
1899\r
1900static PyObject *\r
1901dict_get(register PyDictObject *mp, PyObject *args)\r
1902{\r
1903 PyObject *key;\r
1904 PyObject *failobj = Py_None;\r
1905 PyObject *val = NULL;\r
1906 long hash;\r
1907 PyDictEntry *ep;\r
1908\r
1909 if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))\r
1910 return NULL;\r
1911\r
1912 if (!PyString_CheckExact(key) ||\r
1913 (hash = ((PyStringObject *) key)->ob_shash) == -1) {\r
1914 hash = PyObject_Hash(key);\r
1915 if (hash == -1)\r
1916 return NULL;\r
1917 }\r
1918 ep = (mp->ma_lookup)(mp, key, hash);\r
1919 if (ep == NULL)\r
1920 return NULL;\r
1921 val = ep->me_value;\r
1922 if (val == NULL)\r
1923 val = failobj;\r
1924 Py_INCREF(val);\r
1925 return val;\r
1926}\r
1927\r
1928\r
1929static PyObject *\r
1930dict_setdefault(register PyDictObject *mp, PyObject *args)\r
1931{\r
1932 PyObject *key;\r
1933 PyObject *failobj = Py_None;\r
1934 PyObject *val = NULL;\r
1935 long hash;\r
1936 PyDictEntry *ep;\r
1937\r
1938 if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &failobj))\r
1939 return NULL;\r
1940\r
1941 if (!PyString_CheckExact(key) ||\r
1942 (hash = ((PyStringObject *) key)->ob_shash) == -1) {\r
1943 hash = PyObject_Hash(key);\r
1944 if (hash == -1)\r
1945 return NULL;\r
1946 }\r
1947 ep = (mp->ma_lookup)(mp, key, hash);\r
1948 if (ep == NULL)\r
1949 return NULL;\r
1950 val = ep->me_value;\r
1951 if (val == NULL) {\r
1952 val = failobj;\r
1953 if (PyDict_SetItem((PyObject*)mp, key, failobj))\r
1954 val = NULL;\r
1955 }\r
1956 Py_XINCREF(val);\r
1957 return val;\r
1958}\r
1959\r
1960\r
1961static PyObject *\r
1962dict_clear(register PyDictObject *mp)\r
1963{\r
1964 PyDict_Clear((PyObject *)mp);\r
1965 Py_RETURN_NONE;\r
1966}\r
1967\r
1968static PyObject *\r
1969dict_pop(PyDictObject *mp, PyObject *args)\r
1970{\r
1971 long hash;\r
1972 PyDictEntry *ep;\r
1973 PyObject *old_value, *old_key;\r
1974 PyObject *key, *deflt = NULL;\r
1975\r
1976 if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))\r
1977 return NULL;\r
1978 if (mp->ma_used == 0) {\r
1979 if (deflt) {\r
1980 Py_INCREF(deflt);\r
1981 return deflt;\r
1982 }\r
1983 set_key_error(key);\r
1984 return NULL;\r
1985 }\r
1986 if (!PyString_CheckExact(key) ||\r
1987 (hash = ((PyStringObject *) key)->ob_shash) == -1) {\r
1988 hash = PyObject_Hash(key);\r
1989 if (hash == -1)\r
1990 return NULL;\r
1991 }\r
1992 ep = (mp->ma_lookup)(mp, key, hash);\r
1993 if (ep == NULL)\r
1994 return NULL;\r
1995 if (ep->me_value == NULL) {\r
1996 if (deflt) {\r
1997 Py_INCREF(deflt);\r
1998 return deflt;\r
1999 }\r
2000 set_key_error(key);\r
2001 return NULL;\r
2002 }\r
2003 old_key = ep->me_key;\r
2004 Py_INCREF(dummy);\r
2005 ep->me_key = dummy;\r
2006 old_value = ep->me_value;\r
2007 ep->me_value = NULL;\r
2008 mp->ma_used--;\r
2009 Py_DECREF(old_key);\r
2010 return old_value;\r
2011}\r
2012\r
2013static PyObject *\r
2014dict_popitem(PyDictObject *mp)\r
2015{\r
2016 Py_ssize_t i = 0;\r
2017 PyDictEntry *ep;\r
2018 PyObject *res;\r
2019\r
2020 /* Allocate the result tuple before checking the size. Believe it\r
2021 * or not, this allocation could trigger a garbage collection which\r
2022 * could empty the dict, so if we checked the size first and that\r
2023 * happened, the result would be an infinite loop (searching for an\r
2024 * entry that no longer exists). Note that the usual popitem()\r
2025 * idiom is "while d: k, v = d.popitem()". so needing to throw the\r
2026 * tuple away if the dict *is* empty isn't a significant\r
2027 * inefficiency -- possible, but unlikely in practice.\r
2028 */\r
2029 res = PyTuple_New(2);\r
2030 if (res == NULL)\r
2031 return NULL;\r
2032 if (mp->ma_used == 0) {\r
2033 Py_DECREF(res);\r
2034 PyErr_SetString(PyExc_KeyError,\r
2035 "popitem(): dictionary is empty");\r
2036 return NULL;\r
2037 }\r
2038 /* Set ep to "the first" dict entry with a value. We abuse the hash\r
2039 * field of slot 0 to hold a search finger:\r
2040 * If slot 0 has a value, use slot 0.\r
2041 * Else slot 0 is being used to hold a search finger,\r
2042 * and we use its hash value as the first index to look.\r
2043 */\r
2044 ep = &mp->ma_table[0];\r
2045 if (ep->me_value == NULL) {\r
2046 i = ep->me_hash;\r
2047 /* The hash field may be a real hash value, or it may be a\r
2048 * legit search finger, or it may be a once-legit search\r
2049 * finger that's out of bounds now because it wrapped around\r
2050 * or the table shrunk -- simply make sure it's in bounds now.\r
2051 */\r
2052 if (i > mp->ma_mask || i < 1)\r
2053 i = 1; /* skip slot 0 */\r
2054 while ((ep = &mp->ma_table[i])->me_value == NULL) {\r
2055 i++;\r
2056 if (i > mp->ma_mask)\r
2057 i = 1;\r
2058 }\r
2059 }\r
2060 PyTuple_SET_ITEM(res, 0, ep->me_key);\r
2061 PyTuple_SET_ITEM(res, 1, ep->me_value);\r
2062 Py_INCREF(dummy);\r
2063 ep->me_key = dummy;\r
2064 ep->me_value = NULL;\r
2065 mp->ma_used--;\r
2066 assert(mp->ma_table[0].me_value == NULL);\r
2067 mp->ma_table[0].me_hash = i + 1; /* next place to start */\r
2068 return res;\r
2069}\r
2070\r
2071static int\r
2072dict_traverse(PyObject *op, visitproc visit, void *arg)\r
2073{\r
2074 Py_ssize_t i = 0;\r
2075 PyObject *pk;\r
2076 PyObject *pv;\r
2077\r
2078 while (PyDict_Next(op, &i, &pk, &pv)) {\r
2079 Py_VISIT(pk);\r
2080 Py_VISIT(pv);\r
2081 }\r
2082 return 0;\r
2083}\r
2084\r
2085static int\r
2086dict_tp_clear(PyObject *op)\r
2087{\r
2088 PyDict_Clear(op);\r
2089 return 0;\r
2090}\r
2091\r
2092\r
2093extern PyTypeObject PyDictIterKey_Type; /* Forward */\r
2094extern PyTypeObject PyDictIterValue_Type; /* Forward */\r
2095extern PyTypeObject PyDictIterItem_Type; /* Forward */\r
2096static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);\r
2097\r
2098static PyObject *\r
2099dict_iterkeys(PyDictObject *dict)\r
2100{\r
2101 return dictiter_new(dict, &PyDictIterKey_Type);\r
2102}\r
2103\r
2104static PyObject *\r
2105dict_itervalues(PyDictObject *dict)\r
2106{\r
2107 return dictiter_new(dict, &PyDictIterValue_Type);\r
2108}\r
2109\r
2110static PyObject *\r
2111dict_iteritems(PyDictObject *dict)\r
2112{\r
2113 return dictiter_new(dict, &PyDictIterItem_Type);\r
2114}\r
2115\r
2116static PyObject *\r
2117dict_sizeof(PyDictObject *mp)\r
2118{\r
2119 Py_ssize_t res;\r
2120\r
2121 res = sizeof(PyDictObject);\r
2122 if (mp->ma_table != mp->ma_smalltable)\r
2123 res = res + (mp->ma_mask + 1) * sizeof(PyDictEntry);\r
2124 return PyInt_FromSsize_t(res);\r
2125}\r
2126\r
2127PyDoc_STRVAR(has_key__doc__,\r
2128"D.has_key(k) -> True if D has a key k, else False");\r
2129\r
2130PyDoc_STRVAR(contains__doc__,\r
2131"D.__contains__(k) -> True if D has a key k, else False");\r
2132\r
2133PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");\r
2134\r
2135PyDoc_STRVAR(sizeof__doc__,\r
2136"D.__sizeof__() -> size of D in memory, in bytes");\r
2137\r
2138PyDoc_STRVAR(get__doc__,\r
2139"D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.");\r
2140\r
2141PyDoc_STRVAR(setdefault_doc__,\r
2142"D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D");\r
2143\r
2144PyDoc_STRVAR(pop__doc__,\r
2145"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\\r
2146If key is not found, d is returned if given, otherwise KeyError is raised");\r
2147\r
2148PyDoc_STRVAR(popitem__doc__,\r
2149"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\\r
21502-tuple; but raise KeyError if D is empty.");\r
2151\r
2152PyDoc_STRVAR(keys__doc__,\r
2153"D.keys() -> list of D's keys");\r
2154\r
2155PyDoc_STRVAR(items__doc__,\r
2156"D.items() -> list of D's (key, value) pairs, as 2-tuples");\r
2157\r
2158PyDoc_STRVAR(values__doc__,\r
2159"D.values() -> list of D's values");\r
2160\r
2161PyDoc_STRVAR(update__doc__,\r
2162"D.update(E, **F) -> None. Update D from dict/iterable E and F.\n"\r
2163"If E has a .keys() method, does: for k in E: D[k] = E[k]\n\\r
2164If E lacks .keys() method, does: for (k, v) in E: D[k] = v\n\\r
2165In either case, this is followed by: for k in F: D[k] = F[k]");\r
2166\r
2167PyDoc_STRVAR(fromkeys__doc__,\r
2168"dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.\n\\r
2169v defaults to None.");\r
2170\r
2171PyDoc_STRVAR(clear__doc__,\r
2172"D.clear() -> None. Remove all items from D.");\r
2173\r
2174PyDoc_STRVAR(copy__doc__,\r
2175"D.copy() -> a shallow copy of D");\r
2176\r
2177PyDoc_STRVAR(iterkeys__doc__,\r
2178"D.iterkeys() -> an iterator over the keys of D");\r
2179\r
2180PyDoc_STRVAR(itervalues__doc__,\r
2181"D.itervalues() -> an iterator over the values of D");\r
2182\r
2183PyDoc_STRVAR(iteritems__doc__,\r
2184"D.iteritems() -> an iterator over the (key, value) items of D");\r
2185\r
2186/* Forward */\r
2187static PyObject *dictkeys_new(PyObject *);\r
2188static PyObject *dictitems_new(PyObject *);\r
2189static PyObject *dictvalues_new(PyObject *);\r
2190\r
2191PyDoc_STRVAR(viewkeys__doc__,\r
2192 "D.viewkeys() -> a set-like object providing a view on D's keys");\r
2193PyDoc_STRVAR(viewitems__doc__,\r
2194 "D.viewitems() -> a set-like object providing a view on D's items");\r
2195PyDoc_STRVAR(viewvalues__doc__,\r
2196 "D.viewvalues() -> an object providing a view on D's values");\r
2197\r
2198static PyMethodDef mapp_methods[] = {\r
2199 {"__contains__",(PyCFunction)dict_contains, METH_O | METH_COEXIST,\r
2200 contains__doc__},\r
2201 {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,\r
2202 getitem__doc__},\r
2203 {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS,\r
2204 sizeof__doc__},\r
2205 {"has_key", (PyCFunction)dict_has_key, METH_O,\r
2206 has_key__doc__},\r
2207 {"get", (PyCFunction)dict_get, METH_VARARGS,\r
2208 get__doc__},\r
2209 {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS,\r
2210 setdefault_doc__},\r
2211 {"pop", (PyCFunction)dict_pop, METH_VARARGS,\r
2212 pop__doc__},\r
2213 {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,\r
2214 popitem__doc__},\r
2215 {"keys", (PyCFunction)dict_keys, METH_NOARGS,\r
2216 keys__doc__},\r
2217 {"items", (PyCFunction)dict_items, METH_NOARGS,\r
2218 items__doc__},\r
2219 {"values", (PyCFunction)dict_values, METH_NOARGS,\r
2220 values__doc__},\r
2221 {"viewkeys", (PyCFunction)dictkeys_new, METH_NOARGS,\r
2222 viewkeys__doc__},\r
2223 {"viewitems", (PyCFunction)dictitems_new, METH_NOARGS,\r
2224 viewitems__doc__},\r
2225 {"viewvalues", (PyCFunction)dictvalues_new, METH_NOARGS,\r
2226 viewvalues__doc__},\r
2227 {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,\r
2228 update__doc__},\r
2229 {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS,\r
2230 fromkeys__doc__},\r
2231 {"clear", (PyCFunction)dict_clear, METH_NOARGS,\r
2232 clear__doc__},\r
2233 {"copy", (PyCFunction)dict_copy, METH_NOARGS,\r
2234 copy__doc__},\r
2235 {"iterkeys", (PyCFunction)dict_iterkeys, METH_NOARGS,\r
2236 iterkeys__doc__},\r
2237 {"itervalues", (PyCFunction)dict_itervalues, METH_NOARGS,\r
2238 itervalues__doc__},\r
2239 {"iteritems", (PyCFunction)dict_iteritems, METH_NOARGS,\r
2240 iteritems__doc__},\r
2241 {NULL, NULL} /* sentinel */\r
2242};\r
2243\r
2244/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */\r
2245int\r
2246PyDict_Contains(PyObject *op, PyObject *key)\r
2247{\r
2248 long hash;\r
2249 PyDictObject *mp = (PyDictObject *)op;\r
2250 PyDictEntry *ep;\r
2251\r
2252 if (!PyString_CheckExact(key) ||\r
2253 (hash = ((PyStringObject *) key)->ob_shash) == -1) {\r
2254 hash = PyObject_Hash(key);\r
2255 if (hash == -1)\r
2256 return -1;\r
2257 }\r
2258 ep = (mp->ma_lookup)(mp, key, hash);\r
2259 return ep == NULL ? -1 : (ep->me_value != NULL);\r
2260}\r
2261\r
2262/* Internal version of PyDict_Contains used when the hash value is already known */\r
2263int\r
2264_PyDict_Contains(PyObject *op, PyObject *key, long hash)\r
2265{\r
2266 PyDictObject *mp = (PyDictObject *)op;\r
2267 PyDictEntry *ep;\r
2268\r
2269 ep = (mp->ma_lookup)(mp, key, hash);\r
2270 return ep == NULL ? -1 : (ep->me_value != NULL);\r
2271}\r
2272\r
2273/* Hack to implement "key in dict" */\r
2274static PySequenceMethods dict_as_sequence = {\r
2275 0, /* sq_length */\r
2276 0, /* sq_concat */\r
2277 0, /* sq_repeat */\r
2278 0, /* sq_item */\r
2279 0, /* sq_slice */\r
2280 0, /* sq_ass_item */\r
2281 0, /* sq_ass_slice */\r
2282 PyDict_Contains, /* sq_contains */\r
2283 0, /* sq_inplace_concat */\r
2284 0, /* sq_inplace_repeat */\r
2285};\r
2286\r
2287static PyObject *\r
2288dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\r
2289{\r
2290 PyObject *self;\r
2291\r
2292 assert(type != NULL && type->tp_alloc != NULL);\r
2293 self = type->tp_alloc(type, 0);\r
2294 if (self != NULL) {\r
2295 PyDictObject *d = (PyDictObject *)self;\r
2296 /* It's guaranteed that tp->alloc zeroed out the struct. */\r
2297 assert(d->ma_table == NULL && d->ma_fill == 0 && d->ma_used == 0);\r
2298 INIT_NONZERO_DICT_SLOTS(d);\r
2299 d->ma_lookup = lookdict_string;\r
2300 /* The object has been implicitly tracked by tp_alloc */\r
2301 if (type == &PyDict_Type)\r
2302 _PyObject_GC_UNTRACK(d);\r
2303#ifdef SHOW_CONVERSION_COUNTS\r
2304 ++created;\r
2305#endif\r
2306#ifdef SHOW_TRACK_COUNT\r
2307 if (_PyObject_GC_IS_TRACKED(d))\r
2308 count_tracked++;\r
2309 else\r
2310 count_untracked++;\r
2311#endif\r
2312 }\r
2313 return self;\r
2314}\r
2315\r
2316static int\r
2317dict_init(PyObject *self, PyObject *args, PyObject *kwds)\r
2318{\r
2319 return dict_update_common(self, args, kwds, "dict");\r
2320}\r
2321\r
2322static PyObject *\r
2323dict_iter(PyDictObject *dict)\r
2324{\r
2325 return dictiter_new(dict, &PyDictIterKey_Type);\r
2326}\r
2327\r
2328PyDoc_STRVAR(dictionary_doc,\r
2329"dict() -> new empty dictionary\n"\r
2330"dict(mapping) -> new dictionary initialized from a mapping object's\n"\r
2331" (key, value) pairs\n"\r
2332"dict(iterable) -> new dictionary initialized as if via:\n"\r
2333" d = {}\n"\r
2334" for k, v in iterable:\n"\r
2335" d[k] = v\n"\r
2336"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"\r
2337" in the keyword argument list. For example: dict(one=1, two=2)");\r
2338\r
2339PyTypeObject PyDict_Type = {\r
2340 PyVarObject_HEAD_INIT(&PyType_Type, 0)\r
2341 "dict",\r
2342 sizeof(PyDictObject),\r
2343 0,\r
2344 (destructor)dict_dealloc, /* tp_dealloc */\r
2345 (printfunc)dict_print, /* tp_print */\r
2346 0, /* tp_getattr */\r
2347 0, /* tp_setattr */\r
2348 (cmpfunc)dict_compare, /* tp_compare */\r
2349 (reprfunc)dict_repr, /* tp_repr */\r
2350 0, /* tp_as_number */\r
2351 &dict_as_sequence, /* tp_as_sequence */\r
2352 &dict_as_mapping, /* tp_as_mapping */\r
2353 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */\r
2354 0, /* tp_call */\r
2355 0, /* tp_str */\r
2356 PyObject_GenericGetAttr, /* tp_getattro */\r
2357 0, /* tp_setattro */\r
2358 0, /* tp_as_buffer */\r
2359 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |\r
2360 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */\r
2361 dictionary_doc, /* tp_doc */\r
2362 dict_traverse, /* tp_traverse */\r
2363 dict_tp_clear, /* tp_clear */\r
2364 dict_richcompare, /* tp_richcompare */\r
2365 0, /* tp_weaklistoffset */\r
2366 (getiterfunc)dict_iter, /* tp_iter */\r
2367 0, /* tp_iternext */\r
2368 mapp_methods, /* tp_methods */\r
2369 0, /* tp_members */\r
2370 0, /* tp_getset */\r
2371 0, /* tp_base */\r
2372 0, /* tp_dict */\r
2373 0, /* tp_descr_get */\r
2374 0, /* tp_descr_set */\r
2375 0, /* tp_dictoffset */\r
2376 dict_init, /* tp_init */\r
2377 PyType_GenericAlloc, /* tp_alloc */\r
2378 dict_new, /* tp_new */\r
2379 PyObject_GC_Del, /* tp_free */\r
2380};\r
2381\r
2382/* For backward compatibility with old dictionary interface */\r
2383\r
2384PyObject *\r
2385PyDict_GetItemString(PyObject *v, const char *key)\r
2386{\r
2387 PyObject *kv, *rv;\r
2388 kv = PyString_FromString(key);\r
2389 if (kv == NULL)\r
2390 return NULL;\r
2391 rv = PyDict_GetItem(v, kv);\r
2392 Py_DECREF(kv);\r
2393 return rv;\r
2394}\r
2395\r
2396int\r
2397PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)\r
2398{\r
2399 PyObject *kv;\r
2400 int err;\r
2401 kv = PyString_FromString(key);\r
2402 if (kv == NULL)\r
2403 return -1;\r
2404 PyString_InternInPlace(&kv); /* XXX Should we really? */\r
2405 err = PyDict_SetItem(v, kv, item);\r
2406 Py_DECREF(kv);\r
2407 return err;\r
2408}\r
2409\r
2410int\r
2411PyDict_DelItemString(PyObject *v, const char *key)\r
2412{\r
2413 PyObject *kv;\r
2414 int err;\r
2415 kv = PyString_FromString(key);\r
2416 if (kv == NULL)\r
2417 return -1;\r
2418 err = PyDict_DelItem(v, kv);\r
2419 Py_DECREF(kv);\r
2420 return err;\r
2421}\r
2422\r
2423/* Dictionary iterator types */\r
2424\r
2425typedef struct {\r
2426 PyObject_HEAD\r
2427 PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */\r
2428 Py_ssize_t di_used;\r
2429 Py_ssize_t di_pos;\r
2430 PyObject* di_result; /* reusable result tuple for iteritems */\r
2431 Py_ssize_t len;\r
2432} dictiterobject;\r
2433\r
2434static PyObject *\r
2435dictiter_new(PyDictObject *dict, PyTypeObject *itertype)\r
2436{\r
2437 dictiterobject *di;\r
2438 di = PyObject_GC_New(dictiterobject, itertype);\r
2439 if (di == NULL)\r
2440 return NULL;\r
2441 Py_INCREF(dict);\r
2442 di->di_dict = dict;\r
2443 di->di_used = dict->ma_used;\r
2444 di->di_pos = 0;\r
2445 di->len = dict->ma_used;\r
2446 if (itertype == &PyDictIterItem_Type) {\r
2447 di->di_result = PyTuple_Pack(2, Py_None, Py_None);\r
2448 if (di->di_result == NULL) {\r
2449 Py_DECREF(di);\r
2450 return NULL;\r
2451 }\r
2452 }\r
2453 else\r
2454 di->di_result = NULL;\r
2455 _PyObject_GC_TRACK(di);\r
2456 return (PyObject *)di;\r
2457}\r
2458\r
2459static void\r
2460dictiter_dealloc(dictiterobject *di)\r
2461{\r
2462 Py_XDECREF(di->di_dict);\r
2463 Py_XDECREF(di->di_result);\r
2464 PyObject_GC_Del(di);\r
2465}\r
2466\r
2467static int\r
2468dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)\r
2469{\r
2470 Py_VISIT(di->di_dict);\r
2471 Py_VISIT(di->di_result);\r
2472 return 0;\r
2473}\r
2474\r
2475static PyObject *\r
2476dictiter_len(dictiterobject *di)\r
2477{\r
2478 Py_ssize_t len = 0;\r
2479 if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)\r
2480 len = di->len;\r
2481 return PyInt_FromSize_t(len);\r
2482}\r
2483\r
2484PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");\r
2485\r
2486static PyMethodDef dictiter_methods[] = {\r
2487 {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS, length_hint_doc},\r
2488 {NULL, NULL} /* sentinel */\r
2489};\r
2490\r
2491static PyObject *dictiter_iternextkey(dictiterobject *di)\r
2492{\r
2493 PyObject *key;\r
2494 register Py_ssize_t i, mask;\r
2495 register PyDictEntry *ep;\r
2496 PyDictObject *d = di->di_dict;\r
2497\r
2498 if (d == NULL)\r
2499 return NULL;\r
2500 assert (PyDict_Check(d));\r
2501\r
2502 if (di->di_used != d->ma_used) {\r
2503 PyErr_SetString(PyExc_RuntimeError,\r
2504 "dictionary changed size during iteration");\r
2505 di->di_used = -1; /* Make this state sticky */\r
2506 return NULL;\r
2507 }\r
2508\r
2509 i = di->di_pos;\r
2510 if (i < 0)\r
2511 goto fail;\r
2512 ep = d->ma_table;\r
2513 mask = d->ma_mask;\r
2514 while (i <= mask && ep[i].me_value == NULL)\r
2515 i++;\r
2516 di->di_pos = i+1;\r
2517 if (i > mask)\r
2518 goto fail;\r
2519 di->len--;\r
2520 key = ep[i].me_key;\r
2521 Py_INCREF(key);\r
2522 return key;\r
2523\r
2524fail:\r
2525 Py_DECREF(d);\r
2526 di->di_dict = NULL;\r
2527 return NULL;\r
2528}\r
2529\r
2530PyTypeObject PyDictIterKey_Type = {\r
2531 PyVarObject_HEAD_INIT(&PyType_Type, 0)\r
2532 "dictionary-keyiterator", /* tp_name */\r
2533 sizeof(dictiterobject), /* tp_basicsize */\r
2534 0, /* tp_itemsize */\r
2535 /* methods */\r
2536 (destructor)dictiter_dealloc, /* tp_dealloc */\r
2537 0, /* tp_print */\r
2538 0, /* tp_getattr */\r
2539 0, /* tp_setattr */\r
2540 0, /* tp_compare */\r
2541 0, /* tp_repr */\r
2542 0, /* tp_as_number */\r
2543 0, /* tp_as_sequence */\r
2544 0, /* tp_as_mapping */\r
2545 0, /* tp_hash */\r
2546 0, /* tp_call */\r
2547 0, /* tp_str */\r
2548 PyObject_GenericGetAttr, /* tp_getattro */\r
2549 0, /* tp_setattro */\r
2550 0, /* tp_as_buffer */\r
2551 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */\r
2552 0, /* tp_doc */\r
2553 (traverseproc)dictiter_traverse, /* tp_traverse */\r
2554 0, /* tp_clear */\r
2555 0, /* tp_richcompare */\r
2556 0, /* tp_weaklistoffset */\r
2557 PyObject_SelfIter, /* tp_iter */\r
2558 (iternextfunc)dictiter_iternextkey, /* tp_iternext */\r
2559 dictiter_methods, /* tp_methods */\r
2560 0,\r
2561};\r
2562\r
2563static PyObject *dictiter_iternextvalue(dictiterobject *di)\r
2564{\r
2565 PyObject *value;\r
2566 register Py_ssize_t i, mask;\r
2567 register PyDictEntry *ep;\r
2568 PyDictObject *d = di->di_dict;\r
2569\r
2570 if (d == NULL)\r
2571 return NULL;\r
2572 assert (PyDict_Check(d));\r
2573\r
2574 if (di->di_used != d->ma_used) {\r
2575 PyErr_SetString(PyExc_RuntimeError,\r
2576 "dictionary changed size during iteration");\r
2577 di->di_used = -1; /* Make this state sticky */\r
2578 return NULL;\r
2579 }\r
2580\r
2581 i = di->di_pos;\r
2582 mask = d->ma_mask;\r
2583 if (i < 0 || i > mask)\r
2584 goto fail;\r
2585 ep = d->ma_table;\r
2586 while ((value=ep[i].me_value) == NULL) {\r
2587 i++;\r
2588 if (i > mask)\r
2589 goto fail;\r
2590 }\r
2591 di->di_pos = i+1;\r
2592 di->len--;\r
2593 Py_INCREF(value);\r
2594 return value;\r
2595\r
2596fail:\r
2597 Py_DECREF(d);\r
2598 di->di_dict = NULL;\r
2599 return NULL;\r
2600}\r
2601\r
2602PyTypeObject PyDictIterValue_Type = {\r
2603 PyVarObject_HEAD_INIT(&PyType_Type, 0)\r
2604 "dictionary-valueiterator", /* tp_name */\r
2605 sizeof(dictiterobject), /* tp_basicsize */\r
2606 0, /* tp_itemsize */\r
2607 /* methods */\r
2608 (destructor)dictiter_dealloc, /* tp_dealloc */\r
2609 0, /* tp_print */\r
2610 0, /* tp_getattr */\r
2611 0, /* tp_setattr */\r
2612 0, /* tp_compare */\r
2613 0, /* tp_repr */\r
2614 0, /* tp_as_number */\r
2615 0, /* tp_as_sequence */\r
2616 0, /* tp_as_mapping */\r
2617 0, /* tp_hash */\r
2618 0, /* tp_call */\r
2619 0, /* tp_str */\r
2620 PyObject_GenericGetAttr, /* tp_getattro */\r
2621 0, /* tp_setattro */\r
2622 0, /* tp_as_buffer */\r
2623 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */\r
2624 0, /* tp_doc */\r
2625 (traverseproc)dictiter_traverse, /* tp_traverse */\r
2626 0, /* tp_clear */\r
2627 0, /* tp_richcompare */\r
2628 0, /* tp_weaklistoffset */\r
2629 PyObject_SelfIter, /* tp_iter */\r
2630 (iternextfunc)dictiter_iternextvalue, /* tp_iternext */\r
2631 dictiter_methods, /* tp_methods */\r
2632 0,\r
2633};\r
2634\r
2635static PyObject *dictiter_iternextitem(dictiterobject *di)\r
2636{\r
2637 PyObject *key, *value, *result = di->di_result;\r
2638 register Py_ssize_t i, mask;\r
2639 register PyDictEntry *ep;\r
2640 PyDictObject *d = di->di_dict;\r
2641\r
2642 if (d == NULL)\r
2643 return NULL;\r
2644 assert (PyDict_Check(d));\r
2645\r
2646 if (di->di_used != d->ma_used) {\r
2647 PyErr_SetString(PyExc_RuntimeError,\r
2648 "dictionary changed size during iteration");\r
2649 di->di_used = -1; /* Make this state sticky */\r
2650 return NULL;\r
2651 }\r
2652\r
2653 i = di->di_pos;\r
2654 if (i < 0)\r
2655 goto fail;\r
2656 ep = d->ma_table;\r
2657 mask = d->ma_mask;\r
2658 while (i <= mask && ep[i].me_value == NULL)\r
2659 i++;\r
2660 di->di_pos = i+1;\r
2661 if (i > mask)\r
2662 goto fail;\r
2663\r
2664 if (result->ob_refcnt == 1) {\r
2665 Py_INCREF(result);\r
2666 Py_DECREF(PyTuple_GET_ITEM(result, 0));\r
2667 Py_DECREF(PyTuple_GET_ITEM(result, 1));\r
2668 } else {\r
2669 result = PyTuple_New(2);\r
2670 if (result == NULL)\r
2671 return NULL;\r
2672 }\r
2673 di->len--;\r
2674 key = ep[i].me_key;\r
2675 value = ep[i].me_value;\r
2676 Py_INCREF(key);\r
2677 Py_INCREF(value);\r
2678 PyTuple_SET_ITEM(result, 0, key);\r
2679 PyTuple_SET_ITEM(result, 1, value);\r
2680 return result;\r
2681\r
2682fail:\r
2683 Py_DECREF(d);\r
2684 di->di_dict = NULL;\r
2685 return NULL;\r
2686}\r
2687\r
2688PyTypeObject PyDictIterItem_Type = {\r
2689 PyVarObject_HEAD_INIT(&PyType_Type, 0)\r
2690 "dictionary-itemiterator", /* tp_name */\r
2691 sizeof(dictiterobject), /* tp_basicsize */\r
2692 0, /* tp_itemsize */\r
2693 /* methods */\r
2694 (destructor)dictiter_dealloc, /* tp_dealloc */\r
2695 0, /* tp_print */\r
2696 0, /* tp_getattr */\r
2697 0, /* tp_setattr */\r
2698 0, /* tp_compare */\r
2699 0, /* tp_repr */\r
2700 0, /* tp_as_number */\r
2701 0, /* tp_as_sequence */\r
2702 0, /* tp_as_mapping */\r
2703 0, /* tp_hash */\r
2704 0, /* tp_call */\r
2705 0, /* tp_str */\r
2706 PyObject_GenericGetAttr, /* tp_getattro */\r
2707 0, /* tp_setattro */\r
2708 0, /* tp_as_buffer */\r
2709 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */\r
2710 0, /* tp_doc */\r
2711 (traverseproc)dictiter_traverse, /* tp_traverse */\r
2712 0, /* tp_clear */\r
2713 0, /* tp_richcompare */\r
2714 0, /* tp_weaklistoffset */\r
2715 PyObject_SelfIter, /* tp_iter */\r
2716 (iternextfunc)dictiter_iternextitem, /* tp_iternext */\r
2717 dictiter_methods, /* tp_methods */\r
2718 0,\r
2719};\r
2720\r
2721/***********************************************/\r
2722/* View objects for keys(), items(), values(). */\r
2723/***********************************************/\r
2724\r
2725/* The instance lay-out is the same for all three; but the type differs. */\r
2726\r
2727typedef struct {\r
2728 PyObject_HEAD\r
2729 PyDictObject *dv_dict;\r
2730} dictviewobject;\r
2731\r
2732\r
2733static void\r
2734dictview_dealloc(dictviewobject *dv)\r
2735{\r
2736 Py_XDECREF(dv->dv_dict);\r
2737 PyObject_GC_Del(dv);\r
2738}\r
2739\r
2740static int\r
2741dictview_traverse(dictviewobject *dv, visitproc visit, void *arg)\r
2742{\r
2743 Py_VISIT(dv->dv_dict);\r
2744 return 0;\r
2745}\r
2746\r
2747static Py_ssize_t\r
2748dictview_len(dictviewobject *dv)\r
2749{\r
2750 Py_ssize_t len = 0;\r
2751 if (dv->dv_dict != NULL)\r
2752 len = dv->dv_dict->ma_used;\r
2753 return len;\r
2754}\r
2755\r
2756static PyObject *\r
2757dictview_new(PyObject *dict, PyTypeObject *type)\r
2758{\r
2759 dictviewobject *dv;\r
2760 if (dict == NULL) {\r
2761 PyErr_BadInternalCall();\r
2762 return NULL;\r
2763 }\r
2764 if (!PyDict_Check(dict)) {\r
2765 /* XXX Get rid of this restriction later */\r
2766 PyErr_Format(PyExc_TypeError,\r
2767 "%s() requires a dict argument, not '%s'",\r
2768 type->tp_name, dict->ob_type->tp_name);\r
2769 return NULL;\r
2770 }\r
2771 dv = PyObject_GC_New(dictviewobject, type);\r
2772 if (dv == NULL)\r
2773 return NULL;\r
2774 Py_INCREF(dict);\r
2775 dv->dv_dict = (PyDictObject *)dict;\r
2776 _PyObject_GC_TRACK(dv);\r
2777 return (PyObject *)dv;\r
2778}\r
2779\r
2780/* TODO(guido): The views objects are not complete:\r
2781\r
2782 * support more set operations\r
2783 * support arbitrary mappings?\r
2784 - either these should be static or exported in dictobject.h\r
2785 - if public then they should probably be in builtins\r
2786*/\r
2787\r
2788/* Return 1 if self is a subset of other, iterating over self;\r
2789 0 if not; -1 if an error occurred. */\r
2790static int\r
2791all_contained_in(PyObject *self, PyObject *other)\r
2792{\r
2793 PyObject *iter = PyObject_GetIter(self);\r
2794 int ok = 1;\r
2795\r
2796 if (iter == NULL)\r
2797 return -1;\r
2798 for (;;) {\r
2799 PyObject *next = PyIter_Next(iter);\r
2800 if (next == NULL) {\r
2801 if (PyErr_Occurred())\r
2802 ok = -1;\r
2803 break;\r
2804 }\r
2805 ok = PySequence_Contains(other, next);\r
2806 Py_DECREF(next);\r
2807 if (ok <= 0)\r
2808 break;\r
2809 }\r
2810 Py_DECREF(iter);\r
2811 return ok;\r
2812}\r
2813\r
2814static PyObject *\r
2815dictview_richcompare(PyObject *self, PyObject *other, int op)\r
2816{\r
2817 Py_ssize_t len_self, len_other;\r
2818 int ok;\r
2819 PyObject *result;\r
2820\r
2821 assert(self != NULL);\r
2822 assert(PyDictViewSet_Check(self));\r
2823 assert(other != NULL);\r
2824\r
2825 if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other)) {\r
2826 Py_INCREF(Py_NotImplemented);\r
2827 return Py_NotImplemented;\r
2828 }\r
2829\r
2830 len_self = PyObject_Size(self);\r
2831 if (len_self < 0)\r
2832 return NULL;\r
2833 len_other = PyObject_Size(other);\r
2834 if (len_other < 0)\r
2835 return NULL;\r
2836\r
2837 ok = 0;\r
2838 switch(op) {\r
2839\r
2840 case Py_NE:\r
2841 case Py_EQ:\r
2842 if (len_self == len_other)\r
2843 ok = all_contained_in(self, other);\r
2844 if (op == Py_NE && ok >= 0)\r
2845 ok = !ok;\r
2846 break;\r
2847\r
2848 case Py_LT:\r
2849 if (len_self < len_other)\r
2850 ok = all_contained_in(self, other);\r
2851 break;\r
2852\r
2853 case Py_LE:\r
2854 if (len_self <= len_other)\r
2855 ok = all_contained_in(self, other);\r
2856 break;\r
2857\r
2858 case Py_GT:\r
2859 if (len_self > len_other)\r
2860 ok = all_contained_in(other, self);\r
2861 break;\r
2862\r
2863 case Py_GE:\r
2864 if (len_self >= len_other)\r
2865 ok = all_contained_in(other, self);\r
2866 break;\r
2867\r
2868 }\r
2869 if (ok < 0)\r
2870 return NULL;\r
2871 result = ok ? Py_True : Py_False;\r
2872 Py_INCREF(result);\r
2873 return result;\r
2874}\r
2875\r
2876static PyObject *\r
2877dictview_repr(dictviewobject *dv)\r
2878{\r
2879 PyObject *seq;\r
2880 PyObject *seq_str;\r
2881 PyObject *result;\r
2882\r
2883 seq = PySequence_List((PyObject *)dv);\r
2884 if (seq == NULL)\r
2885 return NULL;\r
2886\r
2887 seq_str = PyObject_Repr(seq);\r
2888 result = PyString_FromFormat("%s(%s)", Py_TYPE(dv)->tp_name,\r
2889 PyString_AS_STRING(seq_str));\r
2890 Py_DECREF(seq_str);\r
2891 Py_DECREF(seq);\r
2892 return result;\r
2893}\r
2894\r
2895/*** dict_keys ***/\r
2896\r
2897static PyObject *\r
2898dictkeys_iter(dictviewobject *dv)\r
2899{\r
2900 if (dv->dv_dict == NULL) {\r
2901 Py_RETURN_NONE;\r
2902 }\r
2903 return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);\r
2904}\r
2905\r
2906static int\r
2907dictkeys_contains(dictviewobject *dv, PyObject *obj)\r
2908{\r
2909 if (dv->dv_dict == NULL)\r
2910 return 0;\r
2911 return PyDict_Contains((PyObject *)dv->dv_dict, obj);\r
2912}\r
2913\r
2914static PySequenceMethods dictkeys_as_sequence = {\r
2915 (lenfunc)dictview_len, /* sq_length */\r
2916 0, /* sq_concat */\r
2917 0, /* sq_repeat */\r
2918 0, /* sq_item */\r
2919 0, /* sq_slice */\r
2920 0, /* sq_ass_item */\r
2921 0, /* sq_ass_slice */\r
2922 (objobjproc)dictkeys_contains, /* sq_contains */\r
2923};\r
2924\r
2925static PyObject*\r
2926dictviews_sub(PyObject* self, PyObject *other)\r
2927{\r
2928 PyObject *result = PySet_New(self);\r
2929 PyObject *tmp;\r
2930 if (result == NULL)\r
2931 return NULL;\r
2932\r
2933 tmp = PyObject_CallMethod(result, "difference_update", "O", other);\r
2934 if (tmp == NULL) {\r
2935 Py_DECREF(result);\r
2936 return NULL;\r
2937 }\r
2938\r
2939 Py_DECREF(tmp);\r
2940 return result;\r
2941}\r
2942\r
2943static PyObject*\r
2944dictviews_and(PyObject* self, PyObject *other)\r
2945{\r
2946 PyObject *result = PySet_New(self);\r
2947 PyObject *tmp;\r
2948 if (result == NULL)\r
2949 return NULL;\r
2950\r
2951 tmp = PyObject_CallMethod(result, "intersection_update", "O", other);\r
2952 if (tmp == NULL) {\r
2953 Py_DECREF(result);\r
2954 return NULL;\r
2955 }\r
2956\r
2957 Py_DECREF(tmp);\r
2958 return result;\r
2959}\r
2960\r
2961static PyObject*\r
2962dictviews_or(PyObject* self, PyObject *other)\r
2963{\r
2964 PyObject *result = PySet_New(self);\r
2965 PyObject *tmp;\r
2966 if (result == NULL)\r
2967 return NULL;\r
2968\r
2969 tmp = PyObject_CallMethod(result, "update", "O", other);\r
2970 if (tmp == NULL) {\r
2971 Py_DECREF(result);\r
2972 return NULL;\r
2973 }\r
2974\r
2975 Py_DECREF(tmp);\r
2976 return result;\r
2977}\r
2978\r
2979static PyObject*\r
2980dictviews_xor(PyObject* self, PyObject *other)\r
2981{\r
2982 PyObject *result = PySet_New(self);\r
2983 PyObject *tmp;\r
2984 if (result == NULL)\r
2985 return NULL;\r
2986\r
2987 tmp = PyObject_CallMethod(result, "symmetric_difference_update", "O",\r
2988 other);\r
2989 if (tmp == NULL) {\r
2990 Py_DECREF(result);\r
2991 return NULL;\r
2992 }\r
2993\r
2994 Py_DECREF(tmp);\r
2995 return result;\r
2996}\r
2997\r
2998static PyNumberMethods dictviews_as_number = {\r
2999 0, /*nb_add*/\r
3000 (binaryfunc)dictviews_sub, /*nb_subtract*/\r
3001 0, /*nb_multiply*/\r
3002 0, /*nb_divide*/\r
3003 0, /*nb_remainder*/\r
3004 0, /*nb_divmod*/\r
3005 0, /*nb_power*/\r
3006 0, /*nb_negative*/\r
3007 0, /*nb_positive*/\r
3008 0, /*nb_absolute*/\r
3009 0, /*nb_nonzero*/\r
3010 0, /*nb_invert*/\r
3011 0, /*nb_lshift*/\r
3012 0, /*nb_rshift*/\r
3013 (binaryfunc)dictviews_and, /*nb_and*/\r
3014 (binaryfunc)dictviews_xor, /*nb_xor*/\r
3015 (binaryfunc)dictviews_or, /*nb_or*/\r
3016};\r
3017\r
3018static PyMethodDef dictkeys_methods[] = {\r
3019 {NULL, NULL} /* sentinel */\r
3020};\r
3021\r
3022PyTypeObject PyDictKeys_Type = {\r
3023 PyVarObject_HEAD_INIT(&PyType_Type, 0)\r
3024 "dict_keys", /* tp_name */\r
3025 sizeof(dictviewobject), /* tp_basicsize */\r
3026 0, /* tp_itemsize */\r
3027 /* methods */\r
3028 (destructor)dictview_dealloc, /* tp_dealloc */\r
3029 0, /* tp_print */\r
3030 0, /* tp_getattr */\r
3031 0, /* tp_setattr */\r
3032 0, /* tp_reserved */\r
3033 (reprfunc)dictview_repr, /* tp_repr */\r
3034 &dictviews_as_number, /* tp_as_number */\r
3035 &dictkeys_as_sequence, /* tp_as_sequence */\r
3036 0, /* tp_as_mapping */\r
3037 0, /* tp_hash */\r
3038 0, /* tp_call */\r
3039 0, /* tp_str */\r
3040 PyObject_GenericGetAttr, /* tp_getattro */\r
3041 0, /* tp_setattro */\r
3042 0, /* tp_as_buffer */\r
3043 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |\r
3044 Py_TPFLAGS_CHECKTYPES, /* tp_flags */\r
3045 0, /* tp_doc */\r
3046 (traverseproc)dictview_traverse, /* tp_traverse */\r
3047 0, /* tp_clear */\r
3048 dictview_richcompare, /* tp_richcompare */\r
3049 0, /* tp_weaklistoffset */\r
3050 (getiterfunc)dictkeys_iter, /* tp_iter */\r
3051 0, /* tp_iternext */\r
3052 dictkeys_methods, /* tp_methods */\r
3053 0,\r
3054};\r
3055\r
3056static PyObject *\r
3057dictkeys_new(PyObject *dict)\r
3058{\r
3059 return dictview_new(dict, &PyDictKeys_Type);\r
3060}\r
3061\r
3062/*** dict_items ***/\r
3063\r
3064static PyObject *\r
3065dictitems_iter(dictviewobject *dv)\r
3066{\r
3067 if (dv->dv_dict == NULL) {\r
3068 Py_RETURN_NONE;\r
3069 }\r
3070 return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);\r
3071}\r
3072\r
3073static int\r
3074dictitems_contains(dictviewobject *dv, PyObject *obj)\r
3075{\r
3076 PyObject *key, *value, *found;\r
3077 if (dv->dv_dict == NULL)\r
3078 return 0;\r
3079 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)\r
3080 return 0;\r
3081 key = PyTuple_GET_ITEM(obj, 0);\r
3082 value = PyTuple_GET_ITEM(obj, 1);\r
3083 found = PyDict_GetItem((PyObject *)dv->dv_dict, key);\r
3084 if (found == NULL) {\r
3085 if (PyErr_Occurred())\r
3086 return -1;\r
3087 return 0;\r
3088 }\r
3089 return PyObject_RichCompareBool(value, found, Py_EQ);\r
3090}\r
3091\r
3092static PySequenceMethods dictitems_as_sequence = {\r
3093 (lenfunc)dictview_len, /* sq_length */\r
3094 0, /* sq_concat */\r
3095 0, /* sq_repeat */\r
3096 0, /* sq_item */\r
3097 0, /* sq_slice */\r
3098 0, /* sq_ass_item */\r
3099 0, /* sq_ass_slice */\r
3100 (objobjproc)dictitems_contains, /* sq_contains */\r
3101};\r
3102\r
3103static PyMethodDef dictitems_methods[] = {\r
3104 {NULL, NULL} /* sentinel */\r
3105};\r
3106\r
3107PyTypeObject PyDictItems_Type = {\r
3108 PyVarObject_HEAD_INIT(&PyType_Type, 0)\r
3109 "dict_items", /* tp_name */\r
3110 sizeof(dictviewobject), /* tp_basicsize */\r
3111 0, /* tp_itemsize */\r
3112 /* methods */\r
3113 (destructor)dictview_dealloc, /* tp_dealloc */\r
3114 0, /* tp_print */\r
3115 0, /* tp_getattr */\r
3116 0, /* tp_setattr */\r
3117 0, /* tp_reserved */\r
3118 (reprfunc)dictview_repr, /* tp_repr */\r
3119 &dictviews_as_number, /* tp_as_number */\r
3120 &dictitems_as_sequence, /* tp_as_sequence */\r
3121 0, /* tp_as_mapping */\r
3122 0, /* tp_hash */\r
3123 0, /* tp_call */\r
3124 0, /* tp_str */\r
3125 PyObject_GenericGetAttr, /* tp_getattro */\r
3126 0, /* tp_setattro */\r
3127 0, /* tp_as_buffer */\r
3128 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |\r
3129 Py_TPFLAGS_CHECKTYPES, /* tp_flags */\r
3130 0, /* tp_doc */\r
3131 (traverseproc)dictview_traverse, /* tp_traverse */\r
3132 0, /* tp_clear */\r
3133 dictview_richcompare, /* tp_richcompare */\r
3134 0, /* tp_weaklistoffset */\r
3135 (getiterfunc)dictitems_iter, /* tp_iter */\r
3136 0, /* tp_iternext */\r
3137 dictitems_methods, /* tp_methods */\r
3138 0,\r
3139};\r
3140\r
3141static PyObject *\r
3142dictitems_new(PyObject *dict)\r
3143{\r
3144 return dictview_new(dict, &PyDictItems_Type);\r
3145}\r
3146\r
3147/*** dict_values ***/\r
3148\r
3149static PyObject *\r
3150dictvalues_iter(dictviewobject *dv)\r
3151{\r
3152 if (dv->dv_dict == NULL) {\r
3153 Py_RETURN_NONE;\r
3154 }\r
3155 return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);\r
3156}\r
3157\r
3158static PySequenceMethods dictvalues_as_sequence = {\r
3159 (lenfunc)dictview_len, /* sq_length */\r
3160 0, /* sq_concat */\r
3161 0, /* sq_repeat */\r
3162 0, /* sq_item */\r
3163 0, /* sq_slice */\r
3164 0, /* sq_ass_item */\r
3165 0, /* sq_ass_slice */\r
3166 (objobjproc)0, /* sq_contains */\r
3167};\r
3168\r
3169static PyMethodDef dictvalues_methods[] = {\r
3170 {NULL, NULL} /* sentinel */\r
3171};\r
3172\r
3173PyTypeObject PyDictValues_Type = {\r
3174 PyVarObject_HEAD_INIT(&PyType_Type, 0)\r
3175 "dict_values", /* tp_name */\r
3176 sizeof(dictviewobject), /* tp_basicsize */\r
3177 0, /* tp_itemsize */\r
3178 /* methods */\r
3179 (destructor)dictview_dealloc, /* tp_dealloc */\r
3180 0, /* tp_print */\r
3181 0, /* tp_getattr */\r
3182 0, /* tp_setattr */\r
3183 0, /* tp_reserved */\r
3184 (reprfunc)dictview_repr, /* tp_repr */\r
3185 0, /* tp_as_number */\r
3186 &dictvalues_as_sequence, /* tp_as_sequence */\r
3187 0, /* tp_as_mapping */\r
3188 0, /* tp_hash */\r
3189 0, /* tp_call */\r
3190 0, /* tp_str */\r
3191 PyObject_GenericGetAttr, /* tp_getattro */\r
3192 0, /* tp_setattro */\r
3193 0, /* tp_as_buffer */\r
3194 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */\r
3195 0, /* tp_doc */\r
3196 (traverseproc)dictview_traverse, /* tp_traverse */\r
3197 0, /* tp_clear */\r
3198 0, /* tp_richcompare */\r
3199 0, /* tp_weaklistoffset */\r
3200 (getiterfunc)dictvalues_iter, /* tp_iter */\r
3201 0, /* tp_iternext */\r
3202 dictvalues_methods, /* tp_methods */\r
3203 0,\r
3204};\r
3205\r
3206static PyObject *\r
3207dictvalues_new(PyObject *dict)\r
3208{\r
3209 return dictview_new(dict, &PyDictValues_Type);\r
3210}\r