~ubuntu-branches/ubuntu/maverick/python3.1/maverick

« back to all changes in this revision

Viewing changes to Objects/dictobject.c

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2009-03-23 00:01:27 UTC
  • Revision ID: james.westby@ubuntu.com-20090323000127-5fstfxju4ufrhthq
Tags: upstream-3.1~a1+20090322
ImportĀ upstreamĀ versionĀ 3.1~a1+20090322

Show diffs side-by-side

added added

removed removed

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