dictobject.c 58.6 KB
Newer Older
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 7 8 9
   It covers typical dictionary use patterns, the parameters for
   tuning dictionaries, and several ideas for possible optimizations.
*/

10
#include "Python.h"
11

12 13
typedef PyDictEntry dictentry;
typedef PyDictObject dictobject;
14

15
/* Define this out if you don't want conversion statistics on exit. */
16 17
#undef SHOW_CONVERSION_COUNTS

18 19 20
/* See large comment block below.  This must be >= 1. */
#define PERTURB_SHIFT 5

21
/*
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
Major subtleties ahead:  Most hash schemes depend on having a "good" hash
function, in the sense of simulating randomness.  Python doesn't:  its most
important hash functions (for strings and ints) are very regular in common
cases:

>>> map(hash, (0, 1, 2, 3))
[0, 1, 2, 3]
>>> map(hash, ("namea", "nameb", "namec", "named"))
[-1658398457, -1658398460, -1658398459, -1658398462]
>>>

This isn't necessarily bad!  To the contrary, in a table of size 2**i, taking
the low-order i bits as the initial table index is extremely fast, and there
are no collisions at all for dicts indexed by a contiguous range of ints.
The same is approximately true when keys are "consecutive" strings.  So this
gives better-than-random behavior in common cases, and that's very desirable.

OTOH, when collisions occur, the tendency to fill contiguous slices of the
hash table makes a good collision resolution strategy crucial.  Taking only
the last i bits of the hash code is also vulnerable:  for example, consider
[i << 16 for i in range(20000)] as a set of keys.  Since ints are their own
hash codes, and this fits in a dict of size 2**15, the last 15 bits of every
hash code are all 0:  they *all* map to the same table index.

But catering to unusual cases should not slow the usual ones, so we just take
the last i bits anyway.  It's up to collision resolution to do the rest.  If
we *usually* find the key we're looking for on the first try (and, it turns
out, we usually do -- the table load factor is kept under 2/3, so the odds
are solidly in our favor), then it makes best sense to keep the initial index
computation dirt cheap.

The first half of collision resolution is to visit table indices via this
recurrence:

    j = ((5*j) + 1) mod 2**i

For any initial j in range(2**i), repeating that 2**i times generates each
int in range(2**i) exactly once (see any text on random-number generation for
proof).  By itself, this doesn't help much:  like linear probing (setting
j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
order.  This would be bad, except that's not the only thing we do, and it's
actually *good* in the common cases where hash keys are consecutive.  In an
example that's really too small to make this entirely clear, for a table of
size 2**3 the order of indices is:

    0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]

If two things come in at index 5, the first place we look after is index 2,
not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
Linear probing is deadly in this case because there the fixed probe order
is the *same* as the order consecutive keys are likely to arrive.  But it's
extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
and certain that consecutive hash codes do not.

The other half of the strategy is to get the other bits of the hash code
into play.  This is done by initializing a (unsigned) vrbl "perturb" to the
full hash code, and changing the recurrence to:

    j = (5*j) + 1 + perturb;
    perturb >>= PERTURB_SHIFT;
    use j % 2**i as the next table index;

Now the probe sequence depends (eventually) on every bit in the hash code,
and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
because it quickly magnifies small differences in the bits that didn't affect
the initial index.  Note that because perturb is unsigned, if the recurrence
is executed often enough perturb eventually becomes and remains 0.  At that
point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
that's certain to find an empty slot eventually (since it generates every int
in range(2**i), and we make sure there's always at least one empty slot).

Selecting a good value for PERTURB_SHIFT is a balancing act.  You want it
small so that the high bits of the hash code continue to affect the probe
sequence across iterations; but you want it large so that in really bad cases
the high-order hash bits have an effect on early iterations.  5 was "the
best" in minimizing total collisions across experiments Tim Peters ran (on
both normal and pathological cases), but 4 and 6 weren't significantly worse.

Historical:  Reimer Behrends contributed the idea of using a polynomial-based
approach, using repeated multiplication by x in GF(2**n) where an irreducible
polynomial for each table size was chosen such that x was a primitive root.
Christian Tismer later extended that to use division by x instead, as an
efficient way to get the high bits of the hash code into play.  This scheme
also gave excellent collision statistics, but was more expensive:  two
if-tests were required inside the loop; computing "the next" index took about
the same number of operations but without as much potential parallelism
(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
above, and then shifting perturb can be done while the table index is being
masked); and the dictobject struct required a member to hold the table's
polynomial.  In Tim's experiments the current scheme ran faster, produced
equally good collision statistics, needed less code & used less memory.
113 114 115 116 117 118 119 120 121 122

Theoretical Python 2.5 headache:  hash codes are only C "long", but
sizeof(Py_ssize_t) > sizeof(long) may be possible.  In that case, and if a
dict is genuinely huge, then only the slots directly reachable via indexing
by a C long can be the first slot in a probe sequence.  The probe sequence
will still eventually reach every slot in the table, but the collision rate
on initial probes may be much higher than this scheme was designed for.
Getting a hash code as fat as Py_ssize_t is the only real cure.  But in
practice, this probably won't make a lick of difference for many years (at
which point everyone will have terabytes of RAM on 64-bit boxes).
123
*/
124

125
/* Object used as dummy key to fill deleted entries */
Raymond Hettinger's avatar
Raymond Hettinger committed
126
static PyObject *dummy = NULL; /* Initialized by first call to newdictobject() */
127

128 129 130 131 132 133 134 135
#ifdef Py_REF_DEBUG
PyObject *
_PyDict_Dummy(void)
{
	return dummy;
}
#endif

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
/* forward declarations */
static dictentry *
lookdict_string(dictobject *mp, PyObject *key, long hash);

#ifdef SHOW_CONVERSION_COUNTS
static long created = 0L;
static long converted = 0L;

static void
show_counts(void)
{
	fprintf(stderr, "created %ld string dicts\n", created);
	fprintf(stderr, "converted %ld to normal dicts\n", converted);
	fprintf(stderr, "%.2f%% conversion rate\n", (100.0*converted)/created);
}
#endif
152

153 154 155 156 157 158 159 160 161 162
/* Initialization macros.
   There are two ways to create a dict:  PyDict_New() is the main C API
   function, and the tp_new slot maps to dict_new().  In the latter case we
   can save a little time over what PyDict_New does because it's guaranteed
   that the PyDictObject struct is already zeroed out.
   Everyone except dict_new() should use EMPTY_TO_MINSIZE (unless they have
   an excellent reason not to).
*/

#define INIT_NONZERO_DICT_SLOTS(mp) do {				\
163
	(mp)->ma_table = (mp)->ma_smalltable;				\
164 165 166 167 168
	(mp)->ma_mask = PyDict_MINSIZE - 1;				\
    } while(0)

#define EMPTY_TO_MINSIZE(mp) do {					\
	memset((mp)->ma_smalltable, 0, sizeof((mp)->ma_smalltable));	\
169
	(mp)->ma_used = (mp)->ma_fill = 0;				\
170
	INIT_NONZERO_DICT_SLOTS(mp);					\
171 172
    } while(0)

Raymond Hettinger's avatar
Raymond Hettinger committed
173 174 175 176 177
/* Dictionary reuse scheme to save calls to malloc, free, and memset */
#define MAXFREEDICTS 80
static PyDictObject *free_dicts[MAXFREEDICTS];
static int num_free_dicts = 0;

178
PyObject *
179
PyDict_New(void)
180
{
181
	register dictobject *mp;
182
	if (dummy == NULL) { /* Auto-initialize dummy */
183
		dummy = PyString_FromString("<dummy key>");
184 185
		if (dummy == NULL)
			return NULL;
186 187 188
#ifdef SHOW_CONVERSION_COUNTS
		Py_AtExit(show_counts);
#endif
189
	}
Raymond Hettinger's avatar
Raymond Hettinger committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
	if (num_free_dicts) {
		mp = free_dicts[--num_free_dicts];
		assert (mp != NULL);
		assert (mp->ob_type == &PyDict_Type);
		_Py_NewReference((PyObject *)mp);
		if (mp->ma_fill) {
			EMPTY_TO_MINSIZE(mp);
		}
		assert (mp->ma_used == 0);
		assert (mp->ma_table == mp->ma_smalltable);
		assert (mp->ma_mask == PyDict_MINSIZE - 1);
	} else {
		mp = PyObject_GC_New(dictobject, &PyDict_Type);
		if (mp == NULL)
			return NULL;
		EMPTY_TO_MINSIZE(mp);
	}
207 208 209 210
	mp->ma_lookup = lookdict_string;
#ifdef SHOW_CONVERSION_COUNTS
	++created;
#endif
Neil Schemenauer's avatar
Neil Schemenauer committed
211
	_PyObject_GC_TRACK(mp);
212
	return (PyObject *)mp;
213 214 215 216
}

/*
The basic lookup function used by all operations.
217
This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
218 219 220
Open addressing is preferred over chaining since the link overhead for
chaining would be substantial (100% with typical malloc overhead).

221 222
The initial probe index is computed as hash mod the table size. Subsequent
probe indices are computed as explained earlier.
223 224

All arithmetic on hash should ignore overflow.
225

226 227 228
(The details in this version are due to Tim Peters, building on many past
contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and
Christian Tismer).
229 230 231 232

This function must never return NULL; failures are indicated by returning
a dictentry* for which the me_value field is NULL.  Exceptions are never
reported by this function, and outstanding exceptions are maintained.
233
*/
234

235
static dictentry *
236
lookdict(dictobject *mp, PyObject *key, register long hash)
237
{
Martin v. Löwis's avatar
Martin v. Löwis committed
238 239
	register Py_ssize_t i;
	register size_t perturb;
240
	register dictentry *freeslot;
241
	register Py_ssize_t mask = mp->ma_mask;
242 243
	dictentry *ep0 = mp->ma_table;
	register dictentry *ep;
244 245
	register int restore_error;
	register int checked_error;
246 247
	register int cmp;
	PyObject *err_type, *err_value, *err_tb;
248
	PyObject *startkey;
249

250
	i = hash & mask;
Guido van Rossum's avatar
Guido van Rossum committed
251
	ep = &ep0[i];
252
	if (ep->me_key == NULL || ep->me_key == key)
253
		return ep;
254 255

	restore_error = checked_error = 0;
256
	if (ep->me_key == dummy)
257
		freeslot = ep;
258
	else {
259 260 261 262 263 264 265
		if (ep->me_hash == hash) {
			/* error can't have been checked yet */
			checked_error = 1;
			if (PyErr_Occurred()) {
				restore_error = 1;
				PyErr_Fetch(&err_type, &err_value, &err_tb);
			}
266 267
			startkey = ep->me_key;
			cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
268
			if (cmp < 0)
Guido van Rossum's avatar
Guido van Rossum committed
269
				PyErr_Clear();
270 271 272 273 274 275 276 277 278 279 280 281 282
			if (ep0 == mp->ma_table && ep->me_key == startkey) {
				if (cmp > 0)
					goto Done;
			}
			else {
				/* The compare did major nasty stuff to the
				 * dict:  start over.
				 * XXX A clever adversary could prevent this
				 * XXX from terminating.
 				 */
 				ep = lookdict(mp, key, hash);
 				goto Done;
 			}
283 284
		}
		freeslot = NULL;
Guido van Rossum's avatar
Guido van Rossum committed
285
	}
286

287 288
	/* In the loop, me_key == dummy is by far (factor of 100s) the
	   least likely outcome, so test for that last. */
289 290 291
	for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
		i = (i << 2) + i + perturb + 1;
		ep = &ep0[i & mask];
292
		if (ep->me_key == NULL) {
293 294 295
			if (freeslot != NULL)
				ep = freeslot;
			break;
296
		}
297 298 299
		if (ep->me_key == key)
			break;
		if (ep->me_hash == hash && ep->me_key != dummy) {
300 301 302 303 304 305 306 307
			if (!checked_error) {
				checked_error = 1;
				if (PyErr_Occurred()) {
					restore_error = 1;
					PyErr_Fetch(&err_type, &err_value,
						    &err_tb);
				}
			}
308 309
			startkey = ep->me_key;
			cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
310
			if (cmp < 0)
Guido van Rossum's avatar
Guido van Rossum committed
311
				PyErr_Clear();
312 313 314 315 316 317 318 319 320 321 322 323 324
			if (ep0 == mp->ma_table && ep->me_key == startkey) {
				if (cmp > 0)
					break;
			}
			else {
				/* The compare did major nasty stuff to the
				 * dict:  start over.
				 * XXX A clever adversary could prevent this
				 * XXX from terminating.
 				 */
 				ep = lookdict(mp, key, hash);
 				break;
 			}
325
		}
326 327
		else if (ep->me_key == dummy && freeslot == NULL)
			freeslot = ep;
328
	}
329 330 331 332 333

Done:
	if (restore_error)
		PyErr_Restore(err_type, err_value, err_tb);
	return ep;
334 335
}

336 337 338 339 340
/*
 * Hacked up version of lookdict which can assume keys are always strings;
 * this assumption allows testing for errors during PyObject_Compare() to
 * be dropped; string-string comparisons never raise exceptions.  This also
 * means we don't need to go through PyObject_Compare(); we can always use
341
 * _PyString_Eq directly.
342
 *
343 344
 * This is valuable because the general-case error handling in lookdict() is
 * expensive, and dicts with pure-string keys are very common.
345 346 347 348
 */
static dictentry *
lookdict_string(dictobject *mp, PyObject *key, register long hash)
{
Martin v. Löwis's avatar
Martin v. Löwis committed
349 350
	register Py_ssize_t i;
	register size_t perturb;
351
	register dictentry *freeslot;
352
	register Py_ssize_t mask = mp->ma_mask;
353 354 355
	dictentry *ep0 = mp->ma_table;
	register dictentry *ep;

356 357 358 359 360
	/* Make sure this function doesn't have to handle non-string keys,
	   including subclasses of str; e.g., one reason to subclass
	   strings is to override __eq__, and for speed we don't cater to
	   that here. */
	if (!PyString_CheckExact(key)) {
361 362 363 364 365 366
#ifdef SHOW_CONVERSION_COUNTS
		++converted;
#endif
		mp->ma_lookup = lookdict;
		return lookdict(mp, key, hash);
	}
367
	i = hash & mask;
368 369 370 371 372 373 374
	ep = &ep0[i];
	if (ep->me_key == NULL || ep->me_key == key)
		return ep;
	if (ep->me_key == dummy)
		freeslot = ep;
	else {
		if (ep->me_hash == hash
375
		    && _PyString_Eq(ep->me_key, key)) {
376 377 378 379
			return ep;
		}
		freeslot = NULL;
	}
380

381 382
	/* In the loop, me_key == dummy is by far (factor of 100s) the
	   least likely outcome, so test for that last. */
383 384 385
	for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
		i = (i << 2) + i + perturb + 1;
		ep = &ep0[i & mask];
386 387 388 389 390
		if (ep->me_key == NULL)
			return freeslot == NULL ? ep : freeslot;
		if (ep->me_key == key
		    || (ep->me_hash == hash
		        && ep->me_key != dummy
391
			&& _PyString_Eq(ep->me_key, key)))
392
			return ep;
393
		if (ep->me_key == dummy && freeslot == NULL)
394
			freeslot = ep;
395 396 397
	}
}

398 399 400 401 402 403
/*
Internal routine to insert a new item into the table.
Used both by the internal resize routine and by the public insert routine.
Eats a reference to key and one to value.
*/
static void
404
insertdict(register dictobject *mp, PyObject *key, long hash, PyObject *value)
405
{
406
	PyObject *old_value;
407
	register dictentry *ep;
408 409 410 411
	typedef PyDictEntry *(*lookupfunc)(PyDictObject *, PyObject *, long);

	assert(mp->ma_lookup != NULL);
	ep = mp->ma_lookup(mp, key, hash);
412
	if (ep->me_value != NULL) {
413 414
		old_value = ep->me_value;
		ep->me_value = value;
415 416
		Py_DECREF(old_value); /* which **CAN** re-enter */
		Py_DECREF(key);
417 418 419 420
	}
	else {
		if (ep->me_key == NULL)
			mp->ma_fill++;
421 422 423 424
		else {
			assert(ep->me_key == dummy);
			Py_DECREF(dummy);
		}
425
		ep->me_key = key;
426
		ep->me_hash = (Py_ssize_t)hash;
427
		ep->me_value = value;
428 429 430 431 432 433 434 435 436 437
		mp->ma_used++;
	}
}

/*
Restructure the table by allocating a new table and reinserting all
items again.  When entries have been deleted, the new table may
actually be smaller than the old one.
*/
static int
438
dictresize(dictobject *mp, Py_ssize_t minused)
439
{
440
	Py_ssize_t newsize;
441
	dictentry *oldtable, *newtable, *ep;
442
	Py_ssize_t i;
443
	int is_oldtable_malloced;
444
	dictentry small_copy[PyDict_MINSIZE];
Tim Peters's avatar
Tim Peters committed
445 446

	assert(minused >= 0);
447

448
	/* Find the smallest table size > minused. */
449
	for (newsize = PyDict_MINSIZE;
450 451 452 453
	     newsize <= minused && newsize > 0;
	     newsize <<= 1)
		;
	if (newsize <= 0) {
454
		PyErr_NoMemory();
455 456
		return -1;
	}
457 458 459 460 461 462

	/* Get space for a new table. */
	oldtable = mp->ma_table;
	assert(oldtable != NULL);
	is_oldtable_malloced = oldtable != mp->ma_smalltable;

463
	if (newsize == PyDict_MINSIZE) {
464
		/* A large table is shrinking, or we can't get any smaller. */
465
		newtable = mp->ma_smalltable;
466
		if (newtable == oldtable) {
467 468
			if (mp->ma_fill == mp->ma_used) {
				/* No dummies, so no point doing anything. */
469
				return 0;
470 471 472 473 474 475 476 477
			}
			/* We're not going to resize it, but rebuild the
			   table anyway to purge old dummy entries.
			   Subtle:  This is *necessary* if fill==size,
			   as lookdict needs at least one virgin slot to
			   terminate failing searches.  If fill < size, it's
			   merely desirable, as dummies slow searches. */
			assert(mp->ma_fill > mp->ma_used);
478 479 480
			memcpy(small_copy, oldtable, sizeof(small_copy));
			oldtable = small_copy;
		}
481 482 483 484 485 486 487 488
	}
	else {
		newtable = PyMem_NEW(dictentry, newsize);
		if (newtable == NULL) {
			PyErr_NoMemory();
			return -1;
		}
	}
489 490

	/* Make the dict empty, using the new table. */
491 492
	assert(newtable != oldtable);
	mp->ma_table = newtable;
493
	mp->ma_mask = newsize - 1;
494
	memset(newtable, 0, sizeof(dictentry) * newsize);
495
	mp->ma_used = 0;
496 497
	i = mp->ma_fill;
	mp->ma_fill = 0;
498

499 500
	/* Copy the data over; this is refcount-neutral for active entries;
	   dummy entries aren't copied over, of course */
501 502 503
	for (ep = oldtable; i > 0; ep++) {
		if (ep->me_value != NULL) {	/* active entry */
			--i;
504
			insertdict(mp, ep->me_key, ep->me_hash, ep->me_value);
505
		}
506
		else if (ep->me_key != NULL) {	/* dummy entry */
507
			--i;
508 509
			assert(ep->me_key == dummy);
			Py_DECREF(ep->me_key);
510
		}
511
		/* else key == value == NULL:  nothing to do */
512
	}
513

514
	if (is_oldtable_malloced)
515
		PyMem_DEL(oldtable);
516 517 518
	return 0;
}

519
PyObject *
520
PyDict_GetItem(PyObject *op, PyObject *key)
521 522
{
	long hash;
523
	dictobject *mp = (dictobject *)op;
524
	if (!PyDict_Check(op)) {
525 526
		return NULL;
	}
527
	if (!PyString_CheckExact(key) ||
528
	    (hash = ((PyStringObject *) key)->ob_shash) == -1)
529
	{
530
		hash = PyObject_Hash(key);
531 532
		if (hash == -1) {
			PyErr_Clear();
533
			return NULL;
534
		}
535
	}
536
	return (mp->ma_lookup)(mp, key, hash)->me_value;
537 538
}

539
/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
540 541 542 543
 * dictionary if it's merely replacing the value for an existing key.
 * This means that it's safe to loop over a dictionary with PyDict_Next()
 * and occasionally replace a value -- but you can't insert new keys or
 * remove them.
544
 */
545
int
546
PyDict_SetItem(register PyObject *op, PyObject *key, PyObject *value)
547
{
548
	register dictobject *mp;
549
	register long hash;
550
	register Py_ssize_t n_used;
551

552 553
	if (!PyDict_Check(op)) {
		PyErr_BadInternalCall();
554 555
		return -1;
	}
556
	mp = (dictobject *)op;
557
	if (PyString_CheckExact(key)) {
558 559 560
		hash = ((PyStringObject *)key)->ob_shash;
		if (hash == -1)
			hash = PyObject_Hash(key);
Guido van Rossum's avatar
Guido van Rossum committed
561
	}
562
	else {
563
		hash = PyObject_Hash(key);
Guido van Rossum's avatar
Guido van Rossum committed
564 565 566
		if (hash == -1)
			return -1;
	}
567
	assert(mp->ma_fill <= mp->ma_mask);  /* at least one empty slot */
568 569 570 571
	n_used = mp->ma_used;
	Py_INCREF(value);
	Py_INCREF(key);
	insertdict(mp, key, hash, value);
572 573 574
	/* If we added a key, we can safely resize.  Otherwise just return!
	 * If fill >= 2/3 size, adjust size.  Normally, this doubles or
	 * quaduples the size, but it's also possible for the dict to shrink
575
	 * (if ma_fill is much larger than ma_used, meaning a lot of dict
576
	 * keys have been * deleted).
577
	 *
578 579 580
	 * Quadrupling the size improves average dictionary sparseness
	 * (reducing collisions) at the cost of some memory and iteration
	 * speed (which loops over every possible entry).  It also halves
581
|	 * the number of expensive resize operations in a growing dictionary.
582 583
	 *
	 * Very large dictionaries (over 50K items) use doubling instead.
584
	 * This may help applications with severe memory constraints.
585
	 */
586 587
	if (!(mp->ma_used > n_used && mp->ma_fill*3 >= (mp->ma_mask+1)*2))
		return 0;
588
	return dictresize(mp, (mp->ma_used > 50000 ? 2 : 4) * mp->ma_used);
589 590 591
}

int
592
PyDict_DelItem(PyObject *op, PyObject *key)
593
{
594
	register dictobject *mp;
595
	register long hash;
596
	register dictentry *ep;
597
	PyObject *old_value, *old_key;
598

599 600
	if (!PyDict_Check(op)) {
		PyErr_BadInternalCall();
601 602
		return -1;
	}
603
	if (!PyString_CheckExact(key) ||
604
	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
605
		hash = PyObject_Hash(key);
606 607 608
		if (hash == -1)
			return -1;
	}
609
	mp = (dictobject *)op;
610
	ep = (mp->ma_lookup)(mp, key, hash);
611
	if (ep->me_value == NULL) {
612
		PyErr_SetObject(PyExc_KeyError, key);
613 614
		return -1;
	}
615
	old_key = ep->me_key;
616
	Py_INCREF(dummy);
617
	ep->me_key = dummy;
618
	old_value = ep->me_value;
619 620
	ep->me_value = NULL;
	mp->ma_used--;
621 622
	Py_DECREF(old_value);
	Py_DECREF(old_key);
623 624 625
	return 0;
}

Guido van Rossum's avatar
Guido van Rossum committed
626
void
627
PyDict_Clear(PyObject *op)
628
{
629
	dictobject *mp;
630 631
	dictentry *ep, *table;
	int table_is_malloced;
632
	Py_ssize_t fill;
633
	dictentry small_copy[PyDict_MINSIZE];
634
#ifdef Py_DEBUG
635
	Py_ssize_t i, n;
636 637
#endif

638
	if (!PyDict_Check(op))
Guido van Rossum's avatar
Guido van Rossum committed
639
		return;
640
	mp = (dictobject *)op;
641
#ifdef Py_DEBUG
642
	n = mp->ma_mask + 1;
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
	i = 0;
#endif

	table = mp->ma_table;
	assert(table != NULL);
	table_is_malloced = table != mp->ma_smalltable;

	/* This is delicate.  During the process of clearing the dict,
	 * decrefs can cause the dict to mutate.  To avoid fatal confusion
	 * (voice of experience), we have to make the dict empty before
	 * clearing the slots, and never refer to anything via mp->xxx while
	 * clearing.
	 */
	fill = mp->ma_fill;
	if (table_is_malloced)
658
		EMPTY_TO_MINSIZE(mp);
659 660 661 662 663 664 665 666

	else if (fill > 0) {
		/* It's a small table with something that needs to be cleared.
		 * Afraid the only safe way is to copy the dict entries into
		 * another small table first.
		 */
		memcpy(small_copy, table, sizeof(small_copy));
		table = small_copy;
667
		EMPTY_TO_MINSIZE(mp);
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
	}
	/* else it's a small table that's already empty */

	/* Now we can finally clear things.  If C had refcounts, we could
	 * assert that the refcount on table is 1 now, i.e. that this function
	 * has unique access to it, so decref side-effects can't alter it.
	 */
	for (ep = table; fill > 0; ++ep) {
#ifdef Py_DEBUG
		assert(i < n);
		++i;
#endif
		if (ep->me_key) {
			--fill;
			Py_DECREF(ep->me_key);
			Py_XDECREF(ep->me_value);
		}
#ifdef Py_DEBUG
		else
			assert(ep->me_value == NULL);
#endif
689
	}
690 691 692

	if (table_is_malloced)
		PyMem_DEL(table);
693 694
}

695 696 697
/*
 * Iterate over a dict.  Use like so:
 *
698
 *     Py_ssize_t i;
699 700
 *     PyObject *key, *value;
 *     i = 0;   # important!  i should not otherwise be changed by you
Neal Norwitz's avatar
Neal Norwitz committed
701
 *     while (PyDict_Next(yourdict, &i, &key, &value)) {
702 703 704 705
 *              Refer to borrowed references in key and value.
 *     }
 *
 * CAUTION:  In general, it isn't safe to use PyDict_Next in a loop that
706 707 708 709
 * mutates the dict.  One exception:  it is safe if the loop merely changes
 * the values associated with the keys (but doesn't insert new keys or
 * delete keys), via PyDict_SetItem().
 */
Guido van Rossum's avatar
Guido van Rossum committed
710
int
Martin v. Löwis's avatar
Martin v. Löwis committed
711
PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
712
{
Martin v. Löwis's avatar
Martin v. Löwis committed
713
	register Py_ssize_t i;
714
	register Py_ssize_t mask;
Raymond Hettinger's avatar
Raymond Hettinger committed
715 716
	register dictentry *ep;

717
	if (!PyDict_Check(op))
Guido van Rossum's avatar
Guido van Rossum committed
718 719 720 721
		return 0;
	i = *ppos;
	if (i < 0)
		return 0;
Raymond Hettinger's avatar
Raymond Hettinger committed
722 723 724
	ep = ((dictobject *)op)->ma_table;
	mask = ((dictobject *)op)->ma_mask;
	while (i <= mask && ep[i].me_value == NULL)
Guido van Rossum's avatar
Guido van Rossum committed
725 726
		i++;
	*ppos = i+1;
Raymond Hettinger's avatar
Raymond Hettinger committed
727
	if (i > mask)
Guido van Rossum's avatar
Guido van Rossum committed
728 729
		return 0;
	if (pkey)
Raymond Hettinger's avatar
Raymond Hettinger committed
730
		*pkey = ep[i].me_key;
Guido van Rossum's avatar
Guido van Rossum committed
731
	if (pvalue)
Raymond Hettinger's avatar
Raymond Hettinger committed
732
		*pvalue = ep[i].me_value;
Guido van Rossum's avatar
Guido van Rossum committed
733
	return 1;
734 735 736 737 738
}

/* Methods */

static void
739
dict_dealloc(register dictobject *mp)
740
{
741
	register dictentry *ep;
742
	Py_ssize_t fill = mp->ma_fill;
743
 	PyObject_GC_UnTrack(mp);
744
	Py_TRASHCAN_SAFE_BEGIN(mp)
745 746 747
	for (ep = mp->ma_table; fill > 0; ep++) {
		if (ep->me_key) {
			--fill;
748
			Py_DECREF(ep->me_key);
749
			Py_XDECREF(ep->me_value);
750
		}
751
	}
752
	if (mp->ma_table != mp->ma_smalltable)
753
		PyMem_DEL(mp->ma_table);
Raymond Hettinger's avatar
Raymond Hettinger committed
754 755
	if (num_free_dicts < MAXFREEDICTS && mp->ob_type == &PyDict_Type)
		free_dicts[num_free_dicts++] = mp;
756
	else
Raymond Hettinger's avatar
Raymond Hettinger committed
757
		mp->ob_type->tp_free((PyObject *)mp);
758
	Py_TRASHCAN_SAFE_END(mp)
759 760 761
}

static int
762
dict_print(register dictobject *mp, register FILE *fp, register int flags)
763
{
764 765
	register Py_ssize_t i;
	register Py_ssize_t any;
766

767
	i = (int)Py_ReprEnter((PyObject*)mp);
768 769 770 771 772 773 774
	if (i != 0) {
		if (i < 0)
			return i;
		fprintf(fp, "{...}");
		return 0;
	}

775 776
	fprintf(fp, "{");
	any = 0;
777
	for (i = 0; i <= mp->ma_mask; i++) {
778 779 780 781 782 783
		dictentry *ep = mp->ma_table + i;
		PyObject *pvalue = ep->me_value;
		if (pvalue != NULL) {
			/* Prevent PyObject_Repr from deleting value during
			   key format */
			Py_INCREF(pvalue);
784 785
			if (any++ > 0)
				fprintf(fp, ", ");
786
			if (PyObject_Print((PyObject *)ep->me_key, fp, 0)!=0) {
787
				Py_DECREF(pvalue);
788
				Py_ReprLeave((PyObject*)mp);
789
				return -1;
790
			}
791
			fprintf(fp, ": ");
792
			if (PyObject_Print(pvalue, fp, 0) != 0) {
793
				Py_DECREF(pvalue);
794
				Py_ReprLeave((PyObject*)mp);
795
				return -1;
796
			}
797
			Py_DECREF(pvalue);
798 799 800
		}
	}
	fprintf(fp, "}");
801
	Py_ReprLeave((PyObject*)mp);
802 803 804
	return 0;
}

805
static PyObject *
806
dict_repr(dictobject *mp)
807
{
Martin v. Löwis's avatar
Martin v. Löwis committed
808
	Py_ssize_t i;
809 810 811
	PyObject *s, *temp, *colon = NULL;
	PyObject *pieces = NULL, *result = NULL;
	PyObject *key, *value;
812

813
	i = Py_ReprEnter((PyObject *)mp);
814
	if (i != 0) {
815 816 817 818 819 820
		return i > 0 ? PyString_FromString("{...}") : NULL;
	}

	if (mp->ma_used == 0) {
		result = PyString_FromString("{}");
		goto Done;
821 822
	}

823 824 825 826
	pieces = PyList_New(0);
	if (pieces == NULL)
		goto Done;

827
	colon = PyString_FromString(": ");
828 829 830 831 832
	if (colon == NULL)
		goto Done;

	/* Do repr() on each key+value pair, and insert ": " between them.
	   Note that repr may mutate the dict. */
833 834
	i = 0;
	while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
835 836 837 838 839 840 841 842 843 844 845 846 847
		int status;
		/* Prevent repr from deleting value during key format. */
		Py_INCREF(value);
		s = PyObject_Repr(key);
		PyString_Concat(&s, colon);
		PyString_ConcatAndDel(&s, PyObject_Repr(value));
		Py_DECREF(value);
		if (s == NULL)
			goto Done;
		status = PyList_Append(pieces, s);
		Py_DECREF(s);  /* append created a new ref */
		if (status < 0)
			goto Done;
848
	}
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874

	/* Add "{}" decorations to the first and last items. */
	assert(PyList_GET_SIZE(pieces) > 0);
	s = PyString_FromString("{");
	if (s == NULL)
		goto Done;
	temp = PyList_GET_ITEM(pieces, 0);
	PyString_ConcatAndDel(&s, temp);
	PyList_SET_ITEM(pieces, 0, s);
	if (s == NULL)
		goto Done;

	s = PyString_FromString("}");
	if (s == NULL)
		goto Done;
	temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
	PyString_ConcatAndDel(&temp, s);
	PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
	if (temp == NULL)
		goto Done;

	/* Paste them all together with ", " between. */
	s = PyString_FromString(", ");
	if (s == NULL)
		goto Done;
	result = _PyString_Join(s, pieces);
875
	Py_DECREF(s);
876 877 878

Done:
	Py_XDECREF(pieces);
879
	Py_XDECREF(colon);
880 881
	Py_ReprLeave((PyObject *)mp);
	return result;
882 883
}

Martin v. Löwis's avatar
Martin v. Löwis committed
884
static Py_ssize_t
885
dict_length(dictobject *mp)
886 887 888 889
{
	return mp->ma_used;
}

890
static PyObject *
891
dict_subscript(dictobject *mp, register PyObject *key)
892
{
893
	PyObject *v;
894
	long hash;
895
	assert(mp->ma_table != NULL);
896
	if (!PyString_CheckExact(key) ||
897
	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
898
		hash = PyObject_Hash(key);
899 900 901
		if (hash == -1)
			return NULL;
	}
902
	v = (mp->ma_lookup)(mp, key, hash) -> me_value;
Guido van Rossum's avatar
Guido van Rossum committed
903 904 905
	if (v == NULL) {
		if (!PyDict_CheckExact(mp)) {
			/* Look up __missing__ method if we're a subclass. */
906
		    	PyObject *missing;
Guido van Rossum's avatar
Guido van Rossum committed
907 908
			static PyObject *missing_str = NULL;
			if (missing_str == NULL)
909
				missing_str =
Guido van Rossum's avatar
Guido van Rossum committed
910
				  PyString_InternFromString("__missing__");
911
			missing = _PyType_Lookup(mp->ob_type, missing_str);
Guido van Rossum's avatar
Guido van Rossum committed
912 913 914 915
			if (missing != NULL)
				return PyObject_CallFunctionObjArgs(missing,
					(PyObject *)mp, key, NULL);
		}
916
		PyErr_SetObject(PyExc_KeyError, key);
Guido van Rossum's avatar
Guido van Rossum committed
917 918
		return NULL;
	}
919
	else
920
		Py_INCREF(v);
921 922 923 924
	return v;
}

static int
925
dict_ass_sub(dictobject *mp, PyObject *v, PyObject *w)
926 927
{
	if (w == NULL)
928
		return PyDict_DelItem((PyObject *)mp, v);
929
	else
930
		return PyDict_SetItem((PyObject *)mp, v, w);
931 932
}

933
static PyMappingMethods dict_as_mapping = {
Martin v. Löwis's avatar
Martin v. Löwis committed
934
	(lenfunc)dict_length, /*mp_length*/
935 936
	(binaryfunc)dict_subscript, /*mp_subscript*/
	(objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
937 938
};

939
static PyObject *
940
dict_keys(register dictobject *mp)
941
{
942
	register PyObject *v;
943
	register Py_ssize_t i, j;
Raymond Hettinger's avatar
Raymond Hettinger committed
944
	dictentry *ep;
945
	Py_ssize_t mask, n;
946 947 948 949

  again:
	n = mp->ma_used;
	v = PyList_New(n);
950 951
	if (v == NULL)
		return NULL;
952 953 954 955 956 957 958
	if (n != mp->ma_used) {
		/* Durnit.  The allocations caused the dict to resize.
		 * Just start over, this shouldn't normally happen.
		 */
		Py_DECREF(v);
		goto again;
	}
Raymond Hettinger's avatar
Raymond Hettinger committed
959 960 961 962 963
	ep = mp->ma_table;
	mask = mp->ma_mask;
	for (i = 0, j = 0; i <= mask; i++) {
		if (ep[i].me_value != NULL) {
			PyObject *key = ep[i].me_key;
964
			Py_INCREF(key);
965
			PyList_SET_ITEM(v, j, key);
966 967 968
			j++;
		}
	}
Raymond Hettinger's avatar
Raymond Hettinger committed
969
	assert(j == n);
970 971 972
	return v;
}

973
static PyObject *
974
dict_values(register dictobject *mp)
Guido van Rossum's avatar
Guido van Rossum committed
975
{
976
	register PyObject *v;
977
	register Py_ssize_t i, j;
Raymond Hettinger's avatar
Raymond Hettinger committed
978
	dictentry *ep;
979
	Py_ssize_t mask, n;
980 981 982 983

  again:
	n = mp->ma_used;
	v = PyList_New(n);
Guido van Rossum's avatar
Guido van Rossum committed
984 985
	if (v == NULL)
		return NULL;
986 987 988 989 990 991 992
	if (n != mp->ma_used) {
		/* Durnit.  The allocations caused the dict to resize.
		 * Just start over, this shouldn't normally happen.
		 */
		Py_DECREF(v);
		goto again;
	}
Raymond Hettinger's avatar
Raymond Hettinger committed
993 994 995 996 997
	ep = mp->ma_table;
	mask = mp->ma_mask;
	for (i = 0, j = 0; i <= mask; i++) {
		if (ep[i].me_value != NULL) {
			PyObject *value = ep[i].me_value;
998
			Py_INCREF(value);
999
			PyList_SET_ITEM(v, j, value);
Guido van Rossum's avatar
Guido van Rossum committed
1000 1001 1002
			j++;
		}
	}
Raymond Hettinger's avatar
Raymond Hettinger committed
1003
	assert(j == n);
Guido van Rossum's avatar
Guido van Rossum committed
1004 1005 1006
	return v;
}

1007
static PyObject *
1008
dict_items(register dictobject *mp)
Guido van Rossum's avatar
Guido van Rossum committed
1009
{
1010
	register PyObject *v;
1011 1012
	register Py_ssize_t i, j, n;
	Py_ssize_t mask;
1013
	PyObject *item, *key, *value;
Raymond Hettinger's avatar
Raymond Hettinger committed
1014
	dictentry *ep;
1015 1016 1017 1018 1019 1020 1021 1022

	/* Preallocate the list of tuples, to avoid allocations during
	 * the loop over the items, which could trigger GC, which
	 * could resize the dict. :-(
	 */
  again:
	n = mp->ma_used;
	v = PyList_New(n);
Guido van Rossum's avatar
Guido van Rossum committed
1023 1024
	if (v == NULL)
		return NULL;
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
	for (i = 0; i < n; i++) {
		item = PyTuple_New(2);
		if (item == NULL) {
			Py_DECREF(v);
			return NULL;
		}
		PyList_SET_ITEM(v, i, item);
	}
	if (n != mp->ma_used) {
		/* Durnit.  The allocations caused the dict to resize.
		 * Just start over, this shouldn't normally happen.
		 */
		Py_DECREF(v);
		goto again;
	}
	/* Nothing we do below makes any function calls. */
Raymond Hettinger's avatar
Raymond Hettinger committed
1041 1042 1043
	ep = mp->ma_table;
	mask = mp->ma_mask;
	for (i = 0, j = 0; i <= mask; i++) {
1044
		if ((value=ep[i].me_value) != NULL) {
Raymond Hettinger's avatar
Raymond Hettinger committed
1045
			key = ep[i].me_key;
1046
			item = PyList_GET_ITEM(v, j);
1047
			Py_INCREF(key);
1048
			PyTuple_SET_ITEM(item, 0, key);
1049
			Py_INCREF(value);
1050
			PyTuple_SET_ITEM(item, 1, value);
Guido van Rossum's avatar
Guido van Rossum committed
1051 1052 1053
			j++;
		}
	}
1054
	assert(j == n);
Guido van Rossum's avatar
Guido van Rossum committed
1055 1056 1057
	return v;
}

1058
static PyObject *
1059
dict_fromkeys(PyObject *cls, PyObject *args)
1060 1061 1062 1063 1064 1065 1066 1067
{
	PyObject *seq;
	PyObject *value = Py_None;
	PyObject *it;	/* iter(seq) */
	PyObject *key;
	PyObject *d;
	int status;

1068
	if (!PyArg_UnpackTuple(args, "fromkeys", 1, 2, &seq, &value))
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
		return NULL;

	d = PyObject_CallObject(cls, NULL);
	if (d == NULL)
		return NULL;

	it = PyObject_GetIter(seq);
	if (it == NULL){
		Py_DECREF(d);
		return NULL;
	}

	for (;;) {
		key = PyIter_Next(it);
		if (key == NULL) {
			if (PyErr_Occurred())
				goto Fail;
			break;
		}
1088
		status = PyObject_SetItem(d, key, value);
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
		Py_DECREF(key);
		if (status < 0)
			goto Fail;
	}

	Py_DECREF(it);
	return d;

Fail:
	Py_DECREF(it);
	Py_DECREF(d);
	return NULL;
}

1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
static int
dict_update_common(PyObject *self, PyObject *args, PyObject *kwds, char *methname)
{
	PyObject *arg = NULL;
	int result = 0;

	if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
		result = -1;

	else if (arg != NULL) {
		if (PyObject_HasAttrString(arg, "keys"))
			result = PyDict_Merge(self, arg, 1);
		else
			result = PyDict_MergeFromSeq2(self, arg, 1);
	}
	if (result == 0 && kwds != NULL)
		result = PyDict_Merge(self, kwds, 1);
	return result;
}

1123
static PyObject *
1124
dict_update(PyObject *self, PyObject *args, PyObject *kwds)
1125
{
1126 1127 1128
	if (dict_update_common(self, args, kwds, "update") != -1)
		Py_RETURN_NONE;
	return NULL;
1129 1130
}

1131 1132
/* Update unconditionally replaces existing items.
   Merge has a 3rd argument 'override'; if set, it acts like Update,
1133 1134 1135 1136
   otherwise it leaves existing items unchanged.

   PyDict_{Update,Merge} update/merge from a mapping object.

1137
   PyDict_MergeFromSeq2 updates/merges from any iterable object
1138 1139 1140
   producing iterable objects of length 2.
*/

1141
int
1142 1143 1144
PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
{
	PyObject *it;	/* iter(seq2) */
1145
	Py_ssize_t i;	/* index into seq2 of current element */
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
	PyObject *item;	/* seq2[i] */
	PyObject *fast;	/* item as a 2-tuple or 2-list */

	assert(d != NULL);
	assert(PyDict_Check(d));
	assert(seq2 != NULL);

	it = PyObject_GetIter(seq2);
	if (it == NULL)
		return -1;

	for (i = 0; ; ++i) {
		PyObject *key, *value;
Martin v. Löwis's avatar
Martin v. Löwis committed
1159
		Py_ssize_t n;
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182

		fast = NULL;
		item = PyIter_Next(it);
		if (item == NULL) {
			if (PyErr_Occurred())
				goto Fail;
			break;
		}

		/* Convert item to sequence, and verify length 2. */
		fast = PySequence_Fast(item, "");
		if (fast == NULL) {
			if (PyErr_ExceptionMatches(PyExc_TypeError))
				PyErr_Format(PyExc_TypeError,
					"cannot convert dictionary update "
					"sequence element #%d to a sequence",
					i);
			goto Fail;
		}
		n = PySequence_Fast_GET_SIZE(fast);
		if (n != 2) {
			PyErr_Format(PyExc_ValueError,
				     "dictionary update sequence element #%d "
1183
				     "has length %zd; 2 is required",
Martin v. Löwis's avatar
Martin v. Löwis committed
1184
				     i, n);
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
			goto Fail;
		}

		/* Update/merge with this (key, value) pair. */
		key = PySequence_Fast_GET_ITEM(fast, 0);
		value = PySequence_Fast_GET_ITEM(fast, 1);
		if (override || PyDict_GetItem(d, key) == NULL) {
			int status = PyDict_SetItem(d, key, value);
			if (status < 0)
				goto Fail;
		}
		Py_DECREF(fast);
		Py_DECREF(item);
	}

	i = 0;
	goto Return;
Fail:
	Py_XDECREF(item);
	Py_XDECREF(fast);
	i = -1;
Return:
	Py_DECREF(it);
1208
	return (int)i;
1209 1210
}

1211 1212
int
PyDict_Update(PyObject *a, PyObject *b)
1213 1214 1215 1216 1217 1218
{
	return PyDict_Merge(a, b, 1);
}

int
PyDict_Merge(PyObject *a, PyObject *b, int override)
1219
{
1220
	register PyDictObject *mp, *other;
1221
	register Py_ssize_t i;
1222
	dictentry *entry;
1223

1224 1225 1226 1227 1228
	/* We accept for the argument either a concrete dictionary object,
	 * or an abstract "mapping" object.  For the former, we can do
	 * things quite efficiently.  For the latter, we only require that
	 * PyMapping_Keys() and PyObject_GetItem() be supported.
	 */
1229 1230 1231 1232 1233 1234 1235
	if (a == NULL || !PyDict_Check(a) || b == NULL) {
		PyErr_BadInternalCall();
		return -1;
	}
	mp = (dictobject*)a;
	if (PyDict_Check(b)) {
		other = (dictobject*)b;
1236 1237
		if (other == mp || other->ma_used == 0)
			/* a.update(a) or a.update({}); nothing to do */
1238
			return 0;
1239 1240 1241 1242 1243 1244
		if (mp->ma_used == 0)
			/* Since the target dict is empty, PyDict_GetItem()
			 * always returns NULL.  Setting override to 1
			 * skips the unnecessary test.
			 */
			override = 1;
1245 1246 1247 1248 1249
		/* Do one big resize at the start, rather than
		 * incrementally resizing as we insert new items.  Expect
		 * that there will be no (or few) overlapping keys.
		 */
		if ((mp->ma_fill + other->ma_used)*3 >= (mp->ma_mask+1)*2) {
1250
		   if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0)
1251
			   return -1;
1252 1253 1254
		}
		for (i = 0; i <= other->ma_mask; i++) {
			entry = &other->ma_table[i];
1255 1256 1257
			if (entry->me_value != NULL &&
			    (override ||
			     PyDict_GetItem(a, entry->me_key) == NULL)) {
1258 1259
				Py_INCREF(entry->me_key);
				Py_INCREF(entry->me_value);
1260 1261
				insertdict(mp, entry->me_key,
					   (long)entry->me_hash,
1262 1263 1264
					   entry->me_value);
			}
		}
1265
	}
1266 1267
	else {
		/* Do it the generic, slower way */
1268
		PyObject *keys = PyMapping_Keys(b);
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
		PyObject *iter;
		PyObject *key, *value;
		int status;

		if (keys == NULL)
			/* Docstring says this is equivalent to E.keys() so
			 * if E doesn't have a .keys() method we want
			 * AttributeError to percolate up.  Might as well
			 * do the same for any other error.
			 */
1279
			return -1;
1280 1281 1282 1283

		iter = PyObject_GetIter(keys);
		Py_DECREF(keys);
		if (iter == NULL)
1284
			return -1;
1285 1286

		for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
1287 1288 1289 1290
			if (!override && PyDict_GetItem(a, key) != NULL) {
				Py_DECREF(key);
				continue;
			}
1291
			value = PyObject_GetItem(b, key);
1292 1293 1294
			if (value == NULL) {
				Py_DECREF(iter);
				Py_DECREF(key);
1295
				return -1;
1296
			}
1297
			status = PyDict_SetItem(a, key, value);
1298 1299 1300 1301
			Py_DECREF(key);
			Py_DECREF(value);
			if (status < 0) {
				Py_DECREF(iter);
1302
				return -1;
1303
			}
1304
		}
1305 1306 1307
		Py_DECREF(iter);
		if (PyErr_Occurred())
			/* Iterator completed, via error */
1308
			return -1;
1309
	}
1310
	return 0;
1311 1312 1313
}

static PyObject *
1314
dict_copy(register dictobject *mp)
1315
{
1316 1317 1318 1319
	return PyDict_Copy((PyObject*)mp);
}

PyObject *
1320
PyDict_Copy(PyObject *o)
1321
{
1322
	PyObject *copy;
1323 1324 1325

	if (o == NULL || !PyDict_Check(o)) {
		PyErr_BadInternalCall();
1326
		return NULL;
1327
	}
1328
	copy = PyDict_New();
1329 1330
	if (copy == NULL)
		return NULL;
1331 1332 1333
	if (PyDict_Merge(copy, o, 1) == 0)
		return copy;
	Py_DECREF(copy);
1334
	return NULL;
1335 1336
}

Martin v. Löwis's avatar
Martin v. Löwis committed
1337
Py_ssize_t
1338
PyDict_Size(PyObject *mp)
1339
{
1340 1341
	if (mp == NULL || !PyDict_Check(mp)) {
		PyErr_BadInternalCall();
1342
		return -1;
1343
	}
1344
	return ((dictobject *)mp)->ma_used;
1345 1346
}

1347
PyObject *
1348
PyDict_Keys(PyObject *mp)
1349
{
1350 1351
	if (mp == NULL || !PyDict_Check(mp)) {
		PyErr_BadInternalCall();
1352 1353
		return NULL;
	}
1354
	return dict_keys((dictobject *)mp);
1355 1356
}

1357
PyObject *
1358
PyDict_Values(PyObject *mp)
Guido van Rossum's avatar
Guido van Rossum committed
1359
{
1360 1361
	if (mp == NULL || !PyDict_Check(mp)) {
		PyErr_BadInternalCall();
Guido van Rossum's avatar
Guido van Rossum committed
1362 1363
		return NULL;
	}
1364
	return dict_values((dictobject *)mp);
Guido van Rossum's avatar
Guido van Rossum committed
1365 1366
}

1367
PyObject *
1368
PyDict_Items(PyObject *mp)
Guido van Rossum's avatar
Guido van Rossum committed
1369
{
1370 1371
	if (mp == NULL || !PyDict_Check(mp)) {
		PyErr_BadInternalCall();
Guido van Rossum's avatar
Guido van Rossum committed
1372 1373
		return NULL;
	}
1374
	return dict_items((dictobject *)mp);
Guido van Rossum's avatar
Guido van Rossum committed
1375 1376
}

1377 1378
/* Subroutine which returns the smallest key in a for which b's value
   is different or absent.  The value is returned too, through the
1379 1380 1381 1382 1383
   pval argument.  Both are NULL if no key in a is found for which b's status
   differs.  The refcounts on (and only on) non-NULL *pval and function return
   values must be decremented by the caller (characterize() increments them
   to ensure that mutating comparison and PyDict_GetItem calls can't delete
   them before the caller is done looking at them). */
1384

1385
static PyObject *
1386
characterize(dictobject *a, dictobject *b, PyObject **pval)
1387
{
1388 1389
	PyObject *akey = NULL; /* smallest key in a s.t. a[akey] != b[akey] */
	PyObject *aval = NULL; /* a[akey] */
1390 1391
	Py_ssize_t i;
	int cmp;
1392

1393
	for (i = 0; i <= a->ma_mask; i++) {
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
		PyObject *thiskey, *thisaval, *thisbval;
		if (a->ma_table[i].me_value == NULL)
			continue;
		thiskey = a->ma_table[i].me_key;
		Py_INCREF(thiskey);  /* keep alive across compares */
		if (akey != NULL) {
			cmp = PyObject_RichCompareBool(akey, thiskey, Py_LT);
			if (cmp < 0) {
				Py_DECREF(thiskey);
				goto Fail;
Guido van Rossum's avatar
Guido van Rossum committed
1404
			}
1405
			if (cmp > 0 ||
1406
			    i > a->ma_mask ||
1407
			    a->ma_table[i].me_value == NULL)
1408
			{
1409 1410 1411 1412 1413
				/* Not the *smallest* a key; or maybe it is
				 * but the compare shrunk the dict so we can't
				 * find its associated value anymore; or
				 * maybe it is but the compare deleted the
				 * a[thiskey] entry.
1414
|				 */
1415 1416
				Py_DECREF(thiskey);
				continue;
1417 1418
			}
		}
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447

		/* Compare a[thiskey] to b[thiskey]; cmp <- true iff equal. */
		thisaval = a->ma_table[i].me_value;
		assert(thisaval);
		Py_INCREF(thisaval);   /* keep alive */
		thisbval = PyDict_GetItem((PyObject *)b, thiskey);
		if (thisbval == NULL)
			cmp = 0;
		else {
			/* both dicts have thiskey:  same values? */
			cmp = PyObject_RichCompareBool(
						thisaval, thisbval, Py_EQ);
			if (cmp < 0) {
		    		Py_DECREF(thiskey);
		    		Py_DECREF(thisaval);
		    		goto Fail;
			}
		}
		if (cmp == 0) {
			/* New winner. */
			Py_XDECREF(akey);
			Py_XDECREF(aval);
			akey = thiskey;
			aval = thisaval;
		}
		else {
			Py_DECREF(thiskey);
			Py_DECREF(thisaval);
		}
1448
	}
1449 1450 1451 1452 1453 1454 1455 1456
	*pval = aval;
	return akey;

Fail:
	Py_XDECREF(akey);
	Py_XDECREF(aval);
	*pval = NULL;
	return NULL;
1457 1458 1459
}

static int
1460
dict_compare(dictobject *a, dictobject *b)
1461
{
1462
	PyObject *adiff, *bdiff, *aval, *bval;
1463 1464 1465 1466 1467 1468 1469
	int res;

	/* Compare lengths first */
	if (a->ma_used < b->ma_used)
		return -1;	/* a is shorter */
	else if (a->ma_used > b->ma_used)
		return 1;	/* b is shorter */
1470

1471
	/* Same length -- check all keys */
1472
	bdiff = bval = NULL;
1473
	adiff = characterize(a, b, &aval);
1474 1475
	if (adiff == NULL) {
		assert(!aval);
Tim Peters's avatar
Tim Peters committed
1476
		/* Either an error, or a is a subset with the same length so
1477 1478 1479 1480 1481
		 * must be equal.
		 */
		res = PyErr_Occurred() ? -1 : 0;
		goto Finished;
	}
1482
	bdiff = characterize(b, a, &bval);
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
	if (bdiff == NULL && PyErr_Occurred()) {
		assert(!bval);
		res = -1;
		goto Finished;
	}
	res = 0;
	if (bdiff) {
		/* bdiff == NULL "should be" impossible now, but perhaps
		 * the last comparison done by the characterize() on a had
		 * the side effect of making the dicts equal!
		 */
		res = PyObject_Compare(adiff, bdiff);
	}
	if (res == 0 && bval != NULL)
1497
		res = PyObject_Compare(aval, bval);
1498 1499 1500 1501 1502 1503

Finished:
	Py_XDECREF(adiff);
	Py_XDECREF(bdiff);
	Py_XDECREF(aval);
	Py_XDECREF(bval);
1504 1505 1506
	return res;
}

1507 1508 1509 1510 1511 1512 1513
/* Return 1 if dicts equal, 0 if not, -1 if error.
 * Gets out as soon as any difference is detected.
 * Uses only Py_EQ comparison.
 */
static int
dict_equal(dictobject *a, dictobject *b)
{
1514
	Py_ssize_t i;
1515 1516 1517 1518

	if (a->ma_used != b->ma_used)
		/* can't be equal if # of entries differ */
		return 0;
1519

1520
	/* Same # of entries -- check all of 'em.  Exit early on any diff. */
1521
	for (i = 0; i <= a->ma_mask; i++) {
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
		PyObject *aval = a->ma_table[i].me_value;
		if (aval != NULL) {
			int cmp;
			PyObject *bval;
			PyObject *key = a->ma_table[i].me_key;
			/* temporarily bump aval's refcount to ensure it stays
			   alive until we're done with it */
			Py_INCREF(aval);
			bval = PyDict_GetItem((PyObject *)b, key);
			if (bval == NULL) {
				Py_DECREF(aval);
				return 0;
			}
			cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
			Py_DECREF(aval);
			if (cmp <= 0)  /* error or not equal */
				return cmp;
 		}
	}
	return 1;
 }

static PyObject *
dict_richcompare(PyObject *v, PyObject *w, int op)
{
	int cmp;
	PyObject *res;

	if (!PyDict_Check(v) || !PyDict_Check(w)) {
		res = Py_NotImplemented;
	}
	else if (op == Py_EQ || op == Py_NE) {
		cmp = dict_equal((dictobject *)v, (dictobject *)w);
		if (cmp < 0)
			return NULL;
		res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
	}
1559 1560
	else
		res = Py_NotImplemented;
1561 1562 1563 1564
	Py_INCREF(res);
	return res;
 }

1565
static PyObject *
1566
dict_has_key(register dictobject *mp, PyObject *key)
1567 1568 1569
{
	long hash;
	register long ok;
1570
	if (!PyString_CheckExact(key) ||
1571
	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
1572
		hash = PyObject_Hash(key);
1573 1574 1575
		if (hash == -1)
			return NULL;
	}
1576
	ok = (mp->ma_lookup)(mp, key, hash)->me_value != NULL;
1577
	return PyBool_FromLong(ok);
1578 1579
}

1580
static PyObject *
1581
dict_get(register dictobject *mp, PyObject *args)
1582 1583
{
	PyObject *key;
1584
	PyObject *failobj = Py_None;
1585 1586 1587
	PyObject *val = NULL;
	long hash;

1588
	if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
1589 1590
		return NULL;

1591
	if (!PyString_CheckExact(key) ||
1592
	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
1593 1594 1595 1596
		hash = PyObject_Hash(key);
		if (hash == -1)
			return NULL;
	}
1597
	val = (mp->ma_lookup)(mp, key, hash)->me_value;
1598

1599 1600 1601 1602 1603 1604 1605
	if (val == NULL)
		val = failobj;
	Py_INCREF(val);
	return val;
}


1606 1607 1608 1609 1610 1611 1612 1613
static PyObject *
dict_setdefault(register dictobject *mp, PyObject *args)
{
	PyObject *key;
	PyObject *failobj = Py_None;
	PyObject *val = NULL;
	long hash;

1614
	if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &failobj))
1615 1616
		return NULL;

1617
	if (!PyString_CheckExact(key) ||
1618
	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
1619 1620 1621 1622
		hash = PyObject_Hash(key);
		if (hash == -1)
			return NULL;
	}
1623
	val = (mp->ma_lookup)(mp, key, hash)->me_value;
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
	if (val == NULL) {
		val = failobj;
		if (PyDict_SetItem((PyObject*)mp, key, failobj))
			val = NULL;
	}
	Py_XINCREF(val);
	return val;
}


1634
static PyObject *
1635
dict_clear(register dictobject *mp)
1636
{
1637
	PyDict_Clear((PyObject *)mp);
1638
	Py_RETURN_NONE;
1639 1640
}

1641
static PyObject *
1642
dict_pop(dictobject *mp, PyObject *args)
1643 1644 1645 1646
{
	long hash;
	dictentry *ep;
	PyObject *old_value, *old_key;
1647
	PyObject *key, *deflt = NULL;
1648

1649 1650
	if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
		return NULL;
1651
	if (mp->ma_used == 0) {
1652 1653 1654 1655
		if (deflt) {
			Py_INCREF(deflt);
			return deflt;
		}
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
		PyErr_SetString(PyExc_KeyError,
				"pop(): dictionary is empty");
		return NULL;
	}
	if (!PyString_CheckExact(key) ||
	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
		hash = PyObject_Hash(key);
		if (hash == -1)
			return NULL;
	}
	ep = (mp->ma_lookup)(mp, key, hash);
	if (ep->me_value == NULL) {
1668 1669 1670 1671
		if (deflt) {
			Py_INCREF(deflt);
			return deflt;
		}
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
		PyErr_SetObject(PyExc_KeyError, key);
		return NULL;
	}
	old_key = ep->me_key;
	Py_INCREF(dummy);
	ep->me_key = dummy;
	old_value = ep->me_value;
	ep->me_value = NULL;
	mp->ma_used--;
	Py_DECREF(old_key);
	return old_value;
}

1685
static PyObject *
1686
dict_popitem(dictobject *mp)
1687
{
1688
	Py_ssize_t i = 0;
1689 1690 1691
	dictentry *ep;
	PyObject *res;

1692 1693 1694 1695 1696 1697
	/* Allocate the result tuple before checking the size.  Believe it
	 * or not, this allocation could trigger a garbage collection which
	 * could empty the dict, so if we checked the size first and that
	 * happened, the result would be an infinite loop (searching for an
	 * entry that no longer exists).  Note that the usual popitem()
	 * idiom is "while d: k, v = d.popitem()". so needing to throw the
1698
	 * tuple away if the dict *is* empty isn't a significant
1699
	 * inefficiency -- possible, but unlikely in practice.
1700 1701 1702 1703
	 */
	res = PyTuple_New(2);
	if (res == NULL)
		return NULL;
1704 1705 1706 1707 1708 1709
	if (mp->ma_used == 0) {
		Py_DECREF(res);
		PyErr_SetString(PyExc_KeyError,
				"popitem(): dictionary is empty");
		return NULL;
	}
1710 1711 1712 1713
	/* Set ep to "the first" dict entry with a value.  We abuse the hash
	 * field of slot 0 to hold a search finger:
	 * If slot 0 has a value, use slot 0.
	 * Else slot 0 is being used to hold a search finger,
1714
|	 * and we use its hash value as the first index to look.
1715 1716 1717
	 */
	ep = &mp->ma_table[0];
	if (ep->me_value == NULL) {
1718
		i = ep->me_hash;
1719 1720 1721 1722
		/* The hash field may be a real hash value, or it may be a
		 * legit search finger, or it may be a once-legit search
		 * finger that's out of bounds now because it wrapped around
		 * or the table shrunk -- simply make sure it's in bounds now.
1723
		 */
1724
		if (i > mp->ma_mask || i < 1)
1725 1726 1727
			i = 1;	/* skip slot 0 */
		while ((ep = &mp->ma_table[i])->me_value == NULL) {
			i++;
1728
			if (i > mp->ma_mask)
1729 1730 1731
				i = 1;
		}
	}
1732 1733 1734 1735 1736 1737 1738 1739
	PyTuple_SET_ITEM(res, 0, ep->me_key);
	PyTuple_SET_ITEM(res, 1, ep->me_value);
	Py_INCREF(dummy);
	ep->me_key = dummy;
	ep->me_value = NULL;
	mp->ma_used--;
	assert(mp->ma_table[0].me_value == NULL);
	mp->ma_table[0].me_hash = i + 1;  /* next place to start */
1740 1741 1742
	return res;
}

1743 1744 1745
static int
dict_traverse(PyObject *op, visitproc visit, void *arg)
{
Martin v. Löwis's avatar
Martin v. Löwis committed
1746
	Py_ssize_t i = 0;
1747 1748 1749 1750
	PyObject *pk;
	PyObject *pv;

	while (PyDict_Next(op, &i, &pk, &pv)) {
1751 1752
		Py_VISIT(pk);
		Py_VISIT(pv);
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
	}
	return 0;
}

static int
dict_tp_clear(PyObject *op)
{
	PyDict_Clear(op);
	return 0;
}

1764

1765 1766 1767 1768
extern PyTypeObject PyDictIterKey_Type; /* Forward */
extern PyTypeObject PyDictIterValue_Type; /* Forward */
extern PyTypeObject PyDictIterItem_Type; /* Forward */
static PyObject *dictiter_new(dictobject *, PyTypeObject *);
1769 1770

static PyObject *
1771
dict_iterkeys(dictobject *dict)
1772
{
1773
	return dictiter_new(dict, &PyDictIterKey_Type);
1774 1775 1776
}

static PyObject *
1777
dict_itervalues(dictobject *dict)
1778
{
1779
	return dictiter_new(dict, &PyDictIterValue_Type);
1780 1781 1782
}

static PyObject *
1783
dict_iteritems(dictobject *dict)
1784
{
1785
	return dictiter_new(dict, &PyDictIterItem_Type);
1786 1787 1788
}


1789
PyDoc_STRVAR(has_key__doc__,
1790
"D.has_key(k) -> True if D has a key k, else False");
1791

1792 1793 1794 1795 1796
PyDoc_STRVAR(contains__doc__,
"D.__contains__(k) -> True if D has a key k, else False");

PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");

1797
PyDoc_STRVAR(get__doc__,
1798
"D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.");
1799

1800
PyDoc_STRVAR(setdefault_doc__,
1801
"D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D");
1802

1803
PyDoc_STRVAR(pop__doc__,
1804 1805
"D.pop(k[,d]) -> v, remove specified key and return the corresponding value\n\
If key is not found, d is returned if given, otherwise KeyError is raised");
1806

1807
PyDoc_STRVAR(popitem__doc__,
1808
"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
1809
2-tuple; but raise KeyError if D is empty");
1810

1811 1812
PyDoc_STRVAR(keys__doc__,
"D.keys() -> list of D's keys");
1813

1814 1815
PyDoc_STRVAR(items__doc__,
"D.items() -> list of D's (key, value) pairs, as 2-tuples");
1816

1817 1818
PyDoc_STRVAR(values__doc__,
"D.values() -> list of D's values");
1819

1820
PyDoc_STRVAR(update__doc__,
1821 1822
"D.update(E, **F) -> None.  Update D from E and F: for k in E: D[k] = E[k]\n\
(if E has keys else: for (k, v) in E: D[k] = v) then: for k in F: D[k] = F[k]");
1823

1824 1825 1826 1827
PyDoc_STRVAR(fromkeys__doc__,
"dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.\n\
v defaults to None.");

1828 1829
PyDoc_STRVAR(clear__doc__,
"D.clear() -> None.  Remove all items from D.");
1830

1831 1832
PyDoc_STRVAR(copy__doc__,
"D.copy() -> a shallow copy of D");
1833

1834 1835
PyDoc_STRVAR(iterkeys__doc__,
"D.iterkeys() -> an iterator over the keys of D");
1836

1837 1838
PyDoc_STRVAR(itervalues__doc__,
"D.itervalues() -> an iterator over the values of D");
1839

1840 1841
PyDoc_STRVAR(iteritems__doc__,
"D.iteritems() -> an iterator over the (key, value) items of D");
1842

1843
static PyMethodDef mapp_methods[] = {
1844 1845
	{"__contains__",(PyCFunction)dict_has_key,      METH_O | METH_COEXIST,
	 contains__doc__},
1846
	{"__getitem__", (PyCFunction)dict_subscript,	METH_O | METH_COEXIST,
1847
	 getitem__doc__},
1848
	{"has_key",	(PyCFunction)dict_has_key,      METH_O,
1849 1850 1851 1852 1853
	 has_key__doc__},
	{"get",         (PyCFunction)dict_get,          METH_VARARGS,
	 get__doc__},
	{"setdefault",  (PyCFunction)dict_setdefault,   METH_VARARGS,
	 setdefault_doc__},
1854
	{"pop",         (PyCFunction)dict_pop,          METH_VARARGS,
1855
	 pop__doc__},
1856
	{"popitem",	(PyCFunction)dict_popitem,	METH_NOARGS,
1857
	 popitem__doc__},
1858
	{"keys",	(PyCFunction)dict_keys,		METH_NOARGS,
1859
	keys__doc__},
1860
	{"items",	(PyCFunction)dict_items,	METH_NOARGS,
1861
	 items__doc__},
1862
	{"values",	(PyCFunction)dict_values,	METH_NOARGS,
1863
	 values__doc__},
1864
	{"update",	(PyCFunction)dict_update,	METH_VARARGS | METH_KEYWORDS,
1865
	 update__doc__},
1866 1867
	{"fromkeys",	(PyCFunction)dict_fromkeys,	METH_VARARGS | METH_CLASS,
	 fromkeys__doc__},
1868
	{"clear",	(PyCFunction)dict_clear,	METH_NOARGS,
1869
	 clear__doc__},
1870
	{"copy",	(PyCFunction)dict_copy,		METH_NOARGS,
1871
	 copy__doc__},
1872
	{"iterkeys",	(PyCFunction)dict_iterkeys,	METH_NOARGS,
1873
	 iterkeys__doc__},
1874
	{"itervalues",	(PyCFunction)dict_itervalues,	METH_NOARGS,
1875
	 itervalues__doc__},
1876
	{"iteritems",	(PyCFunction)dict_iteritems,	METH_NOARGS,
1877
	 iteritems__doc__},
1878
	{NULL,		NULL}	/* sentinel */
1879 1880
};

1881 1882
int
PyDict_Contains(PyObject *op, PyObject *key)
1883 1884
{
	long hash;
1885
	dictobject *mp = (dictobject *)op;
1886

1887
	if (!PyString_CheckExact(key) ||
1888
	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
1889 1890 1891 1892
		hash = PyObject_Hash(key);
		if (hash == -1)
			return -1;
	}
1893
	return (mp->ma_lookup)(mp, key, hash)->me_value != NULL;
1894 1895 1896 1897
}

/* Hack to implement "key in dict" */
static PySequenceMethods dict_as_sequence = {
1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
	0,			/* sq_length */
	0,			/* sq_concat */
	0,			/* sq_repeat */
	0,			/* sq_item */
	0,			/* sq_slice */
	0,			/* sq_ass_item */
	0,			/* sq_ass_slice */
	PyDict_Contains,	/* sq_contains */
	0,			/* sq_inplace_concat */
	0,			/* sq_inplace_repeat */
1908 1909
};

1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
static PyObject *
dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
	PyObject *self;

	assert(type != NULL && type->tp_alloc != NULL);
	self = type->tp_alloc(type, 0);
	if (self != NULL) {
		PyDictObject *d = (PyDictObject *)self;
		/* It's guaranteed that tp->alloc zeroed out the struct. */
		assert(d->ma_table == NULL && d->ma_fill == 0 && d->ma_used == 0);
		INIT_NONZERO_DICT_SLOTS(d);
		d->ma_lookup = lookdict_string;
#ifdef SHOW_CONVERSION_COUNTS
		++created;
#endif
	}
	return self;
}

1930 1931 1932
static int
dict_init(PyObject *self, PyObject *args, PyObject *kwds)
{
1933
	return dict_update_common(self, args, kwds, "dict");
1934 1935
}

1936 1937 1938 1939 1940 1941 1942
static long
dict_nohash(PyObject *self)
{
	PyErr_SetString(PyExc_TypeError, "dict objects are unhashable");
	return -1;
}

1943 1944 1945
static PyObject *
dict_iter(dictobject *dict)
{
1946
	return dictiter_new(dict, &PyDictIterKey_Type);
1947
}
1948

1949
PyDoc_STRVAR(dictionary_doc,
1950 1951
"dict() -> new empty dictionary.\n"
"dict(mapping) -> new dictionary initialized from a mapping object's\n"
1952
"    (key, value) pairs.\n"
1953
"dict(seq) -> new dictionary initialized as if via:\n"
Tim Peters's avatar
Tim Peters committed
1954 1955
"    d = {}\n"
"    for k, v in seq:\n"
1956 1957 1958
"        d[k] = v\n"
"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
"    in the keyword argument list.  For example:  dict(one=1, two=2)");
1959

1960 1961
PyTypeObject PyDict_Type = {
	PyObject_HEAD_INIT(&PyType_Type)
1962
	0,
1963
	"dict",
Neil Schemenauer's avatar
Neil Schemenauer committed
1964
	sizeof(dictobject),
1965
	0,
Guido van Rossum's avatar
Guido van Rossum committed
1966 1967
	(destructor)dict_dealloc,		/* tp_dealloc */
	(printfunc)dict_print,			/* tp_print */
1968
	0,					/* tp_getattr */
Guido van Rossum's avatar
Guido van Rossum committed
1969
	0,					/* tp_setattr */
1970
	(cmpfunc)dict_compare,			/* tp_compare */
Guido van Rossum's avatar
Guido van Rossum committed
1971 1972
	(reprfunc)dict_repr,			/* tp_repr */
	0,					/* tp_as_number */
1973
	&dict_as_sequence,			/* tp_as_sequence */
Guido van Rossum's avatar
Guido van Rossum committed
1974
	&dict_as_mapping,			/* tp_as_mapping */
1975
	dict_nohash,				/* tp_hash */
Guido van Rossum's avatar
Guido van Rossum committed
1976 1977
	0,					/* tp_call */
	0,					/* tp_str */
1978
	PyObject_GenericGetAttr,		/* tp_getattro */
Guido van Rossum's avatar
Guido van Rossum committed
1979 1980
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
Neil Schemenauer's avatar
Neil Schemenauer committed
1981
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1982
		Py_TPFLAGS_BASETYPE,		/* tp_flags */
1983
	dictionary_doc,				/* tp_doc */
1984 1985
	dict_traverse,				/* tp_traverse */
	dict_tp_clear,				/* tp_clear */
1986
	dict_richcompare,			/* tp_richcompare */
1987
	0,					/* tp_weaklistoffset */
1988
	(getiterfunc)dict_iter,			/* tp_iter */
1989
	0,					/* tp_iternext */
1990 1991 1992 1993 1994 1995 1996 1997
	mapp_methods,				/* tp_methods */
	0,					/* tp_members */
	0,					/* tp_getset */
	0,					/* tp_base */
	0,					/* tp_dict */
	0,					/* tp_descr_get */
	0,					/* tp_descr_set */
	0,					/* tp_dictoffset */
1998
	dict_init,				/* tp_init */
1999 2000
	PyType_GenericAlloc,			/* tp_alloc */
	dict_new,				/* tp_new */
2001
	PyObject_GC_Del,        		/* tp_free */
2002 2003
};

2004 2005
/* For backward compatibility with old dictionary interface */

2006
PyObject *
2007
PyDict_GetItemString(PyObject *v, const char *key)
2008
{
2009 2010 2011 2012 2013 2014 2015
	PyObject *kv, *rv;
	kv = PyString_FromString(key);
	if (kv == NULL)
		return NULL;
	rv = PyDict_GetItem(v, kv);
	Py_DECREF(kv);
	return rv;
2016 2017 2018
}

int
2019
PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
2020
{
2021 2022 2023 2024
	PyObject *kv;
	int err;
	kv = PyString_FromString(key);
	if (kv == NULL)
2025
		return -1;
2026
	PyString_InternInPlace(&kv); /* XXX Should we really? */
2027 2028 2029
	err = PyDict_SetItem(v, kv, item);
	Py_DECREF(kv);
	return err;
2030 2031 2032
}

int
2033
PyDict_DelItemString(PyObject *v, const char *key)
2034
{
2035 2036 2037 2038
	PyObject *kv;
	int err;
	kv = PyString_FromString(key);
	if (kv == NULL)
2039
		return -1;
2040 2041 2042
	err = PyDict_DelItem(v, kv);
	Py_DECREF(kv);
	return err;
2043
}
2044

2045
/* Dictionary iterator types */
2046 2047 2048

typedef struct {
	PyObject_HEAD
2049
	dictobject *di_dict; /* Set to NULL when iterator is exhausted */
2050 2051
	Py_ssize_t di_used;
	Py_ssize_t di_pos;
2052
	PyObject* di_result; /* reusable result tuple for iteritems */
2053
	Py_ssize_t len;
2054 2055 2056
} dictiterobject;

static PyObject *
2057
dictiter_new(dictobject *dict, PyTypeObject *itertype)
2058 2059
{
	dictiterobject *di;
2060
	di = PyObject_New(dictiterobject, itertype);
2061 2062 2063 2064
	if (di == NULL)
		return NULL;
	Py_INCREF(dict);
	di->di_dict = dict;
2065
	di->di_used = dict->ma_used;
2066
	di->di_pos = 0;
2067
	di->len = dict->ma_used;
2068 2069 2070 2071 2072 2073 2074 2075 2076
	if (itertype == &PyDictIterItem_Type) {
		di->di_result = PyTuple_Pack(2, Py_None, Py_None);
		if (di->di_result == NULL) {
			Py_DECREF(di);
			return NULL;
		}
	}
	else
		di->di_result = NULL;
2077 2078 2079 2080 2081 2082
	return (PyObject *)di;
}

static void
dictiter_dealloc(dictiterobject *di)
{
2083
	Py_XDECREF(di->di_dict);
2084
	Py_XDECREF(di->di_result);
2085
	PyObject_Del(di);
2086 2087
}

2088
static PyObject *
2089 2090
dictiter_len(dictiterobject *di)
{
2091
	Py_ssize_t len = 0;
2092
	if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
2093
		len = di->len;
2094
	return PyInt_FromSize_t(len);
2095 2096
}

2097
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
2098 2099

static PyMethodDef dictiter_methods[] = {
2100
	{"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS, length_hint_doc},
2101
 	{NULL,		NULL}		/* sentinel */
2102 2103
};

2104
static PyObject *dictiter_iternextkey(dictiterobject *di)
2105
{
2106
	PyObject *key;
2107
	register Py_ssize_t i, mask;
2108 2109
	register dictentry *ep;
	dictobject *d = di->di_dict;
2110

2111
	if (d == NULL)
2112
		return NULL;
2113
	assert (PyDict_Check(d));
2114

2115
	if (di->di_used != d->ma_used) {
2116 2117
		PyErr_SetString(PyExc_RuntimeError,
				"dictionary changed size during iteration");
2118
		di->di_used = -1; /* Make this state sticky */
2119 2120
		return NULL;
	}
2121

2122 2123 2124 2125 2126 2127 2128 2129 2130 2131
	i = di->di_pos;
	if (i < 0)
		goto fail;
	ep = d->ma_table;
	mask = d->ma_mask;
	while (i <= mask && ep[i].me_value == NULL)
		i++;
	di->di_pos = i+1;
	if (i > mask)
		goto fail;
2132
	di->len--;
2133 2134 2135 2136 2137 2138
	key = ep[i].me_key;
	Py_INCREF(key);
	return key;

fail:
	Py_DECREF(d);
2139
	di->di_dict = NULL;
2140
	return NULL;
2141 2142
}

2143
PyTypeObject PyDictIterKey_Type = {
2144 2145
	PyObject_HEAD_INIT(&PyType_Type)
	0,					/* ob_size */
2146
	"dictionary-keyiterator",		/* tp_name */
2147 2148 2149 2150 2151
	sizeof(dictiterobject),			/* tp_basicsize */
	0,					/* tp_itemsize */
	/* methods */
	(destructor)dictiter_dealloc, 		/* tp_dealloc */
	0,					/* tp_print */
2152
	0,					/* tp_getattr */
2153 2154 2155 2156
	0,					/* tp_setattr */
	0,					/* tp_compare */
	0,					/* tp_repr */
	0,					/* tp_as_number */
2157
	0,					/* tp_as_sequence */
2158 2159 2160 2161
	0,					/* tp_as_mapping */
	0,					/* tp_hash */
	0,					/* tp_call */
	0,					/* tp_str */
2162
	PyObject_GenericGetAttr,		/* tp_getattro */
2163 2164 2165 2166 2167 2168 2169 2170
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
	Py_TPFLAGS_DEFAULT,			/* tp_flags */
 	0,					/* tp_doc */
 	0,					/* tp_traverse */
 	0,					/* tp_clear */
	0,					/* tp_richcompare */
	0,					/* tp_weaklistoffset */
2171
	PyObject_SelfIter,			/* tp_iter */
2172
	(iternextfunc)dictiter_iternextkey,	/* tp_iternext */
2173 2174
	dictiter_methods,			/* tp_methods */
	0,
2175 2176 2177 2178 2179
};

static PyObject *dictiter_iternextvalue(dictiterobject *di)
{
	PyObject *value;
2180
	register Py_ssize_t i, mask;
2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
	register dictentry *ep;
	dictobject *d = di->di_dict;

	if (d == NULL)
		return NULL;
	assert (PyDict_Check(d));

	if (di->di_used != d->ma_used) {
		PyErr_SetString(PyExc_RuntimeError,
				"dictionary changed size during iteration");
		di->di_used = -1; /* Make this state sticky */
		return NULL;
	}

	i = di->di_pos;
2196 2197
	mask = d->ma_mask;
	if (i < 0 || i > mask)
2198 2199
		goto fail;
	ep = d->ma_table;
2200
	while ((value=ep[i].me_value) == NULL) {
2201
		i++;
2202 2203 2204
		if (i > mask)
			goto fail;
	}
2205
	di->di_pos = i+1;
2206
	di->len--;
2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
	Py_INCREF(value);
	return value;

fail:
	Py_DECREF(d);
	di->di_dict = NULL;
	return NULL;
}

PyTypeObject PyDictIterValue_Type = {
	PyObject_HEAD_INIT(&PyType_Type)
	0,					/* ob_size */
	"dictionary-valueiterator",		/* tp_name */
	sizeof(dictiterobject),			/* tp_basicsize */
	0,					/* tp_itemsize */
	/* methods */
	(destructor)dictiter_dealloc, 		/* tp_dealloc */
	0,					/* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
	0,					/* tp_repr */
	0,					/* tp_as_number */
2230
	0,					/* tp_as_sequence */
2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245
	0,					/* tp_as_mapping */
	0,					/* tp_hash */
	0,					/* tp_call */
	0,					/* tp_str */
	PyObject_GenericGetAttr,		/* tp_getattro */
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
	Py_TPFLAGS_DEFAULT,			/* tp_flags */
 	0,					/* tp_doc */
 	0,					/* tp_traverse */
 	0,					/* tp_clear */
	0,					/* tp_richcompare */
	0,					/* tp_weaklistoffset */
	PyObject_SelfIter,			/* tp_iter */
	(iternextfunc)dictiter_iternextvalue,	/* tp_iternext */
2246 2247
	dictiter_methods,			/* tp_methods */
	0,
2248 2249 2250 2251 2252
};

static PyObject *dictiter_iternextitem(dictiterobject *di)
{
	PyObject *key, *value, *result = di->di_result;
2253
	register Py_ssize_t i, mask;
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284
	register dictentry *ep;
	dictobject *d = di->di_dict;

	if (d == NULL)
		return NULL;
	assert (PyDict_Check(d));

	if (di->di_used != d->ma_used) {
		PyErr_SetString(PyExc_RuntimeError,
				"dictionary changed size during iteration");
		di->di_used = -1; /* Make this state sticky */
		return NULL;
	}

	i = di->di_pos;
	if (i < 0)
		goto fail;
	ep = d->ma_table;
	mask = d->ma_mask;
	while (i <= mask && ep[i].me_value == NULL)
		i++;
	di->di_pos = i+1;
	if (i > mask)
		goto fail;

	if (result->ob_refcnt == 1) {
		Py_INCREF(result);
		Py_DECREF(PyTuple_GET_ITEM(result, 0));
		Py_DECREF(PyTuple_GET_ITEM(result, 1));
	} else {
		result = PyTuple_New(2);
2285
		if (result == NULL)
2286 2287
			return NULL;
	}
2288
	di->len--;
2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
	key = ep[i].me_key;
	value = ep[i].me_value;
	Py_INCREF(key);
	Py_INCREF(value);
	PyTuple_SET_ITEM(result, 0, key);
	PyTuple_SET_ITEM(result, 1, value);
	return result;

fail:
	Py_DECREF(d);
	di->di_dict = NULL;
	return NULL;
}

PyTypeObject PyDictIterItem_Type = {
	PyObject_HEAD_INIT(&PyType_Type)
	0,					/* ob_size */
	"dictionary-itemiterator",		/* tp_name */
	sizeof(dictiterobject),			/* tp_basicsize */
	0,					/* tp_itemsize */
	/* methods */
	(destructor)dictiter_dealloc, 		/* tp_dealloc */
	0,					/* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
	0,					/* tp_repr */
	0,					/* tp_as_number */
2317
	0,					/* tp_as_sequence */
2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
	0,					/* tp_as_mapping */
	0,					/* tp_hash */
	0,					/* tp_call */
	0,					/* tp_str */
	PyObject_GenericGetAttr,		/* tp_getattro */
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
	Py_TPFLAGS_DEFAULT,			/* tp_flags */
 	0,					/* tp_doc */
 	0,					/* tp_traverse */
 	0,					/* tp_clear */
	0,					/* tp_richcompare */
	0,					/* tp_weaklistoffset */
	PyObject_SelfIter,			/* tp_iter */
	(iternextfunc)dictiter_iternextitem,	/* tp_iternext */
2333 2334
	dictiter_methods,			/* tp_methods */
	0,
2335
};