PageRenderTime 64ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/Objects/dictobject.c

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