File: /Users/paulross/dev/Python-3.6.2/Objects/dictobject.c

Green shading in the line number column means the source is part of the translation unit, red means it is conditionally excluded. Highlighted line numbers link to the translation unit page. Highlighted macros link to the macro page.

       1: /* Dictionary object implementation using a hash table */
       2: 
       3: /* The distribution includes a separate file, Objects/dictnotes.txt,
       4:    describing explorations into dictionary design and optimization.
       5:    It covers typical dictionary use patterns, the parameters for
       6:    tuning dictionaries, and several ideas for possible optimizations.
       7: */
       8: 
       9: /* PyDictKeysObject
      10: 
      11: This implements the dictionary's hashtable.
      12: 
      13: As of Python 3.6, this is compact and ordered. Basic idea is described here.
      14: https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html
      15: 
      16: layout:
      17: 
      18: +---------------+
      19: | dk_refcnt     |
      20: | dk_size       |
      21: | dk_lookup     |
      22: | dk_usable     |
      23: | dk_nentries   |
      24: +---------------+
      25: | dk_indices    |
      26: |               |
      27: +---------------+
      28: | dk_entries    |
      29: |               |
      30: +---------------+
      31: 
      32: dk_indices is actual hashtable.  It holds index in entries, or DKIX_EMPTY(-1)
      33: or DKIX_DUMMY(-2).
      34: Size of indices is dk_size.  Type of each index in indices is vary on dk_size:
      35: 
      36: * int8  for          dk_size <= 128
      37: * int16 for 256   <= dk_size <= 2**15
      38: * int32 for 2**16 <= dk_size <= 2**31
      39: * int64 for 2**32 <= dk_size
      40: 
      41: dk_entries is array of PyDictKeyEntry.  It's size is USABLE_FRACTION(dk_size).
      42: DK_ENTRIES(dk) can be used to get pointer to entries.
      43: 
      44: NOTE: Since negative value is used for DKIX_EMPTY and DKIX_DUMMY, type of
      45: dk_indices entry is signed integer and int16 is used for table which
      46: dk_size == 256.
      47: */
      48: 
      49: 
      50: /*
      51: The DictObject can be in one of two forms.
      52: 
      53: Either:
      54:   A combined table:
      55:     ma_values == NULL, dk_refcnt == 1.
      56:     Values are stored in the me_value field of the PyDictKeysObject.
      57: Or:
      58:   A split table:
      59:     ma_values != NULL, dk_refcnt >= 1
      60:     Values are stored in the ma_values array.
      61:     Only string (unicode) keys are allowed.
      62:     All dicts sharing same key must have same insertion order.
      63: 
      64: There are four kinds of slots in the table (slot is index, and
      65: DK_ENTRIES(keys)[index] if index >= 0):
      66: 
      67: 1. Unused.  index == DKIX_EMPTY
      68:    Does not hold an active (key, value) pair now and never did.  Unused can
      69:    transition to Active upon key insertion.  This is each slot's initial state.
      70: 
      71: 2. Active.  index >= 0, me_key != NULL and me_value != NULL
      72:    Holds an active (key, value) pair.  Active can transition to Dummy or
      73:    Pending upon key deletion (for combined and split tables respectively).
      74:    This is the only case in which me_value != NULL.
      75: 
      76: 3. Dummy.  index == DKIX_DUMMY  (combined only)
      77:    Previously held an active (key, value) pair, but that was deleted and an
      78:    active pair has not yet overwritten the slot.  Dummy can transition to
      79:    Active upon key insertion.  Dummy slots cannot be made Unused again
      80:    else the probe sequence in case of collision would have no way to know
      81:    they were once active.
      82: 
      83: 4. Pending. index >= 0, key != NULL, and value == NULL  (split only)
      84:    Not yet inserted in split-table.
      85: */
      86: 
      87: /*
      88: Preserving insertion order
      89: 
      90: It's simple for combined table.  Since dk_entries is mostly append only, we can
      91: get insertion order by just iterating dk_entries.
      92: 
      93: One exception is .popitem().  It removes last item in dk_entries and decrement
      94: dk_nentries to achieve amortized O(1).  Since there are DKIX_DUMMY remains in
      95: dk_indices, we can't increment dk_usable even though dk_nentries is
      96: decremented.
      97: 
      98: In split table, inserting into pending entry is allowed only for dk_entries[ix]
      99: where ix == mp->ma_used. Inserting into other index and deleting item cause
     100: converting the dict to the combined table.
     101: */
     102: 
     103: /* PyDict_MINSIZE is the starting size for any new dict.
     104:  * 8 allows dicts with no more than 5 active entries; experiments suggested
     105:  * this suffices for the majority of dicts (consisting mostly of usually-small
     106:  * dicts created to pass keyword arguments).
     107:  * Making this 8, rather than 4 reduces the number of resizes for most
     108:  * dictionaries, without any significant extra memory use.
     109:  */
     110: #define PyDict_MINSIZE 8
     111: 
     112: #include "Python.h"
     113: #include "dict-common.h"
     114: #include "stringlib/eq.h"    /* to get unicode_eq() */
     115: 
     116: /*[clinic input]
     117: class dict "PyDictObject *" "&PyDict_Type"
     118: [clinic start generated code]*/
     119: /*[clinic end generated code: output=da39a3ee5e6b4b0d input=f157a5a0ce9589d6]*/
     120: 
     121: 
     122: /*
     123: To ensure the lookup algorithm terminates, there must be at least one Unused
     124: slot (NULL key) in the table.
     125: To avoid slowing down lookups on a near-full table, we resize the table when
     126: it's USABLE_FRACTION (currently two-thirds) full.
     127: */
     128: 
     129: #define PERTURB_SHIFT 5
     130: 
     131: /*
     132: Major subtleties ahead:  Most hash schemes depend on having a "good" hash
     133: function, in the sense of simulating randomness.  Python doesn't:  its most
     134: important hash functions (for ints) are very regular in common
     135: cases:
     136: 
     137:   >>>[hash(i) for i in range(4)]
     138:   [0, 1, 2, 3]
     139: 
     140: This isn't necessarily bad!  To the contrary, in a table of size 2**i, taking
     141: the low-order i bits as the initial table index is extremely fast, and there
     142: are no collisions at all for dicts indexed by a contiguous range of ints. So
     143: this gives better-than-random behavior in common cases, and that's very
     144: desirable.
     145: 
     146: OTOH, when collisions occur, the tendency to fill contiguous slices of the
     147: hash table makes a good collision resolution strategy crucial.  Taking only
     148: the last i bits of the hash code is also vulnerable:  for example, consider
     149: the list [i << 16 for i in range(20000)] as a set of keys.  Since ints are
     150: their own hash codes, and this fits in a dict of size 2**15, the last 15 bits
     151:  of every hash code are all 0:  they *all* map to the same table index.
     152: 
     153: But catering to unusual cases should not slow the usual ones, so we just take
     154: the last i bits anyway.  It's up to collision resolution to do the rest.  If
     155: we *usually* find the key we're looking for on the first try (and, it turns
     156: out, we usually do -- the table load factor is kept under 2/3, so the odds
     157: are solidly in our favor), then it makes best sense to keep the initial index
     158: computation dirt cheap.
     159: 
     160: The first half of collision resolution is to visit table indices via this
     161: recurrence:
     162: 
     163:     j = ((5*j) + 1) mod 2**i
     164: 
     165: For any initial j in range(2**i), repeating that 2**i times generates each
     166: int in range(2**i) exactly once (see any text on random-number generation for
     167: proof).  By itself, this doesn't help much:  like linear probing (setting
     168: j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
     169: order.  This would be bad, except that's not the only thing we do, and it's
     170: actually *good* in the common cases where hash keys are consecutive.  In an
     171: example that's really too small to make this entirely clear, for a table of
     172: size 2**3 the order of indices is:
     173: 
     174:     0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
     175: 
     176: If two things come in at index 5, the first place we look after is index 2,
     177: not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
     178: Linear probing is deadly in this case because there the fixed probe order
     179: is the *same* as the order consecutive keys are likely to arrive.  But it's
     180: extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
     181: and certain that consecutive hash codes do not.
     182: 
     183: The other half of the strategy is to get the other bits of the hash code
     184: into play.  This is done by initializing a (unsigned) vrbl "perturb" to the
     185: full hash code, and changing the recurrence to:
     186: 
     187:     perturb >>= PERTURB_SHIFT;
     188:     j = (5*j) + 1 + perturb;
     189:     use j % 2**i as the next table index;
     190: 
     191: Now the probe sequence depends (eventually) on every bit in the hash code,
     192: and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
     193: because it quickly magnifies small differences in the bits that didn't affect
     194: the initial index.  Note that because perturb is unsigned, if the recurrence
     195: is executed often enough perturb eventually becomes and remains 0.  At that
     196: point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
     197: that's certain to find an empty slot eventually (since it generates every int
     198: in range(2**i), and we make sure there's always at least one empty slot).
     199: 
     200: Selecting a good value for PERTURB_SHIFT is a balancing act.  You want it
     201: small so that the high bits of the hash code continue to affect the probe
     202: sequence across iterations; but you want it large so that in really bad cases
     203: the high-order hash bits have an effect on early iterations.  5 was "the
     204: best" in minimizing total collisions across experiments Tim Peters ran (on
     205: both normal and pathological cases), but 4 and 6 weren't significantly worse.
     206: 
     207: Historical: Reimer Behrends contributed the idea of using a polynomial-based
     208: approach, using repeated multiplication by x in GF(2**n) where an irreducible
     209: polynomial for each table size was chosen such that x was a primitive root.
     210: Christian Tismer later extended that to use division by x instead, as an
     211: efficient way to get the high bits of the hash code into play.  This scheme
     212: also gave excellent collision statistics, but was more expensive:  two
     213: if-tests were required inside the loop; computing "the next" index took about
     214: the same number of operations but without as much potential parallelism
     215: (e.g., computing 5*j can go on at the same time as computing 1+perturb in the
     216: above, and then shifting perturb can be done while the table index is being
     217: masked); and the PyDictObject struct required a member to hold the table's
     218: polynomial.  In Tim's experiments the current scheme ran faster, produced
     219: equally good collision statistics, needed less code & used less memory.
     220: 
     221: */
     222: 
     223: /* forward declarations */
     224: static Py_ssize_t lookdict(PyDictObject *mp, PyObject *key,
     225:                            Py_hash_t hash, PyObject ***value_addr,
     226:                            Py_ssize_t *hashpos);
     227: static Py_ssize_t lookdict_unicode(PyDictObject *mp, PyObject *key,
     228:                                    Py_hash_t hash, PyObject ***value_addr,
     229:                                    Py_ssize_t *hashpos);
     230: static Py_ssize_t
     231: lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
     232:                          Py_hash_t hash, PyObject ***value_addr,
     233:                          Py_ssize_t *hashpos);
     234: static Py_ssize_t lookdict_split(PyDictObject *mp, PyObject *key,
     235:                                  Py_hash_t hash, PyObject ***value_addr,
     236:                                  Py_ssize_t *hashpos);
     237: 
     238: static int dictresize(PyDictObject *mp, Py_ssize_t minused);
     239: 
     240: /*Global counter used to set ma_version_tag field of dictionary.
     241:  * It is incremented each time that a dictionary is created and each
     242:  * time that a dictionary is modified. */
     243: static uint64_t pydict_global_version = 0;
     244: 
     245: #define DICT_NEXT_VERSION() (++pydict_global_version)
     246: 
     247: /* Dictionary reuse scheme to save calls to malloc and free */
     248: #ifndef PyDict_MAXFREELIST
     249: #define PyDict_MAXFREELIST 80
     250: #endif
     251: static PyDictObject *free_list[PyDict_MAXFREELIST];
     252: static int numfree = 0;
     253: static PyDictKeysObject *keys_free_list[PyDict_MAXFREELIST];
     254: static int numfreekeys = 0;
     255: 
     256: #include "clinic/dictobject.c.h"
     257: 
     258: int
     259: PyDict_ClearFreeList(void)
     260: {
     261:     PyDictObject *op;
     262:     int ret = numfree + numfreekeys;
     263:     while (numfree) {
     264:         op = free_list[--numfree];
     265:         assert(PyDict_CheckExact(op));
     266:         PyObject_GC_Del(op);
     267:     }
     268:     while (numfreekeys) {
     269:         PyObject_FREE(keys_free_list[--numfreekeys]);
     270:     }
     271:     return ret;
     272: }
     273: 
     274: /* Print summary info about the state of the optimized allocator */
     275: void
     276: _PyDict_DebugMallocStats(FILE *out)
     277: {
     278:     _PyDebugAllocatorStats(out,
     279:                            "free PyDictObject", numfree, sizeof(PyDictObject));
     280: }
     281: 
     282: 
     283: void
     284: PyDict_Fini(void)
     285: {
     286:     PyDict_ClearFreeList();
     287: }
     288: 
     289: #define DK_SIZE(dk) ((dk)->dk_size)
     290: #if SIZEOF_VOID_P > 4
     291: #define DK_IXSIZE(dk)                          \
     292:     (DK_SIZE(dk) <= 0xff ?                     \
     293:         1 : DK_SIZE(dk) <= 0xffff ?            \
     294:             2 : DK_SIZE(dk) <= 0xffffffff ?    \
     295:                 4 : sizeof(int64_t))
     296: #else
     297: #define DK_IXSIZE(dk)                          \
     298:     (DK_SIZE(dk) <= 0xff ?                     \
     299:         1 : DK_SIZE(dk) <= 0xffff ?            \
     300:             2 : sizeof(int32_t))
     301: #endif
     302: #define DK_ENTRIES(dk) \
     303:     ((PyDictKeyEntry*)(&(dk)->dk_indices.as_1[DK_SIZE(dk) * DK_IXSIZE(dk)]))
     304: 
     305: #define DK_DEBUG_INCREF _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA
     306: #define DK_DEBUG_DECREF _Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA
     307: 
     308: #define DK_INCREF(dk) (DK_DEBUG_INCREF ++(dk)->dk_refcnt)
     309: #define DK_DECREF(dk) if (DK_DEBUG_DECREF (--(dk)->dk_refcnt) == 0) free_keys_object(dk)
     310: #define DK_MASK(dk) (((dk)->dk_size)-1)
     311: #define IS_POWER_OF_2(x) (((x) & (x-1)) == 0)
     312: 
     313: /* lookup indices.  returns DKIX_EMPTY, DKIX_DUMMY, or ix >=0 */
     314: static inline Py_ssize_t
     315: dk_get_index(PyDictKeysObject *keys, Py_ssize_t i)
     316: {
     317:     Py_ssize_t s = DK_SIZE(keys);
     318:     Py_ssize_t ix;
     319: 
     320:     if (s <= 0xff) {
     321:         int8_t *indices = keys->dk_indices.as_1;
     322:         ix = indices[i];
     323:     }
     324:     else if (s <= 0xffff) {
     325:         int16_t *indices = keys->dk_indices.as_2;
     326:         ix = indices[i];
     327:     }
     328: #if SIZEOF_VOID_P > 4
     329:     else if (s > 0xffffffff) {
     330:         int64_t *indices = keys->dk_indices.as_8;
     331:         ix = indices[i];
     332:     }
     333: #endif
     334:     else {
     335:         int32_t *indices = keys->dk_indices.as_4;
     336:         ix = indices[i];
     337:     }
     338:     assert(ix >= DKIX_DUMMY);
     339:     return ix;
     340: }
     341: 
     342: /* write to indices. */
     343: static inline void
     344: dk_set_index(PyDictKeysObject *keys, Py_ssize_t i, Py_ssize_t ix)
     345: {
     346:     Py_ssize_t s = DK_SIZE(keys);
     347: 
     348:     assert(ix >= DKIX_DUMMY);
     349: 
     350:     if (s <= 0xff) {
     351:         int8_t *indices = keys->dk_indices.as_1;
     352:         assert(ix <= 0x7f);
     353:         indices[i] = (char)ix;
     354:     }
     355:     else if (s <= 0xffff) {
     356:         int16_t *indices = keys->dk_indices.as_2;
     357:         assert(ix <= 0x7fff);
     358:         indices[i] = (int16_t)ix;
     359:     }
     360: #if SIZEOF_VOID_P > 4
     361:     else if (s > 0xffffffff) {
     362:         int64_t *indices = keys->dk_indices.as_8;
     363:         indices[i] = ix;
     364:     }
     365: #endif
     366:     else {
     367:         int32_t *indices = keys->dk_indices.as_4;
     368:         assert(ix <= 0x7fffffff);
     369:         indices[i] = (int32_t)ix;
     370:     }
     371: }
     372: 
     373: 
     374: /* USABLE_FRACTION is the maximum dictionary load.
     375:  * Increasing this ratio makes dictionaries more dense resulting in more
     376:  * collisions.  Decreasing it improves sparseness at the expense of spreading
     377:  * indices over more cache lines and at the cost of total memory consumed.
     378:  *
     379:  * USABLE_FRACTION must obey the following:
     380:  *     (0 < USABLE_FRACTION(n) < n) for all n >= 2
     381:  *
     382:  * USABLE_FRACTION should be quick to calculate.
     383:  * Fractions around 1/2 to 2/3 seem to work well in practice.
     384:  */
     385: #define USABLE_FRACTION(n) (((n) << 1)/3)
     386: 
     387: /* ESTIMATE_SIZE is reverse function of USABLE_FRACTION.
     388:  * This can be used to reserve enough size to insert n entries without
     389:  * resizing.
     390:  */
     391: #define ESTIMATE_SIZE(n)  (((n)*3+1) >> 1)
     392: 
     393: /* Alternative fraction that is otherwise close enough to 2n/3 to make
     394:  * little difference. 8 * 2/3 == 8 * 5/8 == 5. 16 * 2/3 == 16 * 5/8 == 10.
     395:  * 32 * 2/3 = 21, 32 * 5/8 = 20.
     396:  * Its advantage is that it is faster to compute on machines with slow division.
     397:  * #define USABLE_FRACTION(n) (((n) >> 1) + ((n) >> 2) - ((n) >> 3))
     398:  */
     399: 
     400: /* GROWTH_RATE. Growth rate upon hitting maximum load.
     401:  * Currently set to used*2 + capacity/2.
     402:  * This means that dicts double in size when growing without deletions,
     403:  * but have more head room when the number of deletions is on a par with the
     404:  * number of insertions.
     405:  * Raising this to used*4 doubles memory consumption depending on the size of
     406:  * the dictionary, but results in half the number of resizes, less effort to
     407:  * resize.
     408:  * GROWTH_RATE was set to used*4 up to version 3.2.
     409:  * GROWTH_RATE was set to used*2 in version 3.3.0
     410:  */
     411: #define GROWTH_RATE(d) (((d)->ma_used*2)+((d)->ma_keys->dk_size>>1))
     412: 
     413: #define ENSURE_ALLOWS_DELETIONS(d) \
     414:     if ((d)->ma_keys->dk_lookup == lookdict_unicode_nodummy) { \
     415:         (d)->ma_keys->dk_lookup = lookdict_unicode; \
     416:     }
     417: 
     418: /* This immutable, empty PyDictKeysObject is used for PyDict_Clear()
     419:  * (which cannot fail and thus can do no allocation).
     420:  */
     421: static PyDictKeysObject empty_keys_struct = {
     422:         1, /* dk_refcnt */
     423:         1, /* dk_size */
     424:         lookdict_split, /* dk_lookup */
     425:         0, /* dk_usable (immutable) */
     426:         0, /* dk_nentries */
     427:         .dk_indices = { .as_1 = {DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY,
     428:                                  DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY}},
     429: };
     430: 
     431: static PyObject *empty_values[1] = { NULL };
     432: 
     433: #define Py_EMPTY_KEYS &empty_keys_struct
     434: 
     435: /* Uncomment to check the dict content in _PyDict_CheckConsistency() */
     436: /* #define DEBUG_PYDICT */
     437: 
     438: 
     439: #ifndef NDEBUG
     440: static int
     441: _PyDict_CheckConsistency(PyDictObject *mp)
     442: {
     443:     PyDictKeysObject *keys = mp->ma_keys;
     444:     int splitted = _PyDict_HasSplitTable(mp);
     445:     Py_ssize_t usable = USABLE_FRACTION(keys->dk_size);
     446: #ifdef DEBUG_PYDICT
     447:     PyDictKeyEntry *entries = DK_ENTRIES(keys);
     448:     Py_ssize_t i;
     449: #endif
     450: 
     451:     assert(0 <= mp->ma_used && mp->ma_used <= usable);
     452:     assert(IS_POWER_OF_2(keys->dk_size));
     453:     assert(0 <= keys->dk_usable
     454:            && keys->dk_usable <= usable);
     455:     assert(0 <= keys->dk_nentries
     456:            && keys->dk_nentries <= usable);
     457:     assert(keys->dk_usable + keys->dk_nentries <= usable);
     458: 
     459:     if (!splitted) {
     460:         /* combined table */
     461:         assert(keys->dk_refcnt == 1);
     462:     }
     463: 
     464: #ifdef DEBUG_PYDICT
     465:     for (i=0; i < keys->dk_size; i++) {
     466:         Py_ssize_t ix = dk_get_index(keys, i);
     467:         assert(DKIX_DUMMY <= ix && ix <= usable);
     468:     }
     469: 
     470:     for (i=0; i < usable; i++) {
     471:         PyDictKeyEntry *entry = &entries[i];
     472:         PyObject *key = entry->me_key;
     473: 
     474:         if (key != NULL) {
     475:             if (PyUnicode_CheckExact(key)) {
     476:                 Py_hash_t hash = ((PyASCIIObject *)key)->hash;
     477:                 assert(hash != -1);
     478:                 assert(entry->me_hash == hash);
     479:             }
     480:             else {
     481:                 /* test_dict fails if PyObject_Hash() is called again */
     482:                 assert(entry->me_hash != -1);
     483:             }
     484:             if (!splitted) {
     485:                 assert(entry->me_value != NULL);
     486:             }
     487:         }
     488: 
     489:         if (splitted) {
     490:             assert(entry->me_value == NULL);
     491:         }
     492:     }
     493: 
     494:     if (splitted) {
     495:         /* splitted table */
     496:         for (i=0; i < mp->ma_used; i++) {
     497:             assert(mp->ma_values[i] != NULL);
     498:         }
     499:     }
     500: #endif
     501: 
     502:     return 1;
     503: }
     504: #endif
     505: 
     506: 
     507: static PyDictKeysObject *new_keys_object(Py_ssize_t size)
     508: {
     509:     PyDictKeysObject *dk;
     510:     Py_ssize_t es, usable;
     511: 
     512:     assert(size >= PyDict_MINSIZE);
     513:     assert(IS_POWER_OF_2(size));
     514: 
     515:     usable = USABLE_FRACTION(size);
     516:     if (size <= 0xff) {
     517:         es = 1;
     518:     }
     519:     else if (size <= 0xffff) {
     520:         es = 2;
     521:     }
     522: #if SIZEOF_VOID_P > 4
     523:     else if (size <= 0xffffffff) {
     524:         es = 4;
     525:     }
     526: #endif
     527:     else {
     528:         es = sizeof(Py_ssize_t);
     529:     }
     530: 
     531:     if (size == PyDict_MINSIZE && numfreekeys > 0) {
     532:         dk = keys_free_list[--numfreekeys];
     533:     }
     534:     else {
     535:         dk = PyObject_MALLOC(sizeof(PyDictKeysObject)
     536:                              - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
     537:                              + es * size
     538:                              + sizeof(PyDictKeyEntry) * usable);
     539:         if (dk == NULL) {
     540:             PyErr_NoMemory();
     541:             return NULL;
     542:         }
     543:     }
     544:     DK_DEBUG_INCREF dk->dk_refcnt = 1;
     545:     dk->dk_size = size;
     546:     dk->dk_usable = usable;
     547:     dk->dk_lookup = lookdict_unicode_nodummy;
     548:     dk->dk_nentries = 0;
     549:     memset(&dk->dk_indices.as_1[0], 0xff, es * size);
     550:     memset(DK_ENTRIES(dk), 0, sizeof(PyDictKeyEntry) * usable);
     551:     return dk;
     552: }
     553: 
     554: static void
     555: free_keys_object(PyDictKeysObject *keys)
     556: {
     557:     PyDictKeyEntry *entries = DK_ENTRIES(keys);
     558:     Py_ssize_t i, n;
     559:     for (i = 0, n = keys->dk_nentries; i < n; i++) {
     560:         Py_XDECREF(entries[i].me_key);
     561:         Py_XDECREF(entries[i].me_value);
     562:     }
     563:     if (keys->dk_size == PyDict_MINSIZE && numfreekeys < PyDict_MAXFREELIST) {
     564:         keys_free_list[numfreekeys++] = keys;
     565:         return;
     566:     }
     567:     PyObject_FREE(keys);
     568: }
     569: 
     570: #define new_values(size) PyMem_NEW(PyObject *, size)
     571: #define free_values(values) PyMem_FREE(values)
     572: 
     573: /* Consumes a reference to the keys object */
     574: static PyObject *
     575: new_dict(PyDictKeysObject *keys, PyObject **values)
     576: {
     577:     PyDictObject *mp;
     578:     assert(keys != NULL);
     579:     if (numfree) {
     580:         mp = free_list[--numfree];
     581:         assert (mp != NULL);
     582:         assert (Py_TYPE(mp) == &PyDict_Type);
     583:         _Py_NewReference((PyObject *)mp);
     584:     }
     585:     else {
     586:         mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
     587:         if (mp == NULL) {
     588:             DK_DECREF(keys);
     589:             free_values(values);
     590:             return NULL;
     591:         }
     592:     }
     593:     mp->ma_keys = keys;
     594:     mp->ma_values = values;
     595:     mp->ma_used = 0;
     596:     mp->ma_version_tag = DICT_NEXT_VERSION();
     597:     assert(_PyDict_CheckConsistency(mp));
     598:     return (PyObject *)mp;
     599: }
     600: 
     601: /* Consumes a reference to the keys object */
     602: static PyObject *
     603: new_dict_with_shared_keys(PyDictKeysObject *keys)
     604: {
     605:     PyObject **values;
     606:     Py_ssize_t i, size;
     607: 
     608:     size = USABLE_FRACTION(DK_SIZE(keys));
     609:     values = new_values(size);
     610:     if (values == NULL) {
     611:         DK_DECREF(keys);
     612:         return PyErr_NoMemory();
     613:     }
     614:     for (i = 0; i < size; i++) {
     615:         values[i] = NULL;
     616:     }
     617:     return new_dict(keys, values);
     618: }
     619: 
     620: PyObject *
     621: PyDict_New(void)
     622: {
     623:     PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
     624:     if (keys == NULL)
     625:         return NULL;
     626:     return new_dict(keys, NULL);
     627: }
     628: 
     629: /* Search index of hash table from offset of entry table */
     630: static Py_ssize_t
     631: lookdict_index(PyDictKeysObject *k, Py_hash_t hash, Py_ssize_t index)
     632: {
     633:     size_t i;
     634:     size_t mask = DK_MASK(k);
     635:     Py_ssize_t ix;
     636: 
     637:     i = (size_t)hash & mask;
     638:     ix = dk_get_index(k, i);
     639:     if (ix == index) {
     640:         return i;
     641:     }
     642:     if (ix == DKIX_EMPTY) {
     643:         return DKIX_EMPTY;
     644:     }
     645: 
     646:     for (size_t perturb = hash;;) {
     647:         perturb >>= PERTURB_SHIFT;
     648:         i = mask & ((i << 2) + i + perturb + 1);
     649:         ix = dk_get_index(k, i);
     650:         if (ix == index) {
     651:             return i;
     652:         }
     653:         if (ix == DKIX_EMPTY) {
     654:             return DKIX_EMPTY;
     655:         }
     656:     }
     657:     assert(0);          /* NOT REACHED */
     658:     return DKIX_ERROR;
     659: }
     660: 
     661: /*
     662: The basic lookup function used by all operations.
     663: This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
     664: Open addressing is preferred over chaining since the link overhead for
     665: chaining would be substantial (100% with typical malloc overhead).
     666: 
     667: The initial probe index is computed as hash mod the table size. Subsequent
     668: probe indices are computed as explained earlier.
     669: 
     670: All arithmetic on hash should ignore overflow.
     671: 
     672: The details in this version are due to Tim Peters, building on many past
     673: contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
     674: Christian Tismer.
     675: 
     676: lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a
     677: comparison raises an exception.
     678: lookdict_unicode() below is specialized to string keys, comparison of which can
     679: never raise an exception; that function can never return DKIX_ERROR when key
     680: is string.  Otherwise, it falls back to lookdict().
     681: lookdict_unicode_nodummy is further specialized for string keys that cannot be
     682: the <dummy> value.
     683: For both, when the key isn't found a DKIX_EMPTY is returned. hashpos returns
     684: where the key index should be inserted.
     685: */
     686: static Py_ssize_t
     687: lookdict(PyDictObject *mp, PyObject *key,
     688:          Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
     689: {
     690:     size_t i, mask;
     691:     Py_ssize_t ix, freeslot;
     692:     int cmp;
     693:     PyDictKeysObject *dk;
     694:     PyDictKeyEntry *ep0, *ep;
     695:     PyObject *startkey;
     696: 
     697: top:
     698:     dk = mp->ma_keys;
     699:     mask = DK_MASK(dk);
     700:     ep0 = DK_ENTRIES(dk);
     701:     i = (size_t)hash & mask;
     702: 
     703:     ix = dk_get_index(dk, i);
     704:     if (ix == DKIX_EMPTY) {
     705:         if (hashpos != NULL)
     706:             *hashpos = i;
     707:         *value_addr = NULL;
     708:         return DKIX_EMPTY;
     709:     }
     710:     if (ix == DKIX_DUMMY) {
     711:         freeslot = i;
     712:     }
     713:     else {
     714:         ep = &ep0[ix];
     715:         assert(ep->me_key != NULL);
     716:         if (ep->me_key == key) {
     717:             *value_addr = &ep->me_value;
     718:             if (hashpos != NULL)
     719:                 *hashpos = i;
     720:             return ix;
     721:         }
     722:         if (ep->me_hash == hash) {
     723:             startkey = ep->me_key;
     724:             Py_INCREF(startkey);
     725:             cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
     726:             Py_DECREF(startkey);
     727:             if (cmp < 0) {
     728:                 *value_addr = NULL;
     729:                 return DKIX_ERROR;
     730:             }
     731:             if (dk == mp->ma_keys && ep->me_key == startkey) {
     732:                 if (cmp > 0) {
     733:                     *value_addr = &ep->me_value;
     734:                     if (hashpos != NULL)
     735:                         *hashpos = i;
     736:                     return ix;
     737:                 }
     738:             }
     739:             else {
     740:                 /* The dict was mutated, restart */
     741:                 goto top;
     742:             }
     743:         }
     744:         freeslot = -1;
     745:     }
     746: 
     747:     for (size_t perturb = hash;;) {
     748:         perturb >>= PERTURB_SHIFT;
     749:         i = ((i << 2) + i + perturb + 1) & mask;
     750:         ix = dk_get_index(dk, i);
     751:         if (ix == DKIX_EMPTY) {
     752:             if (hashpos != NULL) {
     753:                 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
     754:             }
     755:             *value_addr = NULL;
     756:             return ix;
     757:         }
     758:         if (ix == DKIX_DUMMY) {
     759:             if (freeslot == -1)
     760:                 freeslot = i;
     761:             continue;
     762:         }
     763:         ep = &ep0[ix];
     764:         assert(ep->me_key != NULL);
     765:         if (ep->me_key == key) {
     766:             if (hashpos != NULL) {
     767:                 *hashpos = i;
     768:             }
     769:             *value_addr = &ep->me_value;
     770:             return ix;
     771:         }
     772:         if (ep->me_hash == hash) {
     773:             startkey = ep->me_key;
     774:             Py_INCREF(startkey);
     775:             cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
     776:             Py_DECREF(startkey);
     777:             if (cmp < 0) {
     778:                 *value_addr = NULL;
     779:                 return DKIX_ERROR;
     780:             }
     781:             if (dk == mp->ma_keys && ep->me_key == startkey) {
     782:                 if (cmp > 0) {
     783:                     if (hashpos != NULL) {
     784:                         *hashpos = i;
     785:                     }
     786:                     *value_addr = &ep->me_value;
     787:                     return ix;
     788:                 }
     789:             }
     790:             else {
     791:                 /* The dict was mutated, restart */
     792:                 goto top;
     793:             }
     794:         }
     795:     }
     796:     assert(0);          /* NOT REACHED */
     797:     return 0;
     798: }
     799: 
     800: /* Specialized version for string-only keys */
     801: static Py_ssize_t
     802: lookdict_unicode(PyDictObject *mp, PyObject *key,
     803:                  Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
     804: {
     805:     size_t i;
     806:     size_t mask = DK_MASK(mp->ma_keys);
     807:     Py_ssize_t ix, freeslot;
     808:     PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
     809: 
     810:     assert(mp->ma_values == NULL);
     811:     /* Make sure this function doesn't have to handle non-unicode keys,
     812:        including subclasses of str; e.g., one reason to subclass
     813:        unicodes is to override __eq__, and for speed we don't cater to
     814:        that here. */
     815:     if (!PyUnicode_CheckExact(key)) {
     816:         mp->ma_keys->dk_lookup = lookdict;
     817:         return lookdict(mp, key, hash, value_addr, hashpos);
     818:     }
     819:     i = (size_t)hash & mask;
     820:     ix = dk_get_index(mp->ma_keys, i);
     821:     if (ix == DKIX_EMPTY) {
     822:         if (hashpos != NULL)
     823:             *hashpos = i;
     824:         *value_addr = NULL;
     825:         return DKIX_EMPTY;
     826:     }
     827:     if (ix == DKIX_DUMMY) {
     828:         freeslot = i;
     829:     }
     830:     else {
     831:         ep = &ep0[ix];
     832:         assert(ep->me_key != NULL);
     833:         if (ep->me_key == key
     834:             || (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
     835:             if (hashpos != NULL)
     836:                 *hashpos = i;
     837:             *value_addr = &ep->me_value;
     838:             return ix;
     839:         }
     840:         freeslot = -1;
     841:     }
     842: 
     843:     for (size_t perturb = hash;;) {
     844:         perturb >>= PERTURB_SHIFT;
     845:         i = mask & ((i << 2) + i + perturb + 1);
     846:         ix = dk_get_index(mp->ma_keys, i);
     847:         if (ix == DKIX_EMPTY) {
     848:             if (hashpos != NULL) {
     849:                 *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot;
     850:             }
     851:             *value_addr = NULL;
     852:             return DKIX_EMPTY;
     853:         }
     854:         if (ix == DKIX_DUMMY) {
     855:             if (freeslot == -1)
     856:                 freeslot = i;
     857:             continue;
     858:         }
     859:         ep = &ep0[ix];
     860:         assert(ep->me_key != NULL);
     861:         if (ep->me_key == key
     862:             || (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
     863:             *value_addr = &ep->me_value;
     864:             if (hashpos != NULL) {
     865:                 *hashpos = i;
     866:             }
     867:             return ix;
     868:         }
     869:     }
     870:     assert(0);          /* NOT REACHED */
     871:     return 0;
     872: }
     873: 
     874: /* Faster version of lookdict_unicode when it is known that no <dummy> keys
     875:  * will be present. */
     876: static Py_ssize_t
     877: lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key,
     878:                          Py_hash_t hash, PyObject ***value_addr,
     879:                          Py_ssize_t *hashpos)
     880: {
     881:     size_t i;
     882:     size_t mask = DK_MASK(mp->ma_keys);
     883:     Py_ssize_t ix;
     884:     PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
     885: 
     886:     assert(mp->ma_values == NULL);
     887:     /* Make sure this function doesn't have to handle non-unicode keys,
     888:        including subclasses of str; e.g., one reason to subclass
     889:        unicodes is to override __eq__, and for speed we don't cater to
     890:        that here. */
     891:     if (!PyUnicode_CheckExact(key)) {
     892:         mp->ma_keys->dk_lookup = lookdict;
     893:         return lookdict(mp, key, hash, value_addr, hashpos);
     894:     }
     895:     i = (size_t)hash & mask;
     896:     ix = dk_get_index(mp->ma_keys, i);
     897:     assert (ix != DKIX_DUMMY);
     898:     if (ix == DKIX_EMPTY) {
     899:         if (hashpos != NULL)
     900:             *hashpos = i;
     901:         *value_addr = NULL;
     902:         return DKIX_EMPTY;
     903:     }
     904:     ep = &ep0[ix];
     905:     assert(ep->me_key != NULL);
     906:     assert(PyUnicode_CheckExact(ep->me_key));
     907:     if (ep->me_key == key ||
     908:         (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
     909:         if (hashpos != NULL)
     910:             *hashpos = i;
     911:         *value_addr = &ep->me_value;
     912:         return ix;
     913:     }
     914:     for (size_t perturb = hash;;) {
     915:         perturb >>= PERTURB_SHIFT;
     916:         i = mask & ((i << 2) + i + perturb + 1);
     917:         ix = dk_get_index(mp->ma_keys, i);
     918:         assert (ix != DKIX_DUMMY);
     919:         if (ix == DKIX_EMPTY) {
     920:             if (hashpos != NULL)
     921:                 *hashpos = i;
     922:             *value_addr = NULL;
     923:             return DKIX_EMPTY;
     924:         }
     925:         ep = &ep0[ix];
     926:         assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
     927:         if (ep->me_key == key ||
     928:             (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
     929:             if (hashpos != NULL)
     930:                 *hashpos = i;
     931:             *value_addr = &ep->me_value;
     932:             return ix;
     933:         }
     934:     }
     935:     assert(0);          /* NOT REACHED */
     936:     return 0;
     937: }
     938: 
     939: /* Version of lookdict for split tables.
     940:  * All split tables and only split tables use this lookup function.
     941:  * Split tables only contain unicode keys and no dummy keys,
     942:  * so algorithm is the same as lookdict_unicode_nodummy.
     943:  */
     944: static Py_ssize_t
     945: lookdict_split(PyDictObject *mp, PyObject *key,
     946:                Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos)
     947: {
     948:     size_t i;
     949:     size_t mask = DK_MASK(mp->ma_keys);
     950:     Py_ssize_t ix;
     951:     PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
     952: 
     953:     /* mp must split table */
     954:     assert(mp->ma_values != NULL);
     955:     if (!PyUnicode_CheckExact(key)) {
     956:         ix = lookdict(mp, key, hash, value_addr, hashpos);
     957:         if (ix >= 0) {
     958:             *value_addr = &mp->ma_values[ix];
     959:         }
     960:         return ix;
     961:     }
     962: 
     963:     i = (size_t)hash & mask;
     964:     ix = dk_get_index(mp->ma_keys, i);
     965:     if (ix == DKIX_EMPTY) {
     966:         if (hashpos != NULL)
     967:             *hashpos = i;
     968:         *value_addr = NULL;
     969:         return DKIX_EMPTY;
     970:     }
     971:     assert(ix >= 0);
     972:     ep = &ep0[ix];
     973:     assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
     974:     if (ep->me_key == key ||
     975:         (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
     976:         if (hashpos != NULL)
     977:             *hashpos = i;
     978:         *value_addr = &mp->ma_values[ix];
     979:         return ix;
     980:     }
     981:     for (size_t perturb = hash;;) {
     982:         perturb >>= PERTURB_SHIFT;
     983:         i = mask & ((i << 2) + i + perturb + 1);
     984:         ix = dk_get_index(mp->ma_keys, i);
     985:         if (ix == DKIX_EMPTY) {
     986:             if (hashpos != NULL)
     987:                 *hashpos = i;
     988:             *value_addr = NULL;
     989:             return DKIX_EMPTY;
     990:         }
     991:         assert(ix >= 0);
     992:         ep = &ep0[ix];
     993:         assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key));
     994:         if (ep->me_key == key ||
     995:             (ep->me_hash == hash && unicode_eq(ep->me_key, key))) {
     996:             if (hashpos != NULL)
     997:                 *hashpos = i;
     998:             *value_addr = &mp->ma_values[ix];
     999:             return ix;
    1000:         }
    1001:     }
    1002:     assert(0);          /* NOT REACHED */
    1003:     return 0;
    1004: }
    1005: 
    1006: int
    1007: _PyDict_HasOnlyStringKeys(PyObject *dict)
    1008: {
    1009:     Py_ssize_t pos = 0;
    1010:     PyObject *key, *value;
    1011:     assert(PyDict_Check(dict));
    1012:     /* Shortcut */
    1013:     if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict)
    1014:         return 1;
    1015:     while (PyDict_Next(dict, &pos, &key, &value))
    1016:         if (!PyUnicode_Check(key))
    1017:             return 0;
    1018:     return 1;
    1019: }
    1020: 
    1021: #define MAINTAIN_TRACKING(mp, key, value) \
    1022:     do { \
    1023:         if (!_PyObject_GC_IS_TRACKED(mp)) { \
    1024:             if (_PyObject_GC_MAY_BE_TRACKED(key) || \
    1025:                 _PyObject_GC_MAY_BE_TRACKED(value)) { \
    1026:                 _PyObject_GC_TRACK(mp); \
    1027:             } \
    1028:         } \
    1029:     } while(0)
    1030: 
    1031: void
    1032: _PyDict_MaybeUntrack(PyObject *op)
    1033: {
    1034:     PyDictObject *mp;
    1035:     PyObject *value;
    1036:     Py_ssize_t i, numentries;
    1037:     PyDictKeyEntry *ep0;
    1038: 
    1039:     if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
    1040:         return;
    1041: 
    1042:     mp = (PyDictObject *) op;
    1043:     ep0 = DK_ENTRIES(mp->ma_keys);
    1044:     numentries = mp->ma_keys->dk_nentries;
    1045:     if (_PyDict_HasSplitTable(mp)) {
    1046:         for (i = 0; i < numentries; i++) {
    1047:             if ((value = mp->ma_values[i]) == NULL)
    1048:                 continue;
    1049:             if (_PyObject_GC_MAY_BE_TRACKED(value)) {
    1050:                 assert(!_PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key));
    1051:                 return;
    1052:             }
    1053:         }
    1054:     }
    1055:     else {
    1056:         for (i = 0; i < numentries; i++) {
    1057:             if ((value = ep0[i].me_value) == NULL)
    1058:                 continue;
    1059:             if (_PyObject_GC_MAY_BE_TRACKED(value) ||
    1060:                 _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
    1061:                 return;
    1062:         }
    1063:     }
    1064:     _PyObject_GC_UNTRACK(op);
    1065: }
    1066: 
    1067: /* Internal function to find slot for an item from its hash
    1068:    when it is known that the key is not present in the dict.
    1069: 
    1070:    The dict must be combined. */
    1071: static void
    1072: find_empty_slot(PyDictObject *mp, PyObject *key, Py_hash_t hash,
    1073:                 PyObject ***value_addr, Py_ssize_t *hashpos)
    1074: {
    1075:     size_t i;
    1076:     size_t mask = DK_MASK(mp->ma_keys);
    1077:     Py_ssize_t ix;
    1078:     PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys);
    1079: 
    1080:     assert(!_PyDict_HasSplitTable(mp));
    1081:     assert(hashpos != NULL);
    1082:     assert(key != NULL);
    1083: 
    1084:     if (!PyUnicode_CheckExact(key))
    1085:         mp->ma_keys->dk_lookup = lookdict;
    1086:     i = hash & mask;
    1087:     ix = dk_get_index(mp->ma_keys, i);
    1088:     for (size_t perturb = hash; ix != DKIX_EMPTY;) {
    1089:         perturb >>= PERTURB_SHIFT;
    1090:         i = (i << 2) + i + perturb + 1;
    1091:         ix = dk_get_index(mp->ma_keys, i & mask);
    1092:     }
    1093:     ep = &ep0[mp->ma_keys->dk_nentries];
    1094:     *hashpos = i & mask;
    1095:     assert(ep->me_value == NULL);
    1096:     *value_addr = &ep->me_value;
    1097: }
    1098: 
    1099: static int
    1100: insertion_resize(PyDictObject *mp)
    1101: {
    1102:     return dictresize(mp, GROWTH_RATE(mp));
    1103: }
    1104: 
    1105: /*
    1106: Internal routine to insert a new item into the table.
    1107: Used both by the internal resize routine and by the public insert routine.
    1108: Returns -1 if an error occurred, or 0 on success.
    1109: */
    1110: static int
    1111: insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
    1112: {
    1113:     PyObject *old_value;
    1114:     PyObject **value_addr;
    1115:     PyDictKeyEntry *ep, *ep0;
    1116:     Py_ssize_t hashpos, ix;
    1117: 
    1118:     Py_INCREF(key);
    1119:     Py_INCREF(value);
    1120:     if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
    1121:         if (insertion_resize(mp) < 0)
    1122:             goto Fail;
    1123:     }
    1124: 
    1125:     ix = mp->ma_keys->dk_lookup(mp, key, hash, &value_addr, &hashpos);
    1126:     if (ix == DKIX_ERROR)
    1127:         goto Fail;
    1128: 
    1129:     assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict);
    1130:     MAINTAIN_TRACKING(mp, key, value);
    1131: 
    1132:     /* When insertion order is different from shared key, we can't share
    1133:      * the key anymore.  Convert this instance to combine table.
    1134:      */
    1135:     if (_PyDict_HasSplitTable(mp) &&
    1136:         ((ix >= 0 && *value_addr == NULL && mp->ma_used != ix) ||
    1137:          (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
    1138:         if (insertion_resize(mp) < 0)
    1139:             goto Fail;
    1140:         find_empty_slot(mp, key, hash, &value_addr, &hashpos);
    1141:         ix = DKIX_EMPTY;
    1142:     }
    1143: 
    1144:     if (ix == DKIX_EMPTY) {
    1145:         /* Insert into new slot. */
    1146:         if (mp->ma_keys->dk_usable <= 0) {
    1147:             /* Need to resize. */
    1148:             if (insertion_resize(mp) < 0)
    1149:                 goto Fail;
    1150:             find_empty_slot(mp, key, hash, &value_addr, &hashpos);
    1151:         }
    1152:         ep0 = DK_ENTRIES(mp->ma_keys);
    1153:         ep = &ep0[mp->ma_keys->dk_nentries];
    1154:         dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
    1155:         ep->me_key = key;
    1156:         ep->me_hash = hash;
    1157:         if (mp->ma_values) {
    1158:             assert (mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
    1159:             mp->ma_values[mp->ma_keys->dk_nentries] = value;
    1160:         }
    1161:         else {
    1162:             ep->me_value = value;
    1163:         }
    1164:         mp->ma_used++;
    1165:         mp->ma_version_tag = DICT_NEXT_VERSION();
    1166:         mp->ma_keys->dk_usable--;
    1167:         mp->ma_keys->dk_nentries++;
    1168:         assert(mp->ma_keys->dk_usable >= 0);
    1169:         assert(_PyDict_CheckConsistency(mp));
    1170:         return 0;
    1171:     }
    1172: 
    1173:     assert(value_addr != NULL);
    1174: 
    1175:     old_value = *value_addr;
    1176:     if (old_value != NULL) {
    1177:         *value_addr = value;
    1178:         mp->ma_version_tag = DICT_NEXT_VERSION();
    1179:         assert(_PyDict_CheckConsistency(mp));
    1180: 
    1181:         Py_DECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
    1182:         Py_DECREF(key);
    1183:         return 0;
    1184:     }
    1185: 
    1186:     /* pending state */
    1187:     assert(_PyDict_HasSplitTable(mp));
    1188:     assert(ix == mp->ma_used);
    1189:     *value_addr = value;
    1190:     mp->ma_used++;
    1191:     mp->ma_version_tag = DICT_NEXT_VERSION();
    1192:     assert(_PyDict_CheckConsistency(mp));
    1193:     Py_DECREF(key);
    1194:     return 0;
    1195: 
    1196: Fail:
    1197:     Py_DECREF(value);
    1198:     Py_DECREF(key);
    1199:     return -1;
    1200: }
    1201: 
    1202: /*
    1203: Internal routine used by dictresize() to insert an item which is
    1204: known to be absent from the dict.  This routine also assumes that
    1205: the dict contains no deleted entries.  Besides the performance benefit,
    1206: using insertdict() in dictresize() is dangerous (SF bug #1456209).
    1207: Note that no refcounts are changed by this routine; if needed, the caller
    1208: is responsible for incref'ing `key` and `value`.
    1209: Neither mp->ma_used nor k->dk_usable are modified by this routine; the caller
    1210: must set them correctly
    1211: */
    1212: static void
    1213: insertdict_clean(PyDictObject *mp, PyObject *key, Py_hash_t hash,
    1214:                  PyObject *value)
    1215: {
    1216:     size_t i;
    1217:     PyDictKeysObject *k = mp->ma_keys;
    1218:     size_t mask = (size_t)DK_SIZE(k)-1;
    1219:     PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
    1220:     PyDictKeyEntry *ep;
    1221: 
    1222:     assert(k->dk_lookup != NULL);
    1223:     assert(value != NULL);
    1224:     assert(key != NULL);
    1225:     assert(PyUnicode_CheckExact(key) || k->dk_lookup == lookdict);
    1226:     i = hash & mask;
    1227:     for (size_t perturb = hash; dk_get_index(k, i) != DKIX_EMPTY;) {
    1228:         perturb >>= PERTURB_SHIFT;
    1229:         i = mask & ((i << 2) + i + perturb + 1);
    1230:     }
    1231:     ep = &ep0[k->dk_nentries];
    1232:     assert(ep->me_value == NULL);
    1233:     dk_set_index(k, i, k->dk_nentries);
    1234:     k->dk_nentries++;
    1235:     ep->me_key = key;
    1236:     ep->me_hash = hash;
    1237:     ep->me_value = value;
    1238: }
    1239: 
    1240: /*
    1241: Restructure the table by allocating a new table and reinserting all
    1242: items again.  When entries have been deleted, the new table may
    1243: actually be smaller than the old one.
    1244: If a table is split (its keys and hashes are shared, its values are not),
    1245: then the values are temporarily copied into the table, it is resized as
    1246: a combined table, then the me_value slots in the old table are NULLed out.
    1247: After resizing a table is always combined,
    1248: but can be resplit by make_keys_shared().
    1249: */
    1250: static int
    1251: dictresize(PyDictObject *mp, Py_ssize_t minsize)
    1252: {
    1253:     Py_ssize_t i, newsize;
    1254:     PyDictKeysObject *oldkeys;
    1255:     PyObject **oldvalues;
    1256:     PyDictKeyEntry *ep0;
    1257: 
    1258:     /* Find the smallest table size > minused. */
    1259:     for (newsize = PyDict_MINSIZE;
    1260:          newsize < minsize && newsize > 0;
    1261:          newsize <<= 1)
    1262:         ;
    1263:     if (newsize <= 0) {
    1264:         PyErr_NoMemory();
    1265:         return -1;
    1266:     }
    1267:     oldkeys = mp->ma_keys;
    1268:     oldvalues = mp->ma_values;
    1269:     /* Allocate a new table. */
    1270:     mp->ma_keys = new_keys_object(newsize);
    1271:     if (mp->ma_keys == NULL) {
    1272:         mp->ma_keys = oldkeys;
    1273:         return -1;
    1274:     }
    1275:     // New table must be large enough.
    1276:     assert(mp->ma_keys->dk_usable >= mp->ma_used);
    1277:     if (oldkeys->dk_lookup == lookdict)
    1278:         mp->ma_keys->dk_lookup = lookdict;
    1279:     mp->ma_values = NULL;
    1280:     ep0 = DK_ENTRIES(oldkeys);
    1281:     /* Main loop below assumes we can transfer refcount to new keys
    1282:      * and that value is stored in me_value.
    1283:      * Increment ref-counts and copy values here to compensate
    1284:      * This (resizing a split table) should be relatively rare */
    1285:     if (oldvalues != NULL) {
    1286:         for (i = 0; i < oldkeys->dk_nentries; i++) {
    1287:             if (oldvalues[i] != NULL) {
    1288:                 Py_INCREF(ep0[i].me_key);
    1289:                 ep0[i].me_value = oldvalues[i];
    1290:             }
    1291:         }
    1292:     }
    1293:     /* Main loop */
    1294:     for (i = 0; i < oldkeys->dk_nentries; i++) {
    1295:         PyDictKeyEntry *ep = &ep0[i];
    1296:         if (ep->me_value != NULL) {
    1297:             insertdict_clean(mp, ep->me_key, ep->me_hash, ep->me_value);
    1298:         }
    1299:     }
    1300:     mp->ma_keys->dk_usable -= mp->ma_used;
    1301:     if (oldvalues != NULL) {
    1302:         /* NULL out me_value slot in oldkeys, in case it was shared */
    1303:         for (i = 0; i < oldkeys->dk_nentries; i++)
    1304:             ep0[i].me_value = NULL;
    1305:         DK_DECREF(oldkeys);
    1306:         if (oldvalues != empty_values) {
    1307:             free_values(oldvalues);
    1308:         }
    1309:     }
    1310:     else {
    1311:         assert(oldkeys->dk_lookup != lookdict_split);
    1312:         assert(oldkeys->dk_refcnt == 1);
    1313:         DK_DEBUG_DECREF PyObject_FREE(oldkeys);
    1314:     }
    1315:     return 0;
    1316: }
    1317: 
    1318: /* Returns NULL if unable to split table.
    1319:  * A NULL return does not necessarily indicate an error */
    1320: static PyDictKeysObject *
    1321: make_keys_shared(PyObject *op)
    1322: {
    1323:     Py_ssize_t i;
    1324:     Py_ssize_t size;
    1325:     PyDictObject *mp = (PyDictObject *)op;
    1326: 
    1327:     if (!PyDict_CheckExact(op))
    1328:         return NULL;
    1329:     if (!_PyDict_HasSplitTable(mp)) {
    1330:         PyDictKeyEntry *ep0;
    1331:         PyObject **values;
    1332:         assert(mp->ma_keys->dk_refcnt == 1);
    1333:         if (mp->ma_keys->dk_lookup == lookdict) {
    1334:             return NULL;
    1335:         }
    1336:         else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
    1337:             /* Remove dummy keys */
    1338:             if (dictresize(mp, DK_SIZE(mp->ma_keys)))
    1339:                 return NULL;
    1340:         }
    1341:         assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
    1342:         /* Copy values into a new array */
    1343:         ep0 = DK_ENTRIES(mp->ma_keys);
    1344:         size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
    1345:         values = new_values(size);
    1346:         if (values == NULL) {
    1347:             PyErr_SetString(PyExc_MemoryError,
    1348:                 "Not enough memory to allocate new values array");
    1349:             return NULL;
    1350:         }
    1351:         for (i = 0; i < size; i++) {
    1352:             values[i] = ep0[i].me_value;
    1353:             ep0[i].me_value = NULL;
    1354:         }
    1355:         mp->ma_keys->dk_lookup = lookdict_split;
    1356:         mp->ma_values = values;
    1357:     }
    1358:     DK_INCREF(mp->ma_keys);
    1359:     return mp->ma_keys;
    1360: }
    1361: 
    1362: PyObject *
    1363: _PyDict_NewPresized(Py_ssize_t minused)
    1364: {
    1365:     const Py_ssize_t max_presize = 128 * 1024;
    1366:     Py_ssize_t newsize;
    1367:     PyDictKeysObject *new_keys;
    1368: 
    1369:     /* There are no strict guarantee that returned dict can contain minused
    1370:      * items without resize.  So we create medium size dict instead of very
    1371:      * large dict or MemoryError.
    1372:      */
    1373:     if (minused > USABLE_FRACTION(max_presize)) {
    1374:         newsize = max_presize;
    1375:     }
    1376:     else {
    1377:         Py_ssize_t minsize = ESTIMATE_SIZE(minused);
    1378:         newsize = PyDict_MINSIZE;
    1379:         while (newsize < minsize) {
    1380:             newsize <<= 1;
    1381:         }
    1382:     }
    1383:     assert(IS_POWER_OF_2(newsize));
    1384: 
    1385:     new_keys = new_keys_object(newsize);
    1386:     if (new_keys == NULL)
    1387:         return NULL;
    1388:     return new_dict(new_keys, NULL);
    1389: }
    1390: 
    1391: /* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
    1392:  * that may occur (originally dicts supported only string keys, and exceptions
    1393:  * weren't possible).  So, while the original intent was that a NULL return
    1394:  * meant the key wasn't present, in reality it can mean that, or that an error
    1395:  * (suppressed) occurred while computing the key's hash, or that some error
    1396:  * (suppressed) occurred when comparing keys in the dict's internal probe
    1397:  * sequence.  A nasty example of the latter is when a Python-coded comparison
    1398:  * function hits a stack-depth error, which can cause this to return NULL
    1399:  * even if the key is present.
    1400:  */
    1401: PyObject *
    1402: PyDict_GetItem(PyObject *op, PyObject *key)
    1403: {
    1404:     Py_hash_t hash;
    1405:     Py_ssize_t ix;
    1406:     PyDictObject *mp = (PyDictObject *)op;
    1407:     PyThreadState *tstate;
    1408:     PyObject **value_addr;
    1409: 
    1410:     if (!PyDict_Check(op))
    1411:         return NULL;
    1412:     if (!PyUnicode_CheckExact(key) ||
    1413:         (hash = ((PyASCIIObject *) key)->hash) == -1)
    1414:     {
    1415:         hash = PyObject_Hash(key);
    1416:         if (hash == -1) {
    1417:             PyErr_Clear();
    1418:             return NULL;
    1419:         }
    1420:     }
    1421: 
    1422:     /* We can arrive here with a NULL tstate during initialization: try
    1423:        running "python -Wi" for an example related to string interning.
    1424:        Let's just hope that no exception occurs then...  This must be
    1425:        _PyThreadState_Current and not PyThreadState_GET() because in debug
    1426:        mode, the latter complains if tstate is NULL. */
    1427:     tstate = _PyThreadState_UncheckedGet();
    1428:     if (tstate != NULL && tstate->curexc_type != NULL) {
    1429:         /* preserve the existing exception */
    1430:         PyObject *err_type, *err_value, *err_tb;
    1431:         PyErr_Fetch(&err_type, &err_value, &err_tb);
    1432:         ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
    1433:         /* ignore errors */
    1434:         PyErr_Restore(err_type, err_value, err_tb);
    1435:         if (ix < 0)
    1436:             return NULL;
    1437:     }
    1438:     else {
    1439:         ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
    1440:         if (ix < 0) {
    1441:             PyErr_Clear();
    1442:             return NULL;
    1443:         }
    1444:     }
    1445:     return *value_addr;
    1446: }
    1447: 
    1448: /* Same as PyDict_GetItemWithError() but with hash supplied by caller.
    1449:    This returns NULL *with* an exception set if an exception occurred.
    1450:    It returns NULL *without* an exception set if the key wasn't present.
    1451: */
    1452: PyObject *
    1453: _PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
    1454: {
    1455:     Py_ssize_t ix;
    1456:     PyDictObject *mp = (PyDictObject *)op;
    1457:     PyObject **value_addr;
    1458: 
    1459:     if (!PyDict_Check(op)) {
    1460:         PyErr_BadInternalCall();
    1461:         return NULL;
    1462:     }
    1463: 
    1464:     ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
    1465:     if (ix < 0) {
    1466:         return NULL;
    1467:     }
    1468:     return *value_addr;
    1469: }
    1470: 
    1471: /* Variant of PyDict_GetItem() that doesn't suppress exceptions.
    1472:    This returns NULL *with* an exception set if an exception occurred.
    1473:    It returns NULL *without* an exception set if the key wasn't present.
    1474: */
    1475: PyObject *
    1476: PyDict_GetItemWithError(PyObject *op, PyObject *key)
    1477: {
    1478:     Py_ssize_t ix;
    1479:     Py_hash_t hash;
    1480:     PyDictObject*mp = (PyDictObject *)op;
    1481:     PyObject **value_addr;
    1482: 
    1483:     if (!PyDict_Check(op)) {
    1484:         PyErr_BadInternalCall();
    1485:         return NULL;
    1486:     }
    1487:     if (!PyUnicode_CheckExact(key) ||
    1488:         (hash = ((PyASCIIObject *) key)->hash) == -1)
    1489:     {
    1490:         hash = PyObject_Hash(key);
    1491:         if (hash == -1) {
    1492:             return NULL;
    1493:         }
    1494:     }
    1495: 
    1496:     ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
    1497:     if (ix < 0)
    1498:         return NULL;
    1499:     return *value_addr;
    1500: }
    1501: 
    1502: PyObject *
    1503: _PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key)
    1504: {
    1505:     PyObject *kv;
    1506:     kv = _PyUnicode_FromId(key); /* borrowed */
    1507:     if (kv == NULL)
    1508:         return NULL;
    1509:     return PyDict_GetItemWithError(dp, kv);
    1510: }
    1511: 
    1512: /* Fast version of global value lookup (LOAD_GLOBAL).
    1513:  * Lookup in globals, then builtins.
    1514:  *
    1515:  * Raise an exception and return NULL if an error occurred (ex: computing the
    1516:  * key hash failed, key comparison failed, ...). Return NULL if the key doesn't
    1517:  * exist. Return the value if the key exists.
    1518:  */
    1519: PyObject *
    1520: _PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
    1521: {
    1522:     Py_ssize_t ix;
    1523:     Py_hash_t hash;
    1524:     PyObject **value_addr;
    1525: 
    1526:     if (!PyUnicode_CheckExact(key) ||
    1527:         (hash = ((PyASCIIObject *) key)->hash) == -1)
    1528:     {
    1529:         hash = PyObject_Hash(key);
    1530:         if (hash == -1)
    1531:             return NULL;
    1532:     }
    1533: 
    1534:     /* namespace 1: globals */
    1535:     ix = globals->ma_keys->dk_lookup(globals, key, hash, &value_addr, NULL);
    1536:     if (ix == DKIX_ERROR)
    1537:         return NULL;
    1538:     if (ix != DKIX_EMPTY && *value_addr != NULL)
    1539:         return *value_addr;
    1540: 
    1541:     /* namespace 2: builtins */
    1542:     ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value_addr, NULL);
    1543:     if (ix < 0)
    1544:         return NULL;
    1545:     return *value_addr;
    1546: }
    1547: 
    1548: /* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
    1549:  * dictionary if it's merely replacing the value for an existing key.
    1550:  * This means that it's safe to loop over a dictionary with PyDict_Next()
    1551:  * and occasionally replace a value -- but you can't insert new keys or
    1552:  * remove them.
    1553:  */
    1554: int
    1555: PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
    1556: {
    1557:     PyDictObject *mp;
    1558:     Py_hash_t hash;
    1559:     if (!PyDict_Check(op)) {
    1560:         PyErr_BadInternalCall();
    1561:         return -1;
    1562:     }
    1563:     assert(key);
    1564:     assert(value);
    1565:     mp = (PyDictObject *)op;
    1566:     if (!PyUnicode_CheckExact(key) ||
    1567:         (hash = ((PyASCIIObject *) key)->hash) == -1)
    1568:     {
    1569:         hash = PyObject_Hash(key);
    1570:         if (hash == -1)
    1571:             return -1;
    1572:     }
    1573: 
    1574:     /* insertdict() handles any resizing that might be necessary */
    1575:     return insertdict(mp, key, hash, value);
    1576: }
    1577: 
    1578: int
    1579: _PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
    1580:                          Py_hash_t hash)
    1581: {
    1582:     PyDictObject *mp;
    1583: 
    1584:     if (!PyDict_Check(op)) {
    1585:         PyErr_BadInternalCall();
    1586:         return -1;
    1587:     }
    1588:     assert(key);
    1589:     assert(value);
    1590:     assert(hash != -1);
    1591:     mp = (PyDictObject *)op;
    1592: 
    1593:     /* insertdict() handles any resizing that might be necessary */
    1594:     return insertdict(mp, key, hash, value);
    1595: }
    1596: 
    1597: static int
    1598: delitem_common(PyDictObject *mp, Py_ssize_t hashpos, Py_ssize_t ix,
    1599:                PyObject **value_addr)
    1600: {
    1601:     PyObject *old_key, *old_value;
    1602:     PyDictKeyEntry *ep;
    1603: 
    1604:     old_value = *value_addr;
    1605:     assert(old_value != NULL);
    1606:     *value_addr = NULL;
    1607:     mp->ma_used--;
    1608:     mp->ma_version_tag = DICT_NEXT_VERSION();
    1609:     ep = &DK_ENTRIES(mp->ma_keys)[ix];
    1610:     dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
    1611:     ENSURE_ALLOWS_DELETIONS(mp);
    1612:     old_key = ep->me_key;
    1613:     ep->me_key = NULL;
    1614:     Py_DECREF(old_key);
    1615:     Py_DECREF(old_value);
    1616: 
    1617:     assert(_PyDict_CheckConsistency(mp));
    1618:     return 0;
    1619: }
    1620: 
    1621: int
    1622: PyDict_DelItem(PyObject *op, PyObject *key)
    1623: {
    1624:     Py_hash_t hash;
    1625:     assert(key);
    1626:     if (!PyUnicode_CheckExact(key) ||
    1627:         (hash = ((PyASCIIObject *) key)->hash) == -1) {
    1628:         hash = PyObject_Hash(key);
    1629:         if (hash == -1)
    1630:             return -1;
    1631:     }
    1632: 
    1633:     return _PyDict_DelItem_KnownHash(op, key, hash);
    1634: }
    1635: 
    1636: int
    1637: _PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
    1638: {
    1639:     Py_ssize_t hashpos, ix;
    1640:     PyDictObject *mp;
    1641:     PyObject **value_addr;
    1642: 
    1643:     if (!PyDict_Check(op)) {
    1644:         PyErr_BadInternalCall();
    1645:         return -1;
    1646:     }
    1647:     assert(key);
    1648:     assert(hash != -1);
    1649:     mp = (PyDictObject *)op;
    1650:     ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
    1651:     if (ix == DKIX_ERROR)
    1652:         return -1;
    1653:     if (ix == DKIX_EMPTY || *value_addr == NULL) {
    1654:         _PyErr_SetKeyError(key);
    1655:         return -1;
    1656:     }
    1657:     assert(dk_get_index(mp->ma_keys, hashpos) == ix);
    1658: 
    1659:     // Split table doesn't allow deletion.  Combine it.
    1660:     if (_PyDict_HasSplitTable(mp)) {
    1661:         if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
    1662:             return -1;
    1663:         }
    1664:         ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
    1665:         assert(ix >= 0);
    1666:     }
    1667:     return delitem_common(mp, hashpos, ix, value_addr);
    1668: }
    1669: 
    1670: /* This function promises that the predicate -> deletion sequence is atomic
    1671:  * (i.e. protected by the GIL), assuming the predicate itself doesn't
    1672:  * release the GIL.
    1673:  */
    1674: int
    1675: _PyDict_DelItemIf(PyObject *op, PyObject *key,
    1676:                   int (*predicate)(PyObject *value))
    1677: {
    1678:     Py_ssize_t hashpos, ix;
    1679:     PyDictObject *mp;
    1680:     Py_hash_t hash;
    1681:     PyObject **value_addr;
    1682:     int res;
    1683: 
    1684:     if (!PyDict_Check(op)) {
    1685:         PyErr_BadInternalCall();
    1686:         return -1;
    1687:     }
    1688:     assert(key);
    1689:     hash = PyObject_Hash(key);
    1690:     if (hash == -1)
    1691:         return -1;
    1692:     mp = (PyDictObject *)op;
    1693:     ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
    1694:     if (ix == DKIX_ERROR)
    1695:         return -1;
    1696:     if (ix == DKIX_EMPTY || *value_addr == NULL) {
    1697:         _PyErr_SetKeyError(key);
    1698:         return -1;
    1699:     }
    1700:     assert(dk_get_index(mp->ma_keys, hashpos) == ix);
    1701: 
    1702:     // Split table doesn't allow deletion.  Combine it.
    1703:     if (_PyDict_HasSplitTable(mp)) {
    1704:         if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
    1705:             return -1;
    1706:         }
    1707:         ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
    1708:         assert(ix >= 0);
    1709:     }
    1710: 
    1711:     res = predicate(*value_addr);
    1712:     if (res == -1)
    1713:         return -1;
    1714:     if (res > 0)
    1715:         return delitem_common(mp, hashpos, ix, value_addr);
    1716:     else
    1717:         return 0;
    1718: }
    1719: 
    1720: 
    1721: void
    1722: PyDict_Clear(PyObject *op)
    1723: {
    1724:     PyDictObject *mp;
    1725:     PyDictKeysObject *oldkeys;
    1726:     PyObject **oldvalues;
    1727:     Py_ssize_t i, n;
    1728: 
    1729:     if (!PyDict_Check(op))
    1730:         return;
    1731:     mp = ((PyDictObject *)op);
    1732:     oldkeys = mp->ma_keys;
    1733:     oldvalues = mp->ma_values;
    1734:     if (oldvalues == empty_values)
    1735:         return;
    1736:     /* Empty the dict... */
    1737:     DK_INCREF(Py_EMPTY_KEYS);
    1738:     mp->ma_keys = Py_EMPTY_KEYS;
    1739:     mp->ma_values = empty_values;
    1740:     mp->ma_used = 0;
    1741:     mp->ma_version_tag = DICT_NEXT_VERSION();
    1742:     /* ...then clear the keys and values */
    1743:     if (oldvalues != NULL) {
    1744:         n = oldkeys->dk_nentries;
    1745:         for (i = 0; i < n; i++)
    1746:             Py_CLEAR(oldvalues[i]);
    1747:         free_values(oldvalues);
    1748:         DK_DECREF(oldkeys);
    1749:     }
    1750:     else {
    1751:        assert(oldkeys->dk_refcnt == 1);
    1752:        DK_DECREF(oldkeys);
    1753:     }
    1754:     assert(_PyDict_CheckConsistency(mp));
    1755: }
    1756: 
    1757: /* Internal version of PyDict_Next that returns a hash value in addition
    1758:  * to the key and value.
    1759:  * Return 1 on success, return 0 when the reached the end of the dictionary
    1760:  * (or if op is not a dictionary)
    1761:  */
    1762: int
    1763: _PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
    1764:              PyObject **pvalue, Py_hash_t *phash)
    1765: {
    1766:     Py_ssize_t i, n;
    1767:     PyDictObject *mp;
    1768:     PyDictKeyEntry *entry_ptr;
    1769:     PyObject *value;
    1770: 
    1771:     if (!PyDict_Check(op))
    1772:         return 0;
    1773:     mp = (PyDictObject *)op;
    1774:     i = *ppos;
    1775:     n = mp->ma_keys->dk_nentries;
    1776:     if ((size_t)i >= (size_t)n)
    1777:         return 0;
    1778:     if (mp->ma_values) {
    1779:         PyObject **value_ptr = &mp->ma_values[i];
    1780:         while (i < n && *value_ptr == NULL) {
    1781:             value_ptr++;
    1782:             i++;
    1783:         }
    1784:         if (i >= n)
    1785:             return 0;
    1786:         entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
    1787:         value = *value_ptr;
    1788:     }
    1789:     else {
    1790:         entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
    1791:         while (i < n && entry_ptr->me_value == NULL) {
    1792:             entry_ptr++;
    1793:             i++;
    1794:         }
    1795:         if (i >= n)
    1796:             return 0;
    1797:         value = entry_ptr->me_value;
    1798:     }
    1799:     *ppos = i+1;
    1800:     if (pkey)
    1801:         *pkey = entry_ptr->me_key;
    1802:     if (phash)
    1803:         *phash = entry_ptr->me_hash;
    1804:     if (pvalue)
    1805:         *pvalue = value;
    1806:     return 1;
    1807: }
    1808: 
    1809: /*
    1810:  * Iterate over a dict.  Use like so:
    1811:  *
    1812:  *     Py_ssize_t i;
    1813:  *     PyObject *key, *value;
    1814:  *     i = 0;   # important!  i should not otherwise be changed by you
    1815:  *     while (PyDict_Next(yourdict, &i, &key, &value)) {
    1816:  *         Refer to borrowed references in key and value.
    1817:  *     }
    1818:  *
    1819:  * Return 1 on success, return 0 when the reached the end of the dictionary
    1820:  * (or if op is not a dictionary)
    1821:  *
    1822:  * CAUTION:  In general, it isn't safe to use PyDict_Next in a loop that
    1823:  * mutates the dict.  One exception:  it is safe if the loop merely changes
    1824:  * the values associated with the keys (but doesn't insert new keys or
    1825:  * delete keys), via PyDict_SetItem().
    1826:  */
    1827: int
    1828: PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
    1829: {
    1830:     return _PyDict_Next(op, ppos, pkey, pvalue, NULL);
    1831: }
    1832: 
    1833: /* Internal version of dict.pop(). */
    1834: PyObject *
    1835: _PyDict_Pop_KnownHash(PyObject *dict, PyObject *key, Py_hash_t hash, PyObject *deflt)
    1836: {
    1837:     Py_ssize_t ix, hashpos;
    1838:     PyObject *old_value, *old_key;
    1839:     PyDictKeyEntry *ep;
    1840:     PyObject **value_addr;
    1841:     PyDictObject *mp;
    1842: 
    1843:     assert(PyDict_Check(dict));
    1844:     mp = (PyDictObject *)dict;
    1845: 
    1846:     if (mp->ma_used == 0) {
    1847:         if (deflt) {
    1848:             Py_INCREF(deflt);
    1849:             return deflt;
    1850:         }
    1851:         _PyErr_SetKeyError(key);
    1852:         return NULL;
    1853:     }
    1854:     ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
    1855:     if (ix == DKIX_ERROR)
    1856:         return NULL;
    1857:     if (ix == DKIX_EMPTY || *value_addr == NULL) {
    1858:         if (deflt) {
    1859:             Py_INCREF(deflt);
    1860:             return deflt;
    1861:         }
    1862:         _PyErr_SetKeyError(key);
    1863:         return NULL;
    1864:     }
    1865: 
    1866:     // Split table doesn't allow deletion.  Combine it.
    1867:     if (_PyDict_HasSplitTable(mp)) {
    1868:         if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
    1869:             return NULL;
    1870:         }
    1871:         ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
    1872:         assert(ix >= 0);
    1873:     }
    1874: 
    1875:     old_value = *value_addr;
    1876:     assert(old_value != NULL);
    1877:     *value_addr = NULL;
    1878:     mp->ma_used--;
    1879:     mp->ma_version_tag = DICT_NEXT_VERSION();
    1880:     dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
    1881:     ep = &DK_ENTRIES(mp->ma_keys)[ix];
    1882:     ENSURE_ALLOWS_DELETIONS(mp);
    1883:     old_key = ep->me_key;
    1884:     ep->me_key = NULL;
    1885:     Py_DECREF(old_key);
    1886: 
    1887:     assert(_PyDict_CheckConsistency(mp));
    1888:     return old_value;
    1889: }
    1890: 
    1891: PyObject *
    1892: _PyDict_Pop(PyObject *dict, PyObject *key, PyObject *deflt)
    1893: {
    1894:     Py_hash_t hash;
    1895: 
    1896:     if (((PyDictObject *)dict)->ma_used == 0) {
    1897:         if (deflt) {
    1898:             Py_INCREF(deflt);
    1899:             return deflt;
    1900:         }
    1901:         _PyErr_SetKeyError(key);
    1902:         return NULL;
    1903:     }
    1904:     if (!PyUnicode_CheckExact(key) ||
    1905:         (hash = ((PyASCIIObject *) key)->hash) == -1) {
    1906:         hash = PyObject_Hash(key);
    1907:         if (hash == -1)
    1908:             return NULL;
    1909:     }
    1910:     return _PyDict_Pop_KnownHash(dict, key, hash, deflt);
    1911: }
    1912: 
    1913: /* Internal version of dict.from_keys().  It is subclass-friendly. */
    1914: PyObject *
    1915: _PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
    1916: {
    1917:     PyObject *it;       /* iter(iterable) */
    1918:     PyObject *key;
    1919:     PyObject *d;
    1920:     int status;
    1921: 
    1922:     d = PyObject_CallObject(cls, NULL);
    1923:     if (d == NULL)
    1924:         return NULL;
    1925: 
    1926:     if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
    1927:         if (PyDict_CheckExact(iterable)) {
    1928:             PyDictObject *mp = (PyDictObject *)d;
    1929:             PyObject *oldvalue;
    1930:             Py_ssize_t pos = 0;
    1931:             PyObject *key;
    1932:             Py_hash_t hash;
    1933: 
    1934:             if (dictresize(mp, ESTIMATE_SIZE(((PyDictObject *)iterable)->ma_used))) {
    1935:                 Py_DECREF(d);
    1936:                 return NULL;
    1937:             }
    1938: 
    1939:             while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
    1940:                 if (insertdict(mp, key, hash, value)) {
    1941:                     Py_DECREF(d);
    1942:                     return NULL;
    1943:                 }
    1944:             }
    1945:             return d;
    1946:         }
    1947:         if (PyAnySet_CheckExact(iterable)) {
    1948:             PyDictObject *mp = (PyDictObject *)d;
    1949:             Py_ssize_t pos = 0;
    1950:             PyObject *key;
    1951:             Py_hash_t hash;
    1952: 
    1953:             if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) {
    1954:                 Py_DECREF(d);
    1955:                 return NULL;
    1956:             }
    1957: 
    1958:             while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
    1959:                 if (insertdict(mp, key, hash, value)) {
    1960:                     Py_DECREF(d);
    1961:                     return NULL;
    1962:                 }
    1963:             }
    1964:             return d;
    1965:         }
    1966:     }
    1967: 
    1968:     it = PyObject_GetIter(iterable);
    1969:     if (it == NULL){
    1970:         Py_DECREF(d);
    1971:         return NULL;
    1972:     }
    1973: 
    1974:     if (PyDict_CheckExact(d)) {
    1975:         while ((key = PyIter_Next(it)) != NULL) {
    1976:             status = PyDict_SetItem(d, key, value);
    1977:             Py_DECREF(key);
    1978:             if (status < 0)
    1979:                 goto Fail;
    1980:         }
    1981:     } else {
    1982:         while ((key = PyIter_Next(it)) != NULL) {
    1983:             status = PyObject_SetItem(d, key, value);
    1984:             Py_DECREF(key);
    1985:             if (status < 0)
    1986:                 goto Fail;
    1987:         }
    1988:     }
    1989: 
    1990:     if (PyErr_Occurred())
    1991:         goto Fail;
    1992:     Py_DECREF(it);
    1993:     return d;
    1994: 
    1995: Fail:
    1996:     Py_DECREF(it);
    1997:     Py_DECREF(d);
    1998:     return NULL;
    1999: }
    2000: 
    2001: /* Methods */
    2002: 
    2003: static void
    2004: dict_dealloc(PyDictObject *mp)
    2005: {
    2006:     PyObject **values = mp->ma_values;
    2007:     PyDictKeysObject *keys = mp->ma_keys;
    2008:     Py_ssize_t i, n;
    2009:     PyObject_GC_UnTrack(mp);
    2010:     Py_TRASHCAN_SAFE_BEGIN(mp)
    2011:     if (values != NULL) {
    2012:         if (values != empty_values) {
    2013:             for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) {
    2014:                 Py_XDECREF(values[i]);
    2015:             }
    2016:             free_values(values);
    2017:         }
    2018:         DK_DECREF(keys);
    2019:     }
    2020:     else if (keys != NULL) {
    2021:         assert(keys->dk_refcnt == 1);
    2022:         DK_DECREF(keys);
    2023:     }
    2024:     if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
    2025:         free_list[numfree++] = mp;
    2026:     else
    2027:         Py_TYPE(mp)->tp_free((PyObject *)mp);
    2028:     Py_TRASHCAN_SAFE_END(mp)
    2029: }
    2030: 
    2031: 
    2032: static PyObject *
    2033: dict_repr(PyDictObject *mp)
    2034: {
    2035:     Py_ssize_t i;
    2036:     PyObject *key = NULL, *value = NULL;
    2037:     _PyUnicodeWriter writer;
    2038:     int first;
    2039: 
    2040:     i = Py_ReprEnter((PyObject *)mp);
    2041:     if (i != 0) {
    2042:         return i > 0 ? PyUnicode_FromString("{...}") : NULL;
    2043:     }
    2044: 
    2045:     if (mp->ma_used == 0) {
    2046:         Py_ReprLeave((PyObject *)mp);
    2047:         return PyUnicode_FromString("{}");
    2048:     }
    2049: 
    2050:     _PyUnicodeWriter_Init(&writer);
    2051:     writer.overallocate = 1;
    2052:     /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
    2053:     writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
    2054: 
    2055:     if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
    2056:         goto error;
    2057: 
    2058:     /* Do repr() on each key+value pair, and insert ": " between them.
    2059:        Note that repr may mutate the dict. */
    2060:     i = 0;
    2061:     first = 1;
    2062:     while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
    2063:         PyObject *s;
    2064:         int res;
    2065: 
    2066:         /* Prevent repr from deleting key or value during key format. */
    2067:         Py_INCREF(key);
    2068:         Py_INCREF(value);
    2069: 
    2070:         if (!first) {
    2071:             if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
    2072:                 goto error;
    2073:         }
    2074:         first = 0;
    2075: 
    2076:         s = PyObject_Repr(key);
    2077:         if (s == NULL)
    2078:             goto error;
    2079:         res = _PyUnicodeWriter_WriteStr(&writer, s);
    2080:         Py_DECREF(s);
    2081:         if (res < 0)
    2082:             goto error;
    2083: 
    2084:         if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
    2085:             goto error;
    2086: 
    2087:         s = PyObject_Repr(value);
    2088:         if (s == NULL)
    2089:             goto error;
    2090:         res = _PyUnicodeWriter_WriteStr(&writer, s);
    2091:         Py_DECREF(s);
    2092:         if (res < 0)
    2093:             goto error;
    2094: 
    2095:         Py_CLEAR(key);
    2096:         Py_CLEAR(value);
    2097:     }
    2098: 
    2099:     writer.overallocate = 0;
    2100:     if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
    2101:         goto error;
    2102: 
    2103:     Py_ReprLeave((PyObject *)mp);
    2104: 
    2105:     return _PyUnicodeWriter_Finish(&writer);
    2106: 
    2107: error:
    2108:     Py_ReprLeave((PyObject *)mp);
    2109:     _PyUnicodeWriter_Dealloc(&writer);
    2110:     Py_XDECREF(key);
    2111:     Py_XDECREF(value);
    2112:     return NULL;
    2113: }
    2114: 
    2115: static Py_ssize_t
    2116: dict_length(PyDictObject *mp)
    2117: {
    2118:     return mp->ma_used;
    2119: }
    2120: 
    2121: static PyObject *
    2122: dict_subscript(PyDictObject *mp, PyObject *key)
    2123: {
    2124:     PyObject *v;
    2125:     Py_ssize_t ix;
    2126:     Py_hash_t hash;
    2127:     PyObject **value_addr;
    2128: 
    2129:     if (!PyUnicode_CheckExact(key) ||
    2130:         (hash = ((PyASCIIObject *) key)->hash) == -1) {
    2131:         hash = PyObject_Hash(key);
    2132:         if (hash == -1)
    2133:             return NULL;
    2134:     }
    2135:     ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
    2136:     if (ix == DKIX_ERROR)
    2137:         return NULL;
    2138:     if (ix == DKIX_EMPTY || *value_addr == NULL) {
    2139:         if (!PyDict_CheckExact(mp)) {
    2140:             /* Look up __missing__ method if we're a subclass. */
    2141:             PyObject *missing, *res;
    2142:             _Py_IDENTIFIER(__missing__);
    2143:             missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__);
    2144:             if (missing != NULL) {
    2145:                 res = PyObject_CallFunctionObjArgs(missing,
    2146:                                                    key, NULL);
    2147:                 Py_DECREF(missing);
    2148:                 return res;
    2149:             }
    2150:             else if (PyErr_Occurred())
    2151:                 return NULL;
    2152:         }
    2153:         _PyErr_SetKeyError(key);
    2154:         return NULL;
    2155:     }
    2156:     v = *value_addr;
    2157:     Py_INCREF(v);
    2158:     return v;
    2159: }
    2160: 
    2161: static int
    2162: dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
    2163: {
    2164:     if (w == NULL)
    2165:         return PyDict_DelItem((PyObject *)mp, v);
    2166:     else
    2167:         return PyDict_SetItem((PyObject *)mp, v, w);
    2168: }
    2169: 
    2170: static PyMappingMethods dict_as_mapping = {
    2171:     (lenfunc)dict_length, /*mp_length*/
    2172:     (binaryfunc)dict_subscript, /*mp_subscript*/
    2173:     (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
    2174: };
    2175: 
    2176: static PyObject *
    2177: dict_keys(PyDictObject *mp)
    2178: {
    2179:     PyObject *v;
    2180:     Py_ssize_t i, j;
    2181:     PyDictKeyEntry *ep;
    2182:     Py_ssize_t size, n, offset;
    2183:     PyObject **value_ptr;
    2184: 
    2185:   again:
    2186:     n = mp->ma_used;
    2187:     v = PyList_New(n);
    2188:     if (v == NULL)
    2189:         return NULL;
    2190:     if (n != mp->ma_used) {
    2191:         /* Durnit.  The allocations caused the dict to resize.
    2192:          * Just start over, this shouldn't normally happen.
    2193:          */
    2194:         Py_DECREF(v);
    2195:         goto again;
    2196:     }
    2197:     ep = DK_ENTRIES(mp->ma_keys);
    2198:     size = mp->ma_keys->dk_nentries;
    2199:     if (mp->ma_values) {
    2200:         value_ptr = mp->ma_values;
    2201:         offset = sizeof(PyObject *);
    2202:     }
    2203:     else {
    2204:         value_ptr = &ep[0].me_value;
    2205:         offset = sizeof(PyDictKeyEntry);
    2206:     }
    2207:     for (i = 0, j = 0; i < size; i++) {
    2208:         if (*value_ptr != NULL) {
    2209:             PyObject *key = ep[i].me_key;
    2210:             Py_INCREF(key);
    2211:             PyList_SET_ITEM(v, j, key);
    2212:             j++;
    2213:         }
    2214:         value_ptr = (PyObject **)(((char *)value_ptr) + offset);
    2215:     }
    2216:     assert(j == n);
    2217:     return v;
    2218: }
    2219: 
    2220: static PyObject *
    2221: dict_values(PyDictObject *mp)
    2222: {
    2223:     PyObject *v;
    2224:     Py_ssize_t i, j;
    2225:     PyDictKeyEntry *ep;
    2226:     Py_ssize_t size, n, offset;
    2227:     PyObject **value_ptr;
    2228: 
    2229:   again:
    2230:     n = mp->ma_used;
    2231:     v = PyList_New(n);
    2232:     if (v == NULL)
    2233:         return NULL;
    2234:     if (n != mp->ma_used) {
    2235:         /* Durnit.  The allocations caused the dict to resize.
    2236:          * Just start over, this shouldn't normally happen.
    2237:          */
    2238:         Py_DECREF(v);
    2239:         goto again;
    2240:     }
    2241:     ep = DK_ENTRIES(mp->ma_keys);
    2242:     size = mp->ma_keys->dk_nentries;
    2243:     if (mp->ma_values) {
    2244:         value_ptr = mp->ma_values;
    2245:         offset = sizeof(PyObject *);
    2246:     }
    2247:     else {
    2248:         value_ptr = &ep[0].me_value;
    2249:         offset = sizeof(PyDictKeyEntry);
    2250:     }
    2251:     for (i = 0, j = 0; i < size; i++) {
    2252:         PyObject *value = *value_ptr;
    2253:         value_ptr = (PyObject **)(((char *)value_ptr) + offset);
    2254:         if (value != NULL) {
    2255:             Py_INCREF(value);
    2256:             PyList_SET_ITEM(v, j, value);
    2257:             j++;
    2258:         }
    2259:     }
    2260:     assert(j == n);
    2261:     return v;
    2262: }
    2263: 
    2264: static PyObject *
    2265: dict_items(PyDictObject *mp)
    2266: {
    2267:     PyObject *v;
    2268:     Py_ssize_t i, j, n;
    2269:     Py_ssize_t size, offset;
    2270:     PyObject *item, *key;
    2271:     PyDictKeyEntry *ep;
    2272:     PyObject **value_ptr;
    2273: 
    2274:     /* Preallocate the list of tuples, to avoid allocations during
    2275:      * the loop over the items, which could trigger GC, which
    2276:      * could resize the dict. :-(
    2277:      */
    2278:   again:
    2279:     n = mp->ma_used;
    2280:     v = PyList_New(n);
    2281:     if (v == NULL)
    2282:         return NULL;
    2283:     for (i = 0; i < n; i++) {
    2284:         item = PyTuple_New(2);
    2285:         if (item == NULL) {
    2286:             Py_DECREF(v);
    2287:             return NULL;
    2288:         }
    2289:         PyList_SET_ITEM(v, i, item);
    2290:     }
    2291:     if (n != mp->ma_used) {
    2292:         /* Durnit.  The allocations caused the dict to resize.
    2293:          * Just start over, this shouldn't normally happen.
    2294:          */
    2295:         Py_DECREF(v);
    2296:         goto again;
    2297:     }
    2298:     /* Nothing we do below makes any function calls. */
    2299:     ep = DK_ENTRIES(mp->ma_keys);
    2300:     size = mp->ma_keys->dk_nentries;
    2301:     if (mp->ma_values) {
    2302:         value_ptr = mp->ma_values;
    2303:         offset = sizeof(PyObject *);
    2304:     }
    2305:     else {
    2306:         value_ptr = &ep[0].me_value;
    2307:         offset = sizeof(PyDictKeyEntry);
    2308:     }
    2309:     for (i = 0, j = 0; i < size; i++) {
    2310:         PyObject *value = *value_ptr;
    2311:         value_ptr = (PyObject **)(((char *)value_ptr) + offset);
    2312:         if (value != NULL) {
    2313:             key = ep[i].me_key;
    2314:             item = PyList_GET_ITEM(v, j);
    2315:             Py_INCREF(key);
    2316:             PyTuple_SET_ITEM(item, 0, key);
    2317:             Py_INCREF(value);
    2318:             PyTuple_SET_ITEM(item, 1, value);
    2319:             j++;
    2320:         }
    2321:     }
    2322:     assert(j == n);
    2323:     return v;
    2324: }
    2325: 
    2326: /*[clinic input]
    2327: @classmethod
    2328: dict.fromkeys
    2329:     iterable: object
    2330:     value: object=None
    2331:     /
    2332: 
    2333: Returns a new dict with keys from iterable and values equal to value.
    2334: [clinic start generated code]*/
    2335: 
    2336: static PyObject *
    2337: dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
    2338: /*[clinic end generated code: output=8fb98e4b10384999 input=b85a667f9bf4669d]*/
    2339: {
    2340:     return _PyDict_FromKeys((PyObject *)type, iterable, value);
    2341: }
    2342: 
    2343: static int
    2344: dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
    2345:                    const char *methname)
    2346: {
    2347:     PyObject *arg = NULL;
    2348:     int result = 0;
    2349: 
    2350:     if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
    2351:         result = -1;
    2352: 
    2353:     else if (arg != NULL) {
    2354:         _Py_IDENTIFIER(keys);
    2355:         if (_PyObject_HasAttrId(arg, &PyId_keys))
    2356:             result = PyDict_Merge(self, arg, 1);
    2357:         else
    2358:             result = PyDict_MergeFromSeq2(self, arg, 1);
    2359:     }
    2360:     if (result == 0 && kwds != NULL) {
    2361:         if (PyArg_ValidateKeywordArguments(kwds))
    2362:             result = PyDict_Merge(self, kwds, 1);
    2363:         else
    2364:             result = -1;
    2365:     }
    2366:     return result;
    2367: }
    2368: 
    2369: static PyObject *
    2370: dict_update(PyObject *self, PyObject *args, PyObject *kwds)
    2371: {
    2372:     if (dict_update_common(self, args, kwds, "update") != -1)
    2373:         Py_RETURN_NONE;
    2374:     return NULL;
    2375: }
    2376: 
    2377: /* Update unconditionally replaces existing items.
    2378:    Merge has a 3rd argument 'override'; if set, it acts like Update,
    2379:    otherwise it leaves existing items unchanged.
    2380: 
    2381:    PyDict_{Update,Merge} update/merge from a mapping object.
    2382: 
    2383:    PyDict_MergeFromSeq2 updates/merges from any iterable object
    2384:    producing iterable objects of length 2.
    2385: */
    2386: 
    2387: int
    2388: PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
    2389: {
    2390:     PyObject *it;       /* iter(seq2) */
    2391:     Py_ssize_t i;       /* index into seq2 of current element */
    2392:     PyObject *item;     /* seq2[i] */
    2393:     PyObject *fast;     /* item as a 2-tuple or 2-list */
    2394: 
    2395:     assert(d != NULL);
    2396:     assert(PyDict_Check(d));
    2397:     assert(seq2 != NULL);
    2398: 
    2399:     it = PyObject_GetIter(seq2);
    2400:     if (it == NULL)
    2401:         return -1;
    2402: 
    2403:     for (i = 0; ; ++i) {
    2404:         PyObject *key, *value;
    2405:         Py_ssize_t n;
    2406: 
    2407:         fast = NULL;
    2408:         item = PyIter_Next(it);
    2409:         if (item == NULL) {
    2410:             if (PyErr_Occurred())
    2411:                 goto Fail;
    2412:             break;
    2413:         }
    2414: 
    2415:         /* Convert item to sequence, and verify length 2. */
    2416:         fast = PySequence_Fast(item, "");
    2417:         if (fast == NULL) {
    2418:             if (PyErr_ExceptionMatches(PyExc_TypeError))
    2419:                 PyErr_Format(PyExc_TypeError,
    2420:                     "cannot convert dictionary update "
    2421:                     "sequence element #%zd to a sequence",
    2422:                     i);
    2423:             goto Fail;
    2424:         }
    2425:         n = PySequence_Fast_GET_SIZE(fast);
    2426:         if (n != 2) {
    2427:             PyErr_Format(PyExc_ValueError,
    2428:                          "dictionary update sequence element #%zd "
    2429:                          "has length %zd; 2 is required",
    2430:                          i, n);
    2431:             goto Fail;
    2432:         }
    2433: 
    2434:         /* Update/merge with this (key, value) pair. */
    2435:         key = PySequence_Fast_GET_ITEM(fast, 0);
    2436:         value = PySequence_Fast_GET_ITEM(fast, 1);
    2437:         Py_INCREF(key);
    2438:         Py_INCREF(value);
    2439:         if (override || PyDict_GetItem(d, key) == NULL) {
    2440:             int status = PyDict_SetItem(d, key, value);
    2441:             if (status < 0) {
    2442:                 Py_DECREF(key);
    2443:                 Py_DECREF(value);
    2444:                 goto Fail;
    2445:             }
    2446:         }
    2447:         Py_DECREF(key);
    2448:         Py_DECREF(value);
    2449:         Py_DECREF(fast);
    2450:         Py_DECREF(item);
    2451:     }
    2452: 
    2453:     i = 0;
    2454:     assert(_PyDict_CheckConsistency((PyDictObject *)d));
    2455:     goto Return;
    2456: Fail:
    2457:     Py_XDECREF(item);
    2458:     Py_XDECREF(fast);
    2459:     i = -1;
    2460: Return:
    2461:     Py_DECREF(it);
    2462:     return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
    2463: }
    2464: 
    2465: static int
    2466: dict_merge(PyObject *a, PyObject *b, int override)
    2467: {
    2468:     PyDictObject *mp, *other;
    2469:     Py_ssize_t i, n;
    2470:     PyDictKeyEntry *entry, *ep0;
    2471: 
    2472:     assert(0 <= override && override <= 2);
    2473: 
    2474:     /* We accept for the argument either a concrete dictionary object,
    2475:      * or an abstract "mapping" object.  For the former, we can do
    2476:      * things quite efficiently.  For the latter, we only require that
    2477:      * PyMapping_Keys() and PyObject_GetItem() be supported.
    2478:      */
    2479:     if (a == NULL || !PyDict_Check(a) || b == NULL) {
    2480:         PyErr_BadInternalCall();
    2481:         return -1;
    2482:     }
    2483:     mp = (PyDictObject*)a;
    2484:     if (PyDict_Check(b)) {
    2485:         other = (PyDictObject*)b;
    2486:         if (other == mp || other->ma_used == 0)
    2487:             /* a.update(a) or a.update({}); nothing to do */
    2488:             return 0;
    2489:         if (mp->ma_used == 0)
    2490:             /* Since the target dict is empty, PyDict_GetItem()
    2491:              * always returns NULL.  Setting override to 1
    2492:              * skips the unnecessary test.
    2493:              */
    2494:             override = 1;
    2495:         /* Do one big resize at the start, rather than
    2496:          * incrementally resizing as we insert new items.  Expect
    2497:          * that there will be no (or few) overlapping keys.
    2498:          */
    2499:         if (USABLE_FRACTION(mp->ma_keys->dk_size) < other->ma_used) {
    2500:             if (dictresize(mp, ESTIMATE_SIZE(mp->ma_used + other->ma_used))) {
    2501:                return -1;
    2502:             }
    2503:         }
    2504:         ep0 = DK_ENTRIES(other->ma_keys);
    2505:         for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) {
    2506:             PyObject *key, *value;
    2507:             Py_hash_t hash;
    2508:             entry = &ep0[i];
    2509:             key = entry->me_key;
    2510:             hash = entry->me_hash;
    2511:             if (other->ma_values)
    2512:                 value = other->ma_values[i];
    2513:             else
    2514:                 value = entry->me_value;
    2515: 
    2516:             if (value != NULL) {
    2517:                 int err = 0;
    2518:                 Py_INCREF(key);
    2519:                 Py_INCREF(value);
    2520:                 if (override == 1)
    2521:                     err = insertdict(mp, key, hash, value);
    2522:                 else if (_PyDict_GetItem_KnownHash(a, key, hash) == NULL) {
    2523:                     if (PyErr_Occurred()) {
    2524:                         Py_DECREF(value);
    2525:                         Py_DECREF(key);
    2526:                         return -1;
    2527:                     }
    2528:                     err = insertdict(mp, key, hash, value);
    2529:                 }
    2530:                 else if (override != 0) {
    2531:                     _PyErr_SetKeyError(key);
    2532:                     Py_DECREF(value);
    2533:                     Py_DECREF(key);
    2534:                     return -1;
    2535:                 }
    2536:                 Py_DECREF(value);
    2537:                 Py_DECREF(key);
    2538:                 if (err != 0)
    2539:                     return -1;
    2540: 
    2541:                 if (n != other->ma_keys->dk_nentries) {
    2542:                     PyErr_SetString(PyExc_RuntimeError,
    2543:                                     "dict mutated during update");
    2544:                     return -1;
    2545:                 }
    2546:             }
    2547:         }
    2548:     }
    2549:     else {
    2550:         /* Do it the generic, slower way */
    2551:         PyObject *keys = PyMapping_Keys(b);
    2552:         PyObject *iter;
    2553:         PyObject *key, *value;
    2554:         int status;
    2555: 
    2556:         if (keys == NULL)
    2557:             /* Docstring says this is equivalent to E.keys() so
    2558:              * if E doesn't have a .keys() method we want
    2559:              * AttributeError to percolate up.  Might as well
    2560:              * do the same for any other error.
    2561:              */
    2562:             return -1;
    2563: 
    2564:         iter = PyObject_GetIter(keys);
    2565:         Py_DECREF(keys);
    2566:         if (iter == NULL)
    2567:             return -1;
    2568: 
    2569:         for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
    2570:             if (override != 1 && PyDict_GetItem(a, key) != NULL) {
    2571:                 if (override != 0) {
    2572:                     _PyErr_SetKeyError(key);
    2573:                     Py_DECREF(key);
    2574:                     Py_DECREF(iter);
    2575:                     return -1;
    2576:                 }
    2577:                 Py_DECREF(key);
    2578:                 continue;
    2579:             }
    2580:             value = PyObject_GetItem(b, key);
    2581:             if (value == NULL) {
    2582:                 Py_DECREF(iter);
    2583:                 Py_DECREF(key);
    2584:                 return -1;
    2585:             }
    2586:             status = PyDict_SetItem(a, key, value);
    2587:             Py_DECREF(key);
    2588:             Py_DECREF(value);
    2589:             if (status < 0) {
    2590:                 Py_DECREF(iter);
    2591:                 return -1;
    2592:             }
    2593:         }
    2594:         Py_DECREF(iter);
    2595:         if (PyErr_Occurred())
    2596:             /* Iterator completed, via error */
    2597:             return -1;
    2598:     }
    2599:     assert(_PyDict_CheckConsistency((PyDictObject *)a));
    2600:     return 0;
    2601: }
    2602: 
    2603: int
    2604: PyDict_Update(PyObject *a, PyObject *b)
    2605: {
    2606:     return dict_merge(a, b, 1);
    2607: }
    2608: 
    2609: int
    2610: PyDict_Merge(PyObject *a, PyObject *b, int override)
    2611: {
    2612:     /* XXX Deprecate override not in (0, 1). */
    2613:     return dict_merge(a, b, override != 0);
    2614: }
    2615: 
    2616: int
    2617: _PyDict_MergeEx(PyObject *a, PyObject *b, int override)
    2618: {
    2619:     return dict_merge(a, b, override);
    2620: }
    2621: 
    2622: static PyObject *
    2623: dict_copy(PyDictObject *mp)
    2624: {
    2625:     return PyDict_Copy((PyObject*)mp);
    2626: }
    2627: 
    2628: PyObject *
    2629: PyDict_Copy(PyObject *o)
    2630: {
    2631:     PyObject *copy;
    2632:     PyDictObject *mp;
    2633:     Py_ssize_t i, n;
    2634: 
    2635:     if (o == NULL || !PyDict_Check(o)) {
    2636:         PyErr_BadInternalCall();
    2637:         return NULL;
    2638:     }
    2639:     mp = (PyDictObject *)o;
    2640:     if (_PyDict_HasSplitTable(mp)) {
    2641:         PyDictObject *split_copy;
    2642:         Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys));
    2643:         PyObject **newvalues;
    2644:         newvalues = new_values(size);
    2645:         if (newvalues == NULL)
    2646:             return PyErr_NoMemory();
    2647:         split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
    2648:         if (split_copy == NULL) {
    2649:             free_values(newvalues);
    2650:             return NULL;
    2651:         }
    2652:         split_copy->ma_values = newvalues;
    2653:         split_copy->ma_keys = mp->ma_keys;
    2654:         split_copy->ma_used = mp->ma_used;
    2655:         DK_INCREF(mp->ma_keys);
    2656:         for (i = 0, n = size; i < n; i++) {
    2657:             PyObject *value = mp->ma_values[i];
    2658:             Py_XINCREF(value);
    2659:             split_copy->ma_values[i] = value;
    2660:         }
    2661:         if (_PyObject_GC_IS_TRACKED(mp))
    2662:             _PyObject_GC_TRACK(split_copy);
    2663:         return (PyObject *)split_copy;
    2664:     }
    2665:     copy = PyDict_New();
    2666:     if (copy == NULL)
    2667:         return NULL;
    2668:     if (PyDict_Merge(copy, o, 1) == 0)
    2669:         return copy;
    2670:     Py_DECREF(copy);
    2671:     return NULL;
    2672: }
    2673: 
    2674: Py_ssize_t
    2675: PyDict_Size(PyObject *mp)
    2676: {
    2677:     if (mp == NULL || !PyDict_Check(mp)) {
    2678:         PyErr_BadInternalCall();
    2679:         return -1;
    2680:     }
    2681:     return ((PyDictObject *)mp)->ma_used;
    2682: }
    2683: 
    2684: PyObject *
    2685: PyDict_Keys(PyObject *mp)
    2686: {
    2687:     if (mp == NULL || !PyDict_Check(mp)) {
    2688:         PyErr_BadInternalCall();
    2689:         return NULL;
    2690:     }
    2691:     return dict_keys((PyDictObject *)mp);
    2692: }
    2693: 
    2694: PyObject *
    2695: PyDict_Values(PyObject *mp)
    2696: {
    2697:     if (mp == NULL || !PyDict_Check(mp)) {
    2698:         PyErr_BadInternalCall();
    2699:         return NULL;
    2700:     }
    2701:     return dict_values((PyDictObject *)mp);
    2702: }
    2703: 
    2704: PyObject *
    2705: PyDict_Items(PyObject *mp)
    2706: {
    2707:     if (mp == NULL || !PyDict_Check(mp)) {
    2708:         PyErr_BadInternalCall();
    2709:         return NULL;
    2710:     }
    2711:     return dict_items((PyDictObject *)mp);
    2712: }
    2713: 
    2714: /* Return 1 if dicts equal, 0 if not, -1 if error.
    2715:  * Gets out as soon as any difference is detected.
    2716:  * Uses only Py_EQ comparison.
    2717:  */
    2718: static int
    2719: dict_equal(PyDictObject *a, PyDictObject *b)
    2720: {
    2721:     Py_ssize_t i;
    2722: 
    2723:     if (a->ma_used != b->ma_used)
    2724:         /* can't be equal if # of entries differ */
    2725:         return 0;
    2726:     /* Same # of entries -- check all of 'em.  Exit early on any diff. */
    2727:     for (i = 0; i < a->ma_keys->dk_nentries; i++) {
    2728:         PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
    2729:         PyObject *aval;
    2730:         if (a->ma_values)
    2731:             aval = a->ma_values[i];
    2732:         else
    2733:             aval = ep->me_value;
    2734:         if (aval != NULL) {
    2735:             int cmp;
    2736:             PyObject *bval;
    2737:             PyObject **vaddr;
    2738:             PyObject *key = ep->me_key;
    2739:             /* temporarily bump aval's refcount to ensure it stays
    2740:                alive until we're done with it */
    2741:             Py_INCREF(aval);
    2742:             /* ditto for key */
    2743:             Py_INCREF(key);
    2744:             /* reuse the known hash value */
    2745:             if ((b->ma_keys->dk_lookup)(b, key, ep->me_hash, &vaddr, NULL) < 0)
    2746:                 bval = NULL;
    2747:             else
    2748:                 bval = *vaddr;
    2749:             if (bval == NULL) {
    2750:                 Py_DECREF(key);
    2751:                 Py_DECREF(aval);
    2752:                 if (PyErr_Occurred())
    2753:                     return -1;
    2754:                 return 0;
    2755:             }
    2756:             cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
    2757:             Py_DECREF(key);
    2758:             Py_DECREF(aval);
    2759:             if (cmp <= 0)  /* error or not equal */
    2760:                 return cmp;
    2761:         }
    2762:     }
    2763:     return 1;
    2764: }
    2765: 
    2766: static PyObject *
    2767: dict_richcompare(PyObject *v, PyObject *w, int op)
    2768: {
    2769:     int cmp;
    2770:     PyObject *res;
    2771: 
    2772:     if (!PyDict_Check(v) || !PyDict_Check(w)) {
    2773:         res = Py_NotImplemented;
    2774:     }
    2775:     else if (op == Py_EQ || op == Py_NE) {
    2776:         cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
    2777:         if (cmp < 0)
    2778:             return NULL;
    2779:         res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
    2780:     }
    2781:     else
    2782:         res = Py_NotImplemented;
    2783:     Py_INCREF(res);
    2784:     return res;
    2785: }
    2786: 
    2787: /*[clinic input]
    2788: 
    2789: @coexist
    2790: dict.__contains__
    2791: 
    2792:   key: object
    2793:   /
    2794: 
    2795: True if D has a key k, else False.
    2796: [clinic start generated code]*/
    2797: 
    2798: static PyObject *
    2799: dict___contains__(PyDictObject *self, PyObject *key)
    2800: /*[clinic end generated code: output=a3d03db709ed6e6b input=b852b2a19b51ab24]*/
    2801: {
    2802:     register PyDictObject *mp = self;
    2803:     Py_hash_t hash;
    2804:     Py_ssize_t ix;
    2805:     PyObject **value_addr;
    2806: 
    2807:     if (!PyUnicode_CheckExact(key) ||
    2808:         (hash = ((PyASCIIObject *) key)->hash) == -1) {
    2809:         hash = PyObject_Hash(key);
    2810:         if (hash == -1)
    2811:             return NULL;
    2812:     }
    2813:     ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
    2814:     if (ix == DKIX_ERROR)
    2815:         return NULL;
    2816:     if (ix == DKIX_EMPTY || *value_addr == NULL)
    2817:         Py_RETURN_FALSE;
    2818:     Py_RETURN_TRUE;
    2819: }
    2820: 
    2821: static PyObject *
    2822: dict_get(PyDictObject *mp, PyObject *args)
    2823: {
    2824:     PyObject *key;
    2825:     PyObject *failobj = Py_None;
    2826:     PyObject *val = NULL;
    2827:     Py_hash_t hash;
    2828:     Py_ssize_t ix;
    2829:     PyObject **value_addr;
    2830: 
    2831:     if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
    2832:         return NULL;
    2833: 
    2834:     if (!PyUnicode_CheckExact(key) ||
    2835:         (hash = ((PyASCIIObject *) key)->hash) == -1) {
    2836:         hash = PyObject_Hash(key);
    2837:         if (hash == -1)
    2838:             return NULL;
    2839:     }
    2840:     ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
    2841:     if (ix == DKIX_ERROR)
    2842:         return NULL;
    2843:     if (ix == DKIX_EMPTY || *value_addr == NULL)
    2844:         val = failobj;
    2845:     else
    2846:         val = *value_addr;
    2847:     Py_INCREF(val);
    2848:     return val;
    2849: }
    2850: 
    2851: PyObject *
    2852: PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
    2853: {
    2854:     PyDictObject *mp = (PyDictObject *)d;
    2855:     PyObject *value;
    2856:     Py_hash_t hash;
    2857:     Py_ssize_t hashpos, ix;
    2858:     PyObject **value_addr;
    2859: 
    2860:     if (!PyDict_Check(d)) {
    2861:         PyErr_BadInternalCall();
    2862:         return NULL;
    2863:     }
    2864: 
    2865:     if (!PyUnicode_CheckExact(key) ||
    2866:         (hash = ((PyASCIIObject *) key)->hash) == -1) {
    2867:         hash = PyObject_Hash(key);
    2868:         if (hash == -1)
    2869:             return NULL;
    2870:     }
    2871: 
    2872:     if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) {
    2873:         if (insertion_resize(mp) < 0)
    2874:             return NULL;
    2875:     }
    2876: 
    2877:     ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos);
    2878:     if (ix == DKIX_ERROR)
    2879:         return NULL;
    2880: 
    2881:     if (_PyDict_HasSplitTable(mp) &&
    2882:         ((ix >= 0 && *value_addr == NULL && mp->ma_used != ix) ||
    2883:          (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) {
    2884:         if (insertion_resize(mp) < 0) {
    2885:             return NULL;
    2886:         }
    2887:         find_empty_slot(mp, key, hash, &value_addr, &hashpos);
    2888:         ix = DKIX_EMPTY;
    2889:     }
    2890: 
    2891:     if (ix == DKIX_EMPTY) {
    2892:         PyDictKeyEntry *ep, *ep0;
    2893:         value = defaultobj;
    2894:         if (mp->ma_keys->dk_usable <= 0) {
    2895:             if (insertion_resize(mp) < 0) {
    2896:                 return NULL;
    2897:             }
    2898:             find_empty_slot(mp, key, hash, &value_addr, &hashpos);
    2899:         }
    2900:         ep0 = DK_ENTRIES(mp->ma_keys);
    2901:         ep = &ep0[mp->ma_keys->dk_nentries];
    2902:         dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
    2903:         Py_INCREF(key);
    2904:         Py_INCREF(value);
    2905:         MAINTAIN_TRACKING(mp, key, value);
    2906:         ep->me_key = key;
    2907:         ep->me_hash = hash;
    2908:         if (mp->ma_values) {
    2909:             assert(mp->ma_values[mp->ma_keys->dk_nentries] == NULL);
    2910:             mp->ma_values[mp->ma_keys->dk_nentries] = value;
    2911:         }
    2912:         else {
    2913:             ep->me_value = value;
    2914:         }
    2915:         mp->ma_used++;
    2916:         mp->ma_version_tag = DICT_NEXT_VERSION();
    2917:         mp->ma_keys->dk_usable--;
    2918:         mp->ma_keys->dk_nentries++;
    2919:         assert(mp->ma_keys->dk_usable >= 0);
    2920:     }
    2921:     else if (*value_addr == NULL) {
    2922:         value = defaultobj;
    2923:         assert(_PyDict_HasSplitTable(mp));
    2924:         assert(ix == mp->ma_used);
    2925:         Py_INCREF(value);
    2926:         MAINTAIN_TRACKING(mp, key, value);
    2927:         *value_addr = value;
    2928:         mp->ma_used++;
    2929:         mp->ma_version_tag = DICT_NEXT_VERSION();
    2930:     }
    2931:     else {
    2932:         value = *value_addr;
    2933:     }
    2934: 
    2935:     assert(_PyDict_CheckConsistency(mp));
    2936:     return value;
    2937: }
    2938: 
    2939: static PyObject *
    2940: dict_setdefault(PyDictObject *mp, PyObject *args)
    2941: {
    2942:     PyObject *key, *val;
    2943:     PyObject *defaultobj = Py_None;
    2944: 
    2945:     if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &defaultobj))
    2946:         return NULL;
    2947: 
    2948:     val = PyDict_SetDefault((PyObject *)mp, key, defaultobj);
    2949:     Py_XINCREF(val);
    2950:     return val;
    2951: }
    2952: 
    2953: static PyObject *
    2954: dict_clear(PyDictObject *mp)
    2955: {
    2956:     PyDict_Clear((PyObject *)mp);
    2957:     Py_RETURN_NONE;
    2958: }
    2959: 
    2960: static PyObject *
    2961: dict_pop(PyDictObject *mp, PyObject *args)
    2962: {
    2963:     PyObject *key, *deflt = NULL;
    2964: 
    2965:     if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
    2966:         return NULL;
    2967: 
    2968:     return _PyDict_Pop((PyObject*)mp, key, deflt);
    2969: }
    2970: 
    2971: static PyObject *
    2972: dict_popitem(PyDictObject *mp)
    2973: {
    2974:     Py_ssize_t i, j;
    2975:     PyDictKeyEntry *ep0, *ep;
    2976:     PyObject *res;
    2977: 
    2978:     /* Allocate the result tuple before checking the size.  Believe it
    2979:      * or not, this allocation could trigger a garbage collection which
    2980:      * could empty the dict, so if we checked the size first and that
    2981:      * happened, the result would be an infinite loop (searching for an
    2982:      * entry that no longer exists).  Note that the usual popitem()
    2983:      * idiom is "while d: k, v = d.popitem()". so needing to throw the
    2984:      * tuple away if the dict *is* empty isn't a significant
    2985:      * inefficiency -- possible, but unlikely in practice.
    2986:      */
    2987:     res = PyTuple_New(2);
    2988:     if (res == NULL)
    2989:         return NULL;
    2990:     if (mp->ma_used == 0) {
    2991:         Py_DECREF(res);
    2992:         PyErr_SetString(PyExc_KeyError,
    2993:                         "popitem(): dictionary is empty");
    2994:         return NULL;
    2995:     }
    2996:     /* Convert split table to combined table */
    2997:     if (mp->ma_keys->dk_lookup == lookdict_split) {
    2998:         if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
    2999:             Py_DECREF(res);
    3000:             return NULL;
    3001:         }
    3002:     }
    3003:     ENSURE_ALLOWS_DELETIONS(mp);
    3004: 
    3005:     /* Pop last item */
    3006:     ep0 = DK_ENTRIES(mp->ma_keys);
    3007:     i = mp->ma_keys->dk_nentries - 1;
    3008:     while (i >= 0 && ep0[i].me_value == NULL) {
    3009:         i--;
    3010:     }
    3011:     assert(i >= 0);
    3012: 
    3013:     ep = &ep0[i];
    3014:     j = lookdict_index(mp->ma_keys, ep->me_hash, i);
    3015:     assert(j >= 0);
    3016:     assert(dk_get_index(mp->ma_keys, j) == i);
    3017:     dk_set_index(mp->ma_keys, j, DKIX_DUMMY);
    3018: 
    3019:     PyTuple_SET_ITEM(res, 0, ep->me_key);
    3020:     PyTuple_SET_ITEM(res, 1, ep->me_value);
    3021:     ep->me_key = NULL;
    3022:     ep->me_value = NULL;
    3023:     /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
    3024:     mp->ma_keys->dk_nentries = i;
    3025:     mp->ma_used--;
    3026:     mp->ma_version_tag = DICT_NEXT_VERSION();
    3027:     assert(_PyDict_CheckConsistency(mp));
    3028:     return res;
    3029: }
    3030: 
    3031: static int
    3032: dict_traverse(PyObject *op, visitproc visit, void *arg)
    3033: {
    3034:     PyDictObject *mp = (PyDictObject *)op;
    3035:     PyDictKeysObject *keys = mp->ma_keys;
    3036:     PyDictKeyEntry *entries = DK_ENTRIES(keys);
    3037:     Py_ssize_t i, n = keys->dk_nentries;
    3038: 
    3039:     if (keys->dk_lookup == lookdict) {
    3040:         for (i = 0; i < n; i++) {
    3041:             if (entries[i].me_value != NULL) {
    3042:                 Py_VISIT(entries[i].me_value);
    3043:                 Py_VISIT(entries[i].me_key);
    3044:             }
    3045:         }
    3046:     }
    3047:     else {
    3048:         if (mp->ma_values != NULL) {
    3049:             for (i = 0; i < n; i++) {
    3050:                 Py_VISIT(mp->ma_values[i]);
    3051:             }
    3052:         }
    3053:         else {
    3054:             for (i = 0; i < n; i++) {
    3055:                 Py_VISIT(entries[i].me_value);
    3056:             }
    3057:         }
    3058:     }
    3059:     return 0;
    3060: }
    3061: 
    3062: static int
    3063: dict_tp_clear(PyObject *op)
    3064: {
    3065:     PyDict_Clear(op);
    3066:     return 0;
    3067: }
    3068: 
    3069: static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
    3070: 
    3071: Py_ssize_t
    3072: _PyDict_SizeOf(PyDictObject *mp)
    3073: {
    3074:     Py_ssize_t size, usable, res;
    3075: 
    3076:     size = DK_SIZE(mp->ma_keys);
    3077:     usable = USABLE_FRACTION(size);
    3078: 
    3079:     res = _PyObject_SIZE(Py_TYPE(mp));
    3080:     if (mp->ma_values)
    3081:         res += usable * sizeof(PyObject*);
    3082:     /* If the dictionary is split, the keys portion is accounted-for
    3083:        in the type object. */
    3084:     if (mp->ma_keys->dk_refcnt == 1)
    3085:         res += (sizeof(PyDictKeysObject)
    3086:                 - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
    3087:                 + DK_IXSIZE(mp->ma_keys) * size
    3088:                 + sizeof(PyDictKeyEntry) * usable);
    3089:     return res;
    3090: }
    3091: 
    3092: Py_ssize_t
    3093: _PyDict_KeysSize(PyDictKeysObject *keys)
    3094: {
    3095:     return (sizeof(PyDictKeysObject)
    3096:             - Py_MEMBER_SIZE(PyDictKeysObject, dk_indices)
    3097:             + DK_IXSIZE(keys) * DK_SIZE(keys)
    3098:             + USABLE_FRACTION(DK_SIZE(keys)) * sizeof(PyDictKeyEntry));
    3099: }
    3100: 
    3101: static PyObject *
    3102: dict_sizeof(PyDictObject *mp)
    3103: {
    3104:     return PyLong_FromSsize_t(_PyDict_SizeOf(mp));
    3105: }
    3106: 
    3107: PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
    3108: 
    3109: PyDoc_STRVAR(sizeof__doc__,
    3110: "D.__sizeof__() -> size of D in memory, in bytes");
    3111: 
    3112: PyDoc_STRVAR(get__doc__,
    3113: "D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.");
    3114: 
    3115: PyDoc_STRVAR(setdefault_doc__,
    3116: "D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D");
    3117: 
    3118: PyDoc_STRVAR(pop__doc__,
    3119: "D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\
If key is not found, d is returned if given, otherwise KeyError is raised");
    3121: 
    3122: PyDoc_STRVAR(popitem__doc__,
    3123: "D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
2-tuple; but raise KeyError if D is empty.");
    3125: 
    3126: PyDoc_STRVAR(update__doc__,
    3127: "D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.\n\
If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]\n\
If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v\n\
In either case, this is followed by: for k in F:  D[k] = F[k]");
    3131: 
    3132: PyDoc_STRVAR(clear__doc__,
    3133: "D.clear() -> None.  Remove all items from D.");
    3134: 
    3135: PyDoc_STRVAR(copy__doc__,
    3136: "D.copy() -> a shallow copy of D");
    3137: 
    3138: /* Forward */
    3139: static PyObject *dictkeys_new(PyObject *);
    3140: static PyObject *dictitems_new(PyObject *);
    3141: static PyObject *dictvalues_new(PyObject *);
    3142: 
    3143: PyDoc_STRVAR(keys__doc__,
    3144:              "D.keys() -> a set-like object providing a view on D's keys");
    3145: PyDoc_STRVAR(items__doc__,
    3146:              "D.items() -> a set-like object providing a view on D's items");
    3147: PyDoc_STRVAR(values__doc__,
    3148:              "D.values() -> an object providing a view on D's values");
    3149: 
    3150: static PyMethodDef mapp_methods[] = {
    3151:     DICT___CONTAINS___METHODDEF
    3152:     {"__getitem__", (PyCFunction)dict_subscript,        METH_O | METH_COEXIST,
    3153:      getitem__doc__},
    3154:     {"__sizeof__",      (PyCFunction)dict_sizeof,       METH_NOARGS,
    3155:      sizeof__doc__},
    3156:     {"get",         (PyCFunction)dict_get,          METH_VARARGS,
    3157:      get__doc__},
    3158:     {"setdefault",  (PyCFunction)dict_setdefault,   METH_VARARGS,
    3159:      setdefault_doc__},
    3160:     {"pop",         (PyCFunction)dict_pop,          METH_VARARGS,
    3161:      pop__doc__},
    3162:     {"popitem",         (PyCFunction)dict_popitem,      METH_NOARGS,
    3163:      popitem__doc__},
    3164:     {"keys",            (PyCFunction)dictkeys_new,      METH_NOARGS,
    3165:     keys__doc__},
    3166:     {"items",           (PyCFunction)dictitems_new,     METH_NOARGS,
    3167:     items__doc__},
    3168:     {"values",          (PyCFunction)dictvalues_new,    METH_NOARGS,
    3169:     values__doc__},
    3170:     {"update",          (PyCFunction)dict_update,       METH_VARARGS | METH_KEYWORDS,
    3171:      update__doc__},
    3172:     DICT_FROMKEYS_METHODDEF
    3173:     {"clear",           (PyCFunction)dict_clear,        METH_NOARGS,
    3174:      clear__doc__},
    3175:     {"copy",            (PyCFunction)dict_copy,         METH_NOARGS,
    3176:      copy__doc__},
    3177:     {NULL,              NULL}   /* sentinel */
    3178: };
    3179: 
    3180: /* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
    3181: int
    3182: PyDict_Contains(PyObject *op, PyObject *key)
    3183: {
    3184:     Py_hash_t hash;
    3185:     Py_ssize_t ix;
    3186:     PyDictObject *mp = (PyDictObject *)op;
    3187:     PyObject **value_addr;
    3188: 
    3189:     if (!PyUnicode_CheckExact(key) ||
    3190:         (hash = ((PyASCIIObject *) key)->hash) == -1) {
    3191:         hash = PyObject_Hash(key);
    3192:         if (hash == -1)
    3193:             return -1;
    3194:     }
    3195:     ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
    3196:     if (ix == DKIX_ERROR)
    3197:         return -1;
    3198:     return (ix != DKIX_EMPTY && *value_addr != NULL);
    3199: }
    3200: 
    3201: /* Internal version of PyDict_Contains used when the hash value is already known */
    3202: int
    3203: _PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash)
    3204: {
    3205:     PyDictObject *mp = (PyDictObject *)op;
    3206:     PyObject **value_addr;
    3207:     Py_ssize_t ix;
    3208: 
    3209:     ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL);
    3210:     if (ix == DKIX_ERROR)
    3211:         return -1;
    3212:     return (ix != DKIX_EMPTY && *value_addr != NULL);
    3213: }
    3214: 
    3215: /* Hack to implement "key in dict" */
    3216: static PySequenceMethods dict_as_sequence = {
    3217:     0,                          /* sq_length */
    3218:     0,                          /* sq_concat */
    3219:     0,                          /* sq_repeat */
    3220:     0,                          /* sq_item */
    3221:     0,                          /* sq_slice */
    3222:     0,                          /* sq_ass_item */
    3223:     0,                          /* sq_ass_slice */
    3224:     PyDict_Contains,            /* sq_contains */
    3225:     0,                          /* sq_inplace_concat */
    3226:     0,                          /* sq_inplace_repeat */
    3227: };
    3228: 
    3229: static PyObject *
    3230: dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    3231: {
    3232:     PyObject *self;
    3233:     PyDictObject *d;
    3234: 
    3235:     assert(type != NULL && type->tp_alloc != NULL);
    3236:     self = type->tp_alloc(type, 0);
    3237:     if (self == NULL)
    3238:         return NULL;
    3239:     d = (PyDictObject *)self;
    3240: 
    3241:     /* The object has been implicitly tracked by tp_alloc */
    3242:     if (type == &PyDict_Type)
    3243:         _PyObject_GC_UNTRACK(d);
    3244: 
    3245:     d->ma_used = 0;
    3246:     d->ma_version_tag = DICT_NEXT_VERSION();
    3247:     d->ma_keys = new_keys_object(PyDict_MINSIZE);
    3248:     if (d->ma_keys == NULL) {
    3249:         Py_DECREF(self);
    3250:         return NULL;
    3251:     }
    3252:     assert(_PyDict_CheckConsistency(d));
    3253:     return self;
    3254: }
    3255: 
    3256: static int
    3257: dict_init(PyObject *self, PyObject *args, PyObject *kwds)
    3258: {
    3259:     return dict_update_common(self, args, kwds, "dict");
    3260: }
    3261: 
    3262: static PyObject *
    3263: dict_iter(PyDictObject *dict)
    3264: {
    3265:     return dictiter_new(dict, &PyDictIterKey_Type);
    3266: }
    3267: 
    3268: PyDoc_STRVAR(dictionary_doc,
    3269: "dict() -> new empty dictionary\n"
    3270: "dict(mapping) -> new dictionary initialized from a mapping object's\n"
    3271: "    (key, value) pairs\n"
    3272: "dict(iterable) -> new dictionary initialized as if via:\n"
    3273: "    d = {}\n"
    3274: "    for k, v in iterable:\n"
    3275: "        d[k] = v\n"
    3276: "dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
    3277: "    in the keyword argument list.  For example:  dict(one=1, two=2)");
    3278: 
    3279: PyTypeObject PyDict_Type = {
    3280:     PyVarObject_HEAD_INIT(&PyType_Type, 0)
    3281:     "dict",
    3282:     sizeof(PyDictObject),
    3283:     0,
    3284:     (destructor)dict_dealloc,                   /* tp_dealloc */
    3285:     0,                                          /* tp_print */
    3286:     0,                                          /* tp_getattr */
    3287:     0,                                          /* tp_setattr */
    3288:     0,                                          /* tp_reserved */
    3289:     (reprfunc)dict_repr,                        /* tp_repr */
    3290:     0,                                          /* tp_as_number */
    3291:     &dict_as_sequence,                          /* tp_as_sequence */
    3292:     &dict_as_mapping,                           /* tp_as_mapping */
    3293:     PyObject_HashNotImplemented,                /* tp_hash */
    3294:     0,                                          /* tp_call */
    3295:     0,                                          /* tp_str */
    3296:     PyObject_GenericGetAttr,                    /* tp_getattro */
    3297:     0,                                          /* tp_setattro */
    3298:     0,                                          /* tp_as_buffer */
    3299:     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
    3300:         Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS,         /* tp_flags */
    3301:     dictionary_doc,                             /* tp_doc */
    3302:     dict_traverse,                              /* tp_traverse */
    3303:     dict_tp_clear,                              /* tp_clear */
    3304:     dict_richcompare,                           /* tp_richcompare */
    3305:     0,                                          /* tp_weaklistoffset */
    3306:     (getiterfunc)dict_iter,                     /* tp_iter */
    3307:     0,                                          /* tp_iternext */
    3308:     mapp_methods,                               /* tp_methods */
    3309:     0,                                          /* tp_members */
    3310:     0,                                          /* tp_getset */
    3311:     0,                                          /* tp_base */
    3312:     0,                                          /* tp_dict */
    3313:     0,                                          /* tp_descr_get */
    3314:     0,                                          /* tp_descr_set */
    3315:     0,                                          /* tp_dictoffset */
    3316:     dict_init,                                  /* tp_init */
    3317:     PyType_GenericAlloc,                        /* tp_alloc */
    3318:     dict_new,                                   /* tp_new */
    3319:     PyObject_GC_Del,                            /* tp_free */
    3320: };
    3321: 
    3322: PyObject *
    3323: _PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key)
    3324: {
    3325:     PyObject *kv;
    3326:     kv = _PyUnicode_FromId(key); /* borrowed */
    3327:     if (kv == NULL) {
    3328:         PyErr_Clear();
    3329:         return NULL;
    3330:     }
    3331:     return PyDict_GetItem(dp, kv);
    3332: }
    3333: 
    3334: /* For backward compatibility with old dictionary interface */
    3335: 
    3336: PyObject *
    3337: PyDict_GetItemString(PyObject *v, const char *key)
    3338: {
    3339:     PyObject *kv, *rv;
    3340:     kv = PyUnicode_FromString(key);
    3341:     if (kv == NULL) {
    3342:         PyErr_Clear();
    3343:         return NULL;
    3344:     }
    3345:     rv = PyDict_GetItem(v, kv);
    3346:     Py_DECREF(kv);
    3347:     return rv;
    3348: }
    3349: 
    3350: int
    3351: _PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item)
    3352: {
    3353:     PyObject *kv;
    3354:     kv = _PyUnicode_FromId(key); /* borrowed */
    3355:     if (kv == NULL)
    3356:         return -1;
    3357:     return PyDict_SetItem(v, kv, item);
    3358: }
    3359: 
    3360: int
    3361: PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
    3362: {
    3363:     PyObject *kv;
    3364:     int err;
    3365:     kv = PyUnicode_FromString(key);
    3366:     if (kv == NULL)
    3367:         return -1;
    3368:     PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
    3369:     err = PyDict_SetItem(v, kv, item);
    3370:     Py_DECREF(kv);
    3371:     return err;
    3372: }
    3373: 
    3374: int
    3375: _PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
    3376: {
    3377:     PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
    3378:     if (kv == NULL)
    3379:         return -1;
    3380:     return PyDict_DelItem(v, kv);
    3381: }
    3382: 
    3383: int
    3384: PyDict_DelItemString(PyObject *v, const char *key)
    3385: {
    3386:     PyObject *kv;
    3387:     int err;
    3388:     kv = PyUnicode_FromString(key);
    3389:     if (kv == NULL)
    3390:         return -1;
    3391:     err = PyDict_DelItem(v, kv);
    3392:     Py_DECREF(kv);
    3393:     return err;
    3394: }
    3395: 
    3396: /* Dictionary iterator types */
    3397: 
    3398: typedef struct {
    3399:     PyObject_HEAD
    3400:     PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
    3401:     Py_ssize_t di_used;
    3402:     Py_ssize_t di_pos;
    3403:     PyObject* di_result; /* reusable result tuple for iteritems */
    3404:     Py_ssize_t len;
    3405: } dictiterobject;
    3406: 
    3407: static PyObject *
    3408: dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
    3409: {
    3410:     dictiterobject *di;
    3411:     di = PyObject_GC_New(dictiterobject, itertype);
    3412:     if (di == NULL)
    3413:         return NULL;
    3414:     Py_INCREF(dict);
    3415:     di->di_dict = dict;
    3416:     di->di_used = dict->ma_used;
    3417:     di->di_pos = 0;
    3418:     di->len = dict->ma_used;
    3419:     if (itertype == &PyDictIterItem_Type) {
    3420:         di->di_result = PyTuple_Pack(2, Py_None, Py_None);
    3421:         if (di->di_result == NULL) {
    3422:             Py_DECREF(di);
    3423:             return NULL;
    3424:         }
    3425:     }
    3426:     else
    3427:         di->di_result = NULL;
    3428:     _PyObject_GC_TRACK(di);
    3429:     return (PyObject *)di;
    3430: }
    3431: 
    3432: static void
    3433: dictiter_dealloc(dictiterobject *di)
    3434: {
    3435:     Py_XDECREF(di->di_dict);
    3436:     Py_XDECREF(di->di_result);
    3437:     PyObject_GC_Del(di);
    3438: }
    3439: 
    3440: static int
    3441: dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
    3442: {
    3443:     Py_VISIT(di->di_dict);
    3444:     Py_VISIT(di->di_result);
    3445:     return 0;
    3446: }
    3447: 
    3448: static PyObject *
    3449: dictiter_len(dictiterobject *di)
    3450: {
    3451:     Py_ssize_t len = 0;
    3452:     if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
    3453:         len = di->len;
    3454:     return PyLong_FromSize_t(len);
    3455: }
    3456: 
    3457: PyDoc_STRVAR(length_hint_doc,
    3458:              "Private method returning an estimate of len(list(it)).");
    3459: 
    3460: static PyObject *
    3461: dictiter_reduce(dictiterobject *di);
    3462: 
    3463: PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
    3464: 
    3465: static PyMethodDef dictiter_methods[] = {
    3466:     {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS,
    3467:      length_hint_doc},
    3468:      {"__reduce__", (PyCFunction)dictiter_reduce, METH_NOARGS,
    3469:      reduce_doc},
    3470:     {NULL,              NULL}           /* sentinel */
    3471: };
    3472: 
    3473: static PyObject*
    3474: dictiter_iternextkey(dictiterobject *di)
    3475: {
    3476:     PyObject *key;
    3477:     Py_ssize_t i, n;
    3478:     PyDictKeysObject *k;
    3479:     PyDictObject *d = di->di_dict;
    3480: 
    3481:     if (d == NULL)
    3482:         return NULL;
    3483:     assert (PyDict_Check(d));
    3484: 
    3485:     if (di->di_used != d->ma_used) {
    3486:         PyErr_SetString(PyExc_RuntimeError,
    3487:                         "dictionary changed size during iteration");
    3488:         di->di_used = -1; /* Make this state sticky */
    3489:         return NULL;
    3490:     }
    3491: 
    3492:     i = di->di_pos;
    3493:     k = d->ma_keys;
    3494:     n = k->dk_nentries;
    3495:     if (d->ma_values) {
    3496:         PyObject **value_ptr = &d->ma_values[i];
    3497:         while (i < n && *value_ptr == NULL) {
    3498:             value_ptr++;
    3499:             i++;
    3500:         }
    3501:         if (i >= n)
    3502:             goto fail;
    3503:         key = DK_ENTRIES(k)[i].me_key;
    3504:     }
    3505:     else {
    3506:         PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
    3507:         while (i < n && entry_ptr->me_value == NULL) {
    3508:             entry_ptr++;
    3509:             i++;
    3510:         }
    3511:         if (i >= n)
    3512:             goto fail;
    3513:         key = entry_ptr->me_key;
    3514:     }
    3515:     di->di_pos = i+1;
    3516:     di->len--;
    3517:     Py_INCREF(key);
    3518:     return key;
    3519: 
    3520: fail:
    3521:     di->di_dict = NULL;
    3522:     Py_DECREF(d);
    3523:     return NULL;
    3524: }
    3525: 
    3526: PyTypeObject PyDictIterKey_Type = {
    3527:     PyVarObject_HEAD_INIT(&PyType_Type, 0)
    3528:     "dict_keyiterator",                         /* tp_name */
    3529:     sizeof(dictiterobject),                     /* tp_basicsize */
    3530:     0,                                          /* tp_itemsize */
    3531:     /* methods */
    3532:     (destructor)dictiter_dealloc,               /* tp_dealloc */
    3533:     0,                                          /* tp_print */
    3534:     0,                                          /* tp_getattr */
    3535:     0,                                          /* tp_setattr */
    3536:     0,                                          /* tp_reserved */
    3537:     0,                                          /* tp_repr */
    3538:     0,                                          /* tp_as_number */
    3539:     0,                                          /* tp_as_sequence */
    3540:     0,                                          /* tp_as_mapping */
    3541:     0,                                          /* tp_hash */
    3542:     0,                                          /* tp_call */
    3543:     0,                                          /* tp_str */
    3544:     PyObject_GenericGetAttr,                    /* tp_getattro */
    3545:     0,                                          /* tp_setattro */
    3546:     0,                                          /* tp_as_buffer */
    3547:     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
    3548:     0,                                          /* tp_doc */
    3549:     (traverseproc)dictiter_traverse,            /* tp_traverse */
    3550:     0,                                          /* tp_clear */
    3551:     0,                                          /* tp_richcompare */
    3552:     0,                                          /* tp_weaklistoffset */
    3553:     PyObject_SelfIter,                          /* tp_iter */
    3554:     (iternextfunc)dictiter_iternextkey,         /* tp_iternext */
    3555:     dictiter_methods,                           /* tp_methods */
    3556:     0,
    3557: };
    3558: 
    3559: static PyObject *
    3560: dictiter_iternextvalue(dictiterobject *di)
    3561: {
    3562:     PyObject *value;
    3563:     Py_ssize_t i, n;
    3564:     PyDictObject *d = di->di_dict;
    3565: 
    3566:     if (d == NULL)
    3567:         return NULL;
    3568:     assert (PyDict_Check(d));
    3569: 
    3570:     if (di->di_used != d->ma_used) {
    3571:         PyErr_SetString(PyExc_RuntimeError,
    3572:                         "dictionary changed size during iteration");
    3573:         di->di_used = -1; /* Make this state sticky */
    3574:         return NULL;
    3575:     }
    3576: 
    3577:     i = di->di_pos;
    3578:     n = d->ma_keys->dk_nentries;
    3579:     if (d->ma_values) {
    3580:         PyObject **value_ptr = &d->ma_values[i];
    3581:         while (i < n && *value_ptr == NULL) {
    3582:             value_ptr++;
    3583:             i++;
    3584:         }
    3585:         if (i >= n)
    3586:             goto fail;
    3587:         value = *value_ptr;
    3588:     }
    3589:     else {
    3590:         PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
    3591:         while (i < n && entry_ptr->me_value == NULL) {
    3592:             entry_ptr++;
    3593:             i++;
    3594:         }
    3595:         if (i >= n)
    3596:             goto fail;
    3597:         value = entry_ptr->me_value;
    3598:     }
    3599:     di->di_pos = i+1;
    3600:     di->len--;
    3601:     Py_INCREF(value);
    3602:     return value;
    3603: 
    3604: fail:
    3605:     di->di_dict = NULL;
    3606:     Py_DECREF(d);
    3607:     return NULL;
    3608: }
    3609: 
    3610: PyTypeObject PyDictIterValue_Type = {
    3611:     PyVarObject_HEAD_INIT(&PyType_Type, 0)
    3612:     "dict_valueiterator",                       /* tp_name */
    3613:     sizeof(dictiterobject),                     /* tp_basicsize */
    3614:     0,                                          /* tp_itemsize */
    3615:     /* methods */
    3616:     (destructor)dictiter_dealloc,               /* tp_dealloc */
    3617:     0,                                          /* tp_print */
    3618:     0,                                          /* tp_getattr */
    3619:     0,                                          /* tp_setattr */
    3620:     0,                                          /* tp_reserved */
    3621:     0,                                          /* tp_repr */
    3622:     0,                                          /* tp_as_number */
    3623:     0,                                          /* tp_as_sequence */
    3624:     0,                                          /* tp_as_mapping */
    3625:     0,                                          /* tp_hash */
    3626:     0,                                          /* tp_call */
    3627:     0,                                          /* tp_str */
    3628:     PyObject_GenericGetAttr,                    /* tp_getattro */
    3629:     0,                                          /* tp_setattro */
    3630:     0,                                          /* tp_as_buffer */
    3631:     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
    3632:     0,                                          /* tp_doc */
    3633:     (traverseproc)dictiter_traverse,            /* tp_traverse */
    3634:     0,                                          /* tp_clear */
    3635:     0,                                          /* tp_richcompare */
    3636:     0,                                          /* tp_weaklistoffset */
    3637:     PyObject_SelfIter,                          /* tp_iter */
    3638:     (iternextfunc)dictiter_iternextvalue,       /* tp_iternext */
    3639:     dictiter_methods,                           /* tp_methods */
    3640:     0,
    3641: };
    3642: 
    3643: static PyObject *
    3644: dictiter_iternextitem(dictiterobject *di)
    3645: {
    3646:     PyObject *key, *value, *result;
    3647:     Py_ssize_t i, n;
    3648:     PyDictObject *d = di->di_dict;
    3649: 
    3650:     if (d == NULL)
    3651:         return NULL;
    3652:     assert (PyDict_Check(d));
    3653: 
    3654:     if (di->di_used != d->ma_used) {
    3655:         PyErr_SetString(PyExc_RuntimeError,
    3656:                         "dictionary changed size during iteration");
    3657:         di->di_used = -1; /* Make this state sticky */
    3658:         return NULL;
    3659:     }
    3660: 
    3661:     i = di->di_pos;
    3662:     n = d->ma_keys->dk_nentries;
    3663:     if (d->ma_values) {
    3664:         PyObject **value_ptr = &d->ma_values[i];
    3665:         while (i < n && *value_ptr == NULL) {
    3666:             value_ptr++;
    3667:             i++;
    3668:         }
    3669:         if (i >= n)
    3670:             goto fail;
    3671:         key = DK_ENTRIES(d->ma_keys)[i].me_key;
    3672:         value = *value_ptr;
    3673:     }
    3674:     else {
    3675:         PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
    3676:         while (i < n && entry_ptr->me_value == NULL) {
    3677:             entry_ptr++;
    3678:             i++;
    3679:         }
    3680:         if (i >= n)
    3681:             goto fail;
    3682:         key = entry_ptr->me_key;
    3683:         value = entry_ptr->me_value;
    3684:     }
    3685:     di->di_pos = i+1;
    3686:     di->len--;
    3687:     Py_INCREF(key);
    3688:     Py_INCREF(value);
    3689:     result = di->di_result;
    3690:     if (Py_REFCNT(result) == 1) {
    3691:         PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
    3692:         PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
    3693:         PyTuple_SET_ITEM(result, 0, key);  /* steals reference */
    3694:         PyTuple_SET_ITEM(result, 1, value);  /* steals reference */
    3695:         Py_INCREF(result);
    3696:         Py_DECREF(oldkey);
    3697:         Py_DECREF(oldvalue);
    3698:     }
    3699:     else {
    3700:         result = PyTuple_New(2);
    3701:         if (result == NULL)
    3702:             return NULL;
    3703:         PyTuple_SET_ITEM(result, 0, key);  /* steals reference */
    3704:         PyTuple_SET_ITEM(result, 1, value);  /* steals reference */
    3705:     }
    3706:     return result;
    3707: 
    3708: fail:
    3709:     di->di_dict = NULL;
    3710:     Py_DECREF(d);
    3711:     return NULL;
    3712: }
    3713: 
    3714: PyTypeObject PyDictIterItem_Type = {
    3715:     PyVarObject_HEAD_INIT(&PyType_Type, 0)
    3716:     "dict_itemiterator",                        /* tp_name */
    3717:     sizeof(dictiterobject),                     /* tp_basicsize */
    3718:     0,                                          /* tp_itemsize */
    3719:     /* methods */
    3720:     (destructor)dictiter_dealloc,               /* tp_dealloc */
    3721:     0,                                          /* tp_print */
    3722:     0,                                          /* tp_getattr */
    3723:     0,                                          /* tp_setattr */
    3724:     0,                                          /* tp_reserved */
    3725:     0,                                          /* tp_repr */
    3726:     0,                                          /* tp_as_number */
    3727:     0,                                          /* tp_as_sequence */
    3728:     0,                                          /* tp_as_mapping */
    3729:     0,                                          /* tp_hash */
    3730:     0,                                          /* tp_call */
    3731:     0,                                          /* tp_str */
    3732:     PyObject_GenericGetAttr,                    /* tp_getattro */
    3733:     0,                                          /* tp_setattro */
    3734:     0,                                          /* tp_as_buffer */
    3735:     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
    3736:     0,                                          /* tp_doc */
    3737:     (traverseproc)dictiter_traverse,            /* tp_traverse */
    3738:     0,                                          /* tp_clear */
    3739:     0,                                          /* tp_richcompare */
    3740:     0,                                          /* tp_weaklistoffset */
    3741:     PyObject_SelfIter,                          /* tp_iter */
    3742:     (iternextfunc)dictiter_iternextitem,        /* tp_iternext */
    3743:     dictiter_methods,                           /* tp_methods */
    3744:     0,
    3745: };
    3746: 
    3747: 
    3748: static PyObject *
    3749: dictiter_reduce(dictiterobject *di)
    3750: {
    3751:     PyObject *list;
    3752:     dictiterobject tmp;
    3753: 
    3754:     list = PyList_New(0);
    3755:     if (!list)
    3756:         return NULL;
    3757: 
    3758:     /* copy the itertor state */
    3759:     tmp = *di;
    3760:     Py_XINCREF(tmp.di_dict);
    3761: 
    3762:     /* iterate the temporary into a list */
    3763:     for(;;) {
    3764:         PyObject *element = 0;
    3765:         if (Py_TYPE(di) == &PyDictIterItem_Type)
    3766:             element = dictiter_iternextitem(&tmp);
    3767:         else if (Py_TYPE(di) == &PyDictIterKey_Type)
    3768:             element = dictiter_iternextkey(&tmp);
    3769:         else if (Py_TYPE(di) == &PyDictIterValue_Type)
    3770:             element = dictiter_iternextvalue(&tmp);
    3771:         else
    3772:             assert(0);
    3773:         if (element) {
    3774:             if (PyList_Append(list, element)) {
    3775:                 Py_DECREF(element);
    3776:                 Py_DECREF(list);
    3777:                 Py_XDECREF(tmp.di_dict);
    3778:                 return NULL;
    3779:             }
    3780:             Py_DECREF(element);
    3781:         } else
    3782:             break;
    3783:     }
    3784:     Py_XDECREF(tmp.di_dict);
    3785:     /* check for error */
    3786:     if (tmp.di_dict != NULL) {
    3787:         /* we have an error */
    3788:         Py_DECREF(list);
    3789:         return NULL;
    3790:     }
    3791:     return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
    3792: }
    3793: 
    3794: /***********************************************/
    3795: /* View objects for keys(), items(), values(). */
    3796: /***********************************************/
    3797: 
    3798: /* The instance lay-out is the same for all three; but the type differs. */
    3799: 
    3800: static void
    3801: dictview_dealloc(_PyDictViewObject *dv)
    3802: {
    3803:     Py_XDECREF(dv->dv_dict);
    3804:     PyObject_GC_Del(dv);
    3805: }
    3806: 
    3807: static int
    3808: dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
    3809: {
    3810:     Py_VISIT(dv->dv_dict);
    3811:     return 0;
    3812: }
    3813: 
    3814: static Py_ssize_t
    3815: dictview_len(_PyDictViewObject *dv)
    3816: {
    3817:     Py_ssize_t len = 0;
    3818:     if (dv->dv_dict != NULL)
    3819:         len = dv->dv_dict->ma_used;
    3820:     return len;
    3821: }
    3822: 
    3823: PyObject *
    3824: _PyDictView_New(PyObject *dict, PyTypeObject *type)
    3825: {
    3826:     _PyDictViewObject *dv;
    3827:     if (dict == NULL) {
    3828:         PyErr_BadInternalCall();
    3829:         return NULL;
    3830:     }
    3831:     if (!PyDict_Check(dict)) {
    3832:         /* XXX Get rid of this restriction later */
    3833:         PyErr_Format(PyExc_TypeError,
    3834:                      "%s() requires a dict argument, not '%s'",
    3835:                      type->tp_name, dict->ob_type->tp_name);
    3836:         return NULL;
    3837:     }
    3838:     dv = PyObject_GC_New(_PyDictViewObject, type);
    3839:     if (dv == NULL)
    3840:         return NULL;
    3841:     Py_INCREF(dict);
    3842:     dv->dv_dict = (PyDictObject *)dict;
    3843:     _PyObject_GC_TRACK(dv);
    3844:     return (PyObject *)dv;
    3845: }
    3846: 
    3847: /* TODO(guido): The views objects are not complete:
    3848: 
    3849:  * support more set operations
    3850:  * support arbitrary mappings?
    3851:    - either these should be static or exported in dictobject.h
    3852:    - if public then they should probably be in builtins
    3853: */
    3854: 
    3855: /* Return 1 if self is a subset of other, iterating over self;
    3856:    0 if not; -1 if an error occurred. */
    3857: static int
    3858: all_contained_in(PyObject *self, PyObject *other)
    3859: {
    3860:     PyObject *iter = PyObject_GetIter(self);
    3861:     int ok = 1;
    3862: 
    3863:     if (iter == NULL)
    3864:         return -1;
    3865:     for (;;) {
    3866:         PyObject *next = PyIter_Next(iter);
    3867:         if (next == NULL) {
    3868:             if (PyErr_Occurred())
    3869:                 ok = -1;
    3870:             break;
    3871:         }
    3872:         ok = PySequence_Contains(other, next);
    3873:         Py_DECREF(next);
    3874:         if (ok <= 0)
    3875:             break;
    3876:     }
    3877:     Py_DECREF(iter);
    3878:     return ok;
    3879: }
    3880: 
    3881: static PyObject *
    3882: dictview_richcompare(PyObject *self, PyObject *other, int op)
    3883: {
    3884:     Py_ssize_t len_self, len_other;
    3885:     int ok;
    3886:     PyObject *result;
    3887: 
    3888:     assert(self != NULL);
    3889:     assert(PyDictViewSet_Check(self));
    3890:     assert(other != NULL);
    3891: 
    3892:     if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
    3893:         Py_RETURN_NOTIMPLEMENTED;
    3894: 
    3895:     len_self = PyObject_Size(self);
    3896:     if (len_self < 0)
    3897:         return NULL;
    3898:     len_other = PyObject_Size(other);
    3899:     if (len_other < 0)
    3900:         return NULL;
    3901: 
    3902:     ok = 0;
    3903:     switch(op) {
    3904: 
    3905:     case Py_NE:
    3906:     case Py_EQ:
    3907:         if (len_self == len_other)
    3908:             ok = all_contained_in(self, other);
    3909:         if (op == Py_NE && ok >= 0)
    3910:             ok = !ok;
    3911:         break;
    3912: 
    3913:     case Py_LT:
    3914:         if (len_self < len_other)
    3915:             ok = all_contained_in(self, other);
    3916:         break;
    3917: 
    3918:       case Py_LE:
    3919:           if (len_self <= len_other)
    3920:               ok = all_contained_in(self, other);
    3921:           break;
    3922: 
    3923:     case Py_GT:
    3924:         if (len_self > len_other)
    3925:             ok = all_contained_in(other, self);
    3926:         break;
    3927: 
    3928:     case Py_GE:
    3929:         if (len_self >= len_other)
    3930:             ok = all_contained_in(other, self);
    3931:         break;
    3932: 
    3933:     }
    3934:     if (ok < 0)
    3935:         return NULL;
    3936:     result = ok ? Py_True : Py_False;
    3937:     Py_INCREF(result);
    3938:     return result;
    3939: }
    3940: 
    3941: static PyObject *
    3942: dictview_repr(_PyDictViewObject *dv)
    3943: {
    3944:     PyObject *seq;
    3945:     PyObject *result;
    3946: 
    3947:     seq = PySequence_List((PyObject *)dv);
    3948:     if (seq == NULL)
    3949:         return NULL;
    3950: 
    3951:     result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
    3952:     Py_DECREF(seq);
    3953:     return result;
    3954: }
    3955: 
    3956: /*** dict_keys ***/
    3957: 
    3958: static PyObject *
    3959: dictkeys_iter(_PyDictViewObject *dv)
    3960: {
    3961:     if (dv->dv_dict == NULL) {
    3962:         Py_RETURN_NONE;
    3963:     }
    3964:     return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
    3965: }
    3966: 
    3967: static int
    3968: dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
    3969: {
    3970:     if (dv->dv_dict == NULL)
    3971:         return 0;
    3972:     return PyDict_Contains((PyObject *)dv->dv_dict, obj);
    3973: }
    3974: 
    3975: static PySequenceMethods dictkeys_as_sequence = {
    3976:     (lenfunc)dictview_len,              /* sq_length */
    3977:     0,                                  /* sq_concat */
    3978:     0,                                  /* sq_repeat */
    3979:     0,                                  /* sq_item */
    3980:     0,                                  /* sq_slice */
    3981:     0,                                  /* sq_ass_item */
    3982:     0,                                  /* sq_ass_slice */
    3983:     (objobjproc)dictkeys_contains,      /* sq_contains */
    3984: };
    3985: 
    3986: static PyObject*
    3987: dictviews_sub(PyObject* self, PyObject *other)
    3988: {
    3989:     PyObject *result = PySet_New(self);
    3990:     PyObject *tmp;
    3991:     _Py_IDENTIFIER(difference_update);
    3992: 
    3993:     if (result == NULL)
    3994:         return NULL;
    3995: 
    3996:     tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_difference_update, other, NULL);
    3997:     if (tmp == NULL) {
    3998:         Py_DECREF(result);
    3999:         return NULL;
    4000:     }
    4001: 
    4002:     Py_DECREF(tmp);
    4003:     return result;
    4004: }
    4005: 
    4006: PyObject*
    4007: _PyDictView_Intersect(PyObject* self, PyObject *other)
    4008: {
    4009:     PyObject *result = PySet_New(self);
    4010:     PyObject *tmp;
    4011:     _Py_IDENTIFIER(intersection_update);
    4012: 
    4013:     if (result == NULL)
    4014:         return NULL;
    4015: 
    4016:     tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_intersection_update, other, NULL);
    4017:     if (tmp == NULL) {
    4018:         Py_DECREF(result);
    4019:         return NULL;
    4020:     }
    4021: 
    4022:     Py_DECREF(tmp);
    4023:     return result;
    4024: }
    4025: 
    4026: static PyObject*
    4027: dictviews_or(PyObject* self, PyObject *other)
    4028: {
    4029:     PyObject *result = PySet_New(self);
    4030:     PyObject *tmp;
    4031:     _Py_IDENTIFIER(update);
    4032: 
    4033:     if (result == NULL)
    4034:         return NULL;
    4035: 
    4036:     tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_update, other, NULL);
    4037:     if (tmp == NULL) {
    4038:         Py_DECREF(result);
    4039:         return NULL;
    4040:     }
    4041: 
    4042:     Py_DECREF(tmp);
    4043:     return result;
    4044: }
    4045: 
    4046: static PyObject*
    4047: dictviews_xor(PyObject* self, PyObject *other)
    4048: {
    4049:     PyObject *result = PySet_New(self);
    4050:     PyObject *tmp;
    4051:     _Py_IDENTIFIER(symmetric_difference_update);
    4052: 
    4053:     if (result == NULL)
    4054:         return NULL;
    4055: 
    4056:     tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_symmetric_difference_update, other, NULL);
    4057:     if (tmp == NULL) {
    4058:         Py_DECREF(result);
    4059:         return NULL;
    4060:     }
    4061: 
    4062:     Py_DECREF(tmp);
    4063:     return result;
    4064: }
    4065: 
    4066: static PyNumberMethods dictviews_as_number = {
    4067:     0,                                  /*nb_add*/
    4068:     (binaryfunc)dictviews_sub,          /*nb_subtract*/
    4069:     0,                                  /*nb_multiply*/
    4070:     0,                                  /*nb_remainder*/
    4071:     0,                                  /*nb_divmod*/
    4072:     0,                                  /*nb_power*/
    4073:     0,                                  /*nb_negative*/
    4074:     0,                                  /*nb_positive*/
    4075:     0,                                  /*nb_absolute*/
    4076:     0,                                  /*nb_bool*/
    4077:     0,                                  /*nb_invert*/
    4078:     0,                                  /*nb_lshift*/
    4079:     0,                                  /*nb_rshift*/
    4080:     (binaryfunc)_PyDictView_Intersect,  /*nb_and*/
    4081:     (binaryfunc)dictviews_xor,          /*nb_xor*/
    4082:     (binaryfunc)dictviews_or,           /*nb_or*/
    4083: };
    4084: 
    4085: static PyObject*
    4086: dictviews_isdisjoint(PyObject *self, PyObject *other)
    4087: {
    4088:     PyObject *it;
    4089:     PyObject *item = NULL;
    4090: 
    4091:     if (self == other) {
    4092:         if (dictview_len((_PyDictViewObject *)self) == 0)
    4093:             Py_RETURN_TRUE;
    4094:         else
    4095:             Py_RETURN_FALSE;
    4096:     }
    4097: 
    4098:     /* Iterate over the shorter object (only if other is a set,
    4099:      * because PySequence_Contains may be expensive otherwise): */
    4100:     if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
    4101:         Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
    4102:         Py_ssize_t len_other = PyObject_Size(other);
    4103:         if (len_other == -1)
    4104:             return NULL;
    4105: 
    4106:         if ((len_other > len_self)) {
    4107:             PyObject *tmp = other;
    4108:             other = self;
    4109:             self = tmp;
    4110:         }
    4111:     }
    4112: 
    4113:     it = PyObject_GetIter(other);
    4114:     if (it == NULL)
    4115:         return NULL;
    4116: 
    4117:     while ((item = PyIter_Next(it)) != NULL) {
    4118:         int contains = PySequence_Contains(self, item);
    4119:         Py_DECREF(item);
    4120:         if (contains == -1) {
    4121:             Py_DECREF(it);
    4122:             return NULL;
    4123:         }
    4124: 
    4125:         if (contains) {
    4126:             Py_DECREF(it);
    4127:             Py_RETURN_FALSE;
    4128:         }
    4129:     }
    4130:     Py_DECREF(it);
    4131:     if (PyErr_Occurred())
    4132:         return NULL; /* PyIter_Next raised an exception. */
    4133:     Py_RETURN_TRUE;
    4134: }
    4135: 
    4136: PyDoc_STRVAR(isdisjoint_doc,
    4137: "Return True if the view and the given iterable have a null intersection.");
    4138: 
    4139: static PyMethodDef dictkeys_methods[] = {
    4140:     {"isdisjoint",      (PyCFunction)dictviews_isdisjoint,  METH_O,
    4141:      isdisjoint_doc},
    4142:     {NULL,              NULL}           /* sentinel */
    4143: };
    4144: 
    4145: PyTypeObject PyDictKeys_Type = {
    4146:     PyVarObject_HEAD_INIT(&PyType_Type, 0)
    4147:     "dict_keys",                                /* tp_name */
    4148:     sizeof(_PyDictViewObject),                  /* tp_basicsize */
    4149:     0,                                          /* tp_itemsize */
    4150:     /* methods */
    4151:     (destructor)dictview_dealloc,               /* tp_dealloc */
    4152:     0,                                          /* tp_print */
    4153:     0,                                          /* tp_getattr */
    4154:     0,                                          /* tp_setattr */
    4155:     0,                                          /* tp_reserved */
    4156:     (reprfunc)dictview_repr,                    /* tp_repr */
    4157:     &dictviews_as_number,                       /* tp_as_number */
    4158:     &dictkeys_as_sequence,                      /* tp_as_sequence */
    4159:     0,                                          /* tp_as_mapping */
    4160:     0,                                          /* tp_hash */
    4161:     0,                                          /* tp_call */
    4162:     0,                                          /* tp_str */
    4163:     PyObject_GenericGetAttr,                    /* tp_getattro */
    4164:     0,                                          /* tp_setattro */
    4165:     0,                                          /* tp_as_buffer */
    4166:     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
    4167:     0,                                          /* tp_doc */
    4168:     (traverseproc)dictview_traverse,            /* tp_traverse */
    4169:     0,                                          /* tp_clear */
    4170:     dictview_richcompare,                       /* tp_richcompare */
    4171:     0,                                          /* tp_weaklistoffset */
    4172:     (getiterfunc)dictkeys_iter,                 /* tp_iter */
    4173:     0,                                          /* tp_iternext */
    4174:     dictkeys_methods,                           /* tp_methods */
    4175:     0,
    4176: };
    4177: 
    4178: static PyObject *
    4179: dictkeys_new(PyObject *dict)
    4180: {
    4181:     return _PyDictView_New(dict, &PyDictKeys_Type);
    4182: }
    4183: 
    4184: /*** dict_items ***/
    4185: 
    4186: static PyObject *
    4187: dictitems_iter(_PyDictViewObject *dv)
    4188: {
    4189:     if (dv->dv_dict == NULL) {
    4190:         Py_RETURN_NONE;
    4191:     }
    4192:     return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
    4193: }
    4194: 
    4195: static int
    4196: dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
    4197: {
    4198:     int result;
    4199:     PyObject *key, *value, *found;
    4200:     if (dv->dv_dict == NULL)
    4201:         return 0;
    4202:     if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
    4203:         return 0;
    4204:     key = PyTuple_GET_ITEM(obj, 0);
    4205:     value = PyTuple_GET_ITEM(obj, 1);
    4206:     found = PyDict_GetItemWithError((PyObject *)dv->dv_dict, key);
    4207:     if (found == NULL) {
    4208:         if (PyErr_Occurred())
    4209:             return -1;
    4210:         return 0;
    4211:     }
    4212:     Py_INCREF(found);
    4213:     result = PyObject_RichCompareBool(value, found, Py_EQ);
    4214:     Py_DECREF(found);
    4215:     return result;
    4216: }
    4217: 
    4218: static PySequenceMethods dictitems_as_sequence = {
    4219:     (lenfunc)dictview_len,              /* sq_length */
    4220:     0,                                  /* sq_concat */
    4221:     0,                                  /* sq_repeat */
    4222:     0,                                  /* sq_item */
    4223:     0,                                  /* sq_slice */
    4224:     0,                                  /* sq_ass_item */
    4225:     0,                                  /* sq_ass_slice */
    4226:     (objobjproc)dictitems_contains,     /* sq_contains */
    4227: };
    4228: 
    4229: static PyMethodDef dictitems_methods[] = {
    4230:     {"isdisjoint",      (PyCFunction)dictviews_isdisjoint,  METH_O,
    4231:      isdisjoint_doc},
    4232:     {NULL,              NULL}           /* sentinel */
    4233: };
    4234: 
    4235: PyTypeObject PyDictItems_Type = {
    4236:     PyVarObject_HEAD_INIT(&PyType_Type, 0)
    4237:     "dict_items",                               /* tp_name */
    4238:     sizeof(_PyDictViewObject),                  /* tp_basicsize */
    4239:     0,                                          /* tp_itemsize */
    4240:     /* methods */
    4241:     (destructor)dictview_dealloc,               /* tp_dealloc */
    4242:     0,                                          /* tp_print */
    4243:     0,                                          /* tp_getattr */
    4244:     0,                                          /* tp_setattr */
    4245:     0,                                          /* tp_reserved */
    4246:     (reprfunc)dictview_repr,                    /* tp_repr */
    4247:     &dictviews_as_number,                       /* tp_as_number */
    4248:     &dictitems_as_sequence,                     /* tp_as_sequence */
    4249:     0,                                          /* tp_as_mapping */
    4250:     0,                                          /* tp_hash */
    4251:     0,                                          /* tp_call */
    4252:     0,                                          /* tp_str */
    4253:     PyObject_GenericGetAttr,                    /* tp_getattro */
    4254:     0,                                          /* tp_setattro */
    4255:     0,                                          /* tp_as_buffer */
    4256:     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
    4257:     0,                                          /* tp_doc */
    4258:     (traverseproc)dictview_traverse,            /* tp_traverse */
    4259:     0,                                          /* tp_clear */
    4260:     dictview_richcompare,                       /* tp_richcompare */
    4261:     0,                                          /* tp_weaklistoffset */
    4262:     (getiterfunc)dictitems_iter,                /* tp_iter */
    4263:     0,                                          /* tp_iternext */
    4264:     dictitems_methods,                          /* tp_methods */
    4265:     0,
    4266: };
    4267: 
    4268: static PyObject *
    4269: dictitems_new(PyObject *dict)
    4270: {
    4271:     return _PyDictView_New(dict, &PyDictItems_Type);
    4272: }
    4273: 
    4274: /*** dict_values ***/
    4275: 
    4276: static PyObject *
    4277: dictvalues_iter(_PyDictViewObject *dv)
    4278: {
    4279:     if (dv->dv_dict == NULL) {
    4280:         Py_RETURN_NONE;
    4281:     }
    4282:     return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
    4283: }
    4284: 
    4285: static PySequenceMethods dictvalues_as_sequence = {
    4286:     (lenfunc)dictview_len,              /* sq_length */
    4287:     0,                                  /* sq_concat */
    4288:     0,                                  /* sq_repeat */
    4289:     0,                                  /* sq_item */
    4290:     0,                                  /* sq_slice */
    4291:     0,                                  /* sq_ass_item */
    4292:     0,                                  /* sq_ass_slice */
    4293:     (objobjproc)0,                      /* sq_contains */
    4294: };
    4295: 
    4296: static PyMethodDef dictvalues_methods[] = {
    4297:     {NULL,              NULL}           /* sentinel */
    4298: };
    4299: 
    4300: PyTypeObject PyDictValues_Type = {
    4301:     PyVarObject_HEAD_INIT(&PyType_Type, 0)
    4302:     "dict_values",                              /* tp_name */
    4303:     sizeof(_PyDictViewObject),                  /* tp_basicsize */
    4304:     0,                                          /* tp_itemsize */
    4305:     /* methods */
    4306:     (destructor)dictview_dealloc,               /* tp_dealloc */
    4307:     0,                                          /* tp_print */
    4308:     0,                                          /* tp_getattr */
    4309:     0,                                          /* tp_setattr */
    4310:     0,                                          /* tp_reserved */
    4311:     (reprfunc)dictview_repr,                    /* tp_repr */
    4312:     0,                                          /* tp_as_number */
    4313:     &dictvalues_as_sequence,                    /* tp_as_sequence */
    4314:     0,                                          /* tp_as_mapping */
    4315:     0,                                          /* tp_hash */
    4316:     0,                                          /* tp_call */
    4317:     0,                                          /* tp_str */
    4318:     PyObject_GenericGetAttr,                    /* tp_getattro */
    4319:     0,                                          /* tp_setattro */
    4320:     0,                                          /* tp_as_buffer */
    4321:     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
    4322:     0,                                          /* tp_doc */
    4323:     (traverseproc)dictview_traverse,            /* tp_traverse */
    4324:     0,                                          /* tp_clear */
    4325:     0,                                          /* tp_richcompare */
    4326:     0,                                          /* tp_weaklistoffset */
    4327:     (getiterfunc)dictvalues_iter,               /* tp_iter */
    4328:     0,                                          /* tp_iternext */
    4329:     dictvalues_methods,                         /* tp_methods */
    4330:     0,
    4331: };
    4332: 
    4333: static PyObject *
    4334: dictvalues_new(PyObject *dict)
    4335: {
    4336:     return _PyDictView_New(dict, &PyDictValues_Type);
    4337: }
    4338: 
    4339: /* Returns NULL if cannot allocate a new PyDictKeysObject,
    4340:    but does not set an error */
    4341: PyDictKeysObject *
    4342: _PyDict_NewKeysForClass(void)
    4343: {
    4344:     PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE);
    4345:     if (keys == NULL)
    4346:         PyErr_Clear();
    4347:     else
    4348:         keys->dk_lookup = lookdict_split;
    4349:     return keys;
    4350: }
    4351: 
    4352: #define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
    4353: 
    4354: PyObject *
    4355: PyObject_GenericGetDict(PyObject *obj, void *context)
    4356: {
    4357:     PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
    4358:     if (dictptr == NULL) {
    4359:         PyErr_SetString(PyExc_AttributeError,
    4360:                         "This object has no __dict__");
    4361:         return NULL;
    4362:     }
    4363:     dict = *dictptr;
    4364:     if (dict == NULL) {
    4365:         PyTypeObject *tp = Py_TYPE(obj);
    4366:         if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
    4367:             DK_INCREF(CACHED_KEYS(tp));
    4368:             *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp));
    4369:         }
    4370:         else {
    4371:             *dictptr = dict = PyDict_New();
    4372:         }
    4373:     }
    4374:     Py_XINCREF(dict);
    4375:     return dict;
    4376: }
    4377: 
    4378: int
    4379: _PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
    4380:                       PyObject *key, PyObject *value)
    4381: {
    4382:     PyObject *dict;
    4383:     int res;
    4384:     PyDictKeysObject *cached;
    4385: 
    4386:     assert(dictptr != NULL);
    4387:     if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
    4388:         assert(dictptr != NULL);
    4389:         dict = *dictptr;
    4390:         if (dict == NULL) {
    4391:             DK_INCREF(cached);
    4392:             dict = new_dict_with_shared_keys(cached);
    4393:             if (dict == NULL)
    4394:                 return -1;
    4395:             *dictptr = dict;
    4396:         }
    4397:         if (value == NULL) {
    4398:             res = PyDict_DelItem(dict, key);
    4399:             // Since key sharing dict doesn't allow deletion, PyDict_DelItem()
    4400:             // always converts dict to combined form.
    4401:             if ((cached = CACHED_KEYS(tp)) != NULL) {
    4402:                 CACHED_KEYS(tp) = NULL;
    4403:                 DK_DECREF(cached);
    4404:             }
    4405:         }
    4406:         else {
    4407:             int was_shared = (cached == ((PyDictObject *)dict)->ma_keys);
    4408:             res = PyDict_SetItem(dict, key, value);
    4409:             if (was_shared &&
    4410:                     (cached = CACHED_KEYS(tp)) != NULL &&
    4411:                     cached != ((PyDictObject *)dict)->ma_keys) {
    4412:                 /* PyDict_SetItem() may call dictresize and convert split table
    4413:                  * into combined table.  In such case, convert it to split
    4414:                  * table again and update type's shared key only when this is
    4415:                  * the only dict sharing key with the type.
    4416:                  *
    4417:                  * This is to allow using shared key in class like this:
    4418:                  *
    4419:                  *     class C:
    4420:                  *         def __init__(self):
    4421:                  *             # one dict resize happens
    4422:                  *             self.a, self.b, self.c = 1, 2, 3
    4423:                  *             self.d, self.e, self.f = 4, 5, 6
    4424:                  *     a = C()
    4425:                  */
    4426:                 if (cached->dk_refcnt == 1) {
    4427:                     CACHED_KEYS(tp) = make_keys_shared(dict);
    4428:                 }
    4429:                 else {
    4430:                     CACHED_KEYS(tp) = NULL;
    4431:                 }
    4432:                 DK_DECREF(cached);
    4433:                 if (CACHED_KEYS(tp) == NULL && PyErr_Occurred())
    4434:                     return -1;
    4435:             }
    4436:         }
    4437:     } else {
    4438:         dict = *dictptr;
    4439:         if (dict == NULL) {
    4440:             dict = PyDict_New();
    4441:             if (dict == NULL)
    4442:                 return -1;
    4443:             *dictptr = dict;
    4444:         }
    4445:         if (value == NULL) {
    4446:             res = PyDict_DelItem(dict, key);
    4447:         } else {
    4448:             res = PyDict_SetItem(dict, key, value);
    4449:         }
    4450:     }
    4451:     return res;
    4452: }
    4453: 
    4454: void
    4455: _PyDictKeys_DecRef(PyDictKeysObject *keys)
    4456: {
    4457:     DK_DECREF(keys);
    4458: }
    4459: