setobject.c 57.8 KB
Newer Older
1

2 3 4
/* set object implementation 
   Written and maintained by Raymond D. Hettinger <python@rcn.com>
   Derived from Lib/sets.py and Objects/dictobject.c.
5

6
   Copyright (c) 2003-2007 Python Software Foundation.
7
   All rights reserved.
8 9
*/

10
#include "Python.h"
11
#include "structmember.h"
12

13 14 15 16 17 18 19 20 21 22 23 24 25 26
/* Set a key error with the specified argument, wrapping it in a
 * tuple automatically so that tuple keys are not unpacked as the
 * exception arguments. */
static void
set_key_error(PyObject *arg)
{
	PyObject *tup;
	tup = PyTuple_Pack(1, arg);
	if (!tup)
		return; /* caller will expect error to be set anyway */
	PyErr_SetObject(PyExc_KeyError, tup);
	Py_DECREF(tup);
}

27 28 29 30
/* This must be >= 1. */
#define PERTURB_SHIFT 5

/* Object used as dummy key to fill deleted entries */
31
static PyObject *dummy = NULL; /* Initialized by first call to make_new_set() */
32

33 34 35 36 37 38 39 40
#ifdef Py_REF_DEBUG
PyObject *
_PySet_Dummy(void)
{
	return dummy;
}
#endif

41 42 43 44 45 46
#define INIT_NONZERO_SET_SLOTS(so) do {				\
	(so)->table = (so)->smalltable;				\
	(so)->mask = PySet_MINSIZE - 1;				\
	(so)->hash = -1;					\
    } while(0)

47 48 49
#define EMPTY_TO_MINSIZE(so) do {				\
	memset((so)->smalltable, 0, sizeof((so)->smalltable));	\
	(so)->used = (so)->fill = 0;				\
50
	INIT_NONZERO_SET_SLOTS(so);				\
51 52
    } while(0)

53
/* Reuse scheme to save calls to malloc, free, and memset */
54 55 56 57 58
#ifndef PySet_MAXFREELIST
#define PySet_MAXFREELIST 80
#endif
static PySetObject *free_list[PySet_MAXFREELIST];
static int numfree = 0;
59 60 61 62 63 64 65 66

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

The initial probe index is computed as hash mod the table size. Subsequent
67
probe indices are computed as explained in Objects/dictobject.c.
68 69 70

All arithmetic on hash should ignore overflow.

71 72
Unlike the dictionary implementation, the lookkey functions can return
NULL if the rich comparison returns an error.
73 74 75 76 77
*/

static setentry *
set_lookkey(PySetObject *so, PyObject *key, register long hash)
{
Martin v. Löwis's avatar
Martin v. Löwis committed
78 79
	register Py_ssize_t i;
	register size_t perturb;
80
	register setentry *freeslot;
Neal Norwitz's avatar
Neal Norwitz committed
81
	register size_t mask = so->mask;
82
	setentry *table = so->table;
Raymond Hettinger's avatar
Raymond Hettinger committed
83
	register setentry *entry;
84 85 86 87
	register int cmp;
	PyObject *startkey;

	i = hash & mask;
88
	entry = &table[i];
Raymond Hettinger's avatar
Raymond Hettinger committed
89 90
	if (entry->key == NULL || entry->key == key)
		return entry;
91

Raymond Hettinger's avatar
Raymond Hettinger committed
92 93
	if (entry->key == dummy)
		freeslot = entry;
94
	else {
Raymond Hettinger's avatar
Raymond Hettinger committed
95 96
		if (entry->hash == hash) {
			startkey = entry->key;
97
			Py_INCREF(startkey);
98
			cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
99
			Py_DECREF(startkey);
100
			if (cmp < 0)
101
				return NULL;
102
			if (table == so->table && entry->key == startkey) {
103
				if (cmp > 0)
104
					return entry;
105 106 107 108 109
			}
			else {
				/* The compare did major nasty stuff to the
				 * set:  start over.
 				 */
110
 				return set_lookkey(so, key, hash);
111 112 113 114 115 116 117 118 119
 			}
		}
		freeslot = NULL;
	}

	/* In the loop, key == dummy is by far (factor of 100s) the
	   least likely outcome, so test for that last. */
	for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
		i = (i << 2) + i + perturb + 1;
120
		entry = &table[i & mask];
Raymond Hettinger's avatar
Raymond Hettinger committed
121
		if (entry->key == NULL) {
122
			if (freeslot != NULL)
Raymond Hettinger's avatar
Raymond Hettinger committed
123
				entry = freeslot;
124 125
			break;
		}
Raymond Hettinger's avatar
Raymond Hettinger committed
126
		if (entry->key == key)
127
			break;
Raymond Hettinger's avatar
Raymond Hettinger committed
128 129
		if (entry->hash == hash && entry->key != dummy) {
			startkey = entry->key;
130
			Py_INCREF(startkey);
131
			cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
132
			Py_DECREF(startkey);
133
			if (cmp < 0)
134
				return NULL;
135
			if (table == so->table && entry->key == startkey) {
136 137 138 139 140 141 142
				if (cmp > 0)
					break;
			}
			else {
				/* The compare did major nasty stuff to the
				 * set:  start over.
 				 */
143
 				return set_lookkey(so, key, hash);
144 145
 			}
		}
Raymond Hettinger's avatar
Raymond Hettinger committed
146 147
		else if (entry->key == dummy && freeslot == NULL)
			freeslot = entry;
148
	}
Raymond Hettinger's avatar
Raymond Hettinger committed
149
	return entry;
150 151 152 153
}

/*
 * Hacked up version of set_lookkey which can assume keys are always strings;
154
 * This means we can always use _PyString_Eq directly and not have to check to
155
 * see if the comparison altered the table.
156 157 158 159
 */
static setentry *
set_lookkey_string(PySetObject *so, PyObject *key, register long hash)
{
Martin v. Löwis's avatar
Martin v. Löwis committed
160 161
	register Py_ssize_t i;
	register size_t perturb;
162
	register setentry *freeslot;
Neal Norwitz's avatar
Neal Norwitz committed
163
	register size_t mask = so->mask;
164
	setentry *table = so->table;
Raymond Hettinger's avatar
Raymond Hettinger committed
165
	register setentry *entry;
166 167 168 169 170

	/* 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. */
171
	if (!PyString_CheckExact(key)) {
172 173 174 175
		so->lookup = set_lookkey;
		return set_lookkey(so, key, hash);
	}
	i = hash & mask;
176
	entry = &table[i];
Raymond Hettinger's avatar
Raymond Hettinger committed
177 178
	if (entry->key == NULL || entry->key == key)
		return entry;
179 180 181
	if (entry->key == dummy)
		freeslot = entry;
	else {
182
		if (entry->hash == hash && _PyString_Eq(entry->key, key))
Raymond Hettinger's avatar
Raymond Hettinger committed
183
			return entry;
184 185 186 187 188 189 190 191 192 193 194 195 196
		freeslot = NULL;
	}

	/* In the loop, key == dummy is by far (factor of 100s) the
	   least likely outcome, so test for that last. */
	for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
		i = (i << 2) + i + perturb + 1;
		entry = &table[i & mask];
		if (entry->key == NULL)
			return freeslot == NULL ? entry : freeslot;
		if (entry->key == key
		    || (entry->hash == hash
			&& entry->key != dummy
197
			&& _PyString_Eq(entry->key, key)))
198 199 200
			return entry;
		if (entry->key == dummy && freeslot == NULL)
			freeslot = entry;
201
	}
202 203
	assert(0);	/* NOT REACHED */
	return 0;
204 205 206
}

/*
Raymond Hettinger's avatar
Raymond Hettinger committed
207
Internal routine to insert a new key into the table.
208
Used by the public insert routine.
209 210
Eats a reference to key.
*/
211
static int
212 213
set_insert_key(register PySetObject *so, PyObject *key, long hash)
{
Raymond Hettinger's avatar
Raymond Hettinger committed
214
	register setentry *entry;
215 216 217
	typedef setentry *(*lookupfunc)(PySetObject *, PyObject *, long);

	assert(so->lookup != NULL);
Raymond Hettinger's avatar
Raymond Hettinger committed
218
	entry = so->lookup(so, key, hash);
219 220
	if (entry == NULL)
		return -1;
Raymond Hettinger's avatar
Raymond Hettinger committed
221
	if (entry->key == NULL) {
222 223
		/* UNUSED */
		so->fill++; 
Raymond Hettinger's avatar
Raymond Hettinger committed
224 225
		entry->key = key;
		entry->hash = hash;
226
		so->used++;
Raymond Hettinger's avatar
Raymond Hettinger committed
227
	} else if (entry->key == dummy) {
228
		/* DUMMY */
Raymond Hettinger's avatar
Raymond Hettinger committed
229 230
		entry->key = key;
		entry->hash = hash;
231 232 233 234 235 236
		so->used++;
		Py_DECREF(dummy);
	} else {
		/* ACTIVE */
		Py_DECREF(key);
	}
237
	return 0;
238 239
}

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
/*
Internal routine used by set_table_resize() to insert an item which is
known to be absent from the set.  This routine also assumes that
the set contains no deleted entries.  Besides the performance benefit,
using set_insert_clean() in set_table_resize() is dangerous (SF bug #1456209).
Note that no refcounts are changed by this routine; if needed, the caller
is responsible for incref'ing `key`.
*/
static void
set_insert_clean(register PySetObject *so, PyObject *key, long hash)
{
	register size_t i;
	register size_t perturb;
	register size_t mask = (size_t)so->mask;
	setentry *table = so->table;
	register setentry *entry;

	i = hash & mask;
	entry = &table[i];
	for (perturb = hash; entry->key != NULL; perturb >>= PERTURB_SHIFT) {
		i = (i << 2) + i + perturb + 1;
		entry = &table[i & mask];
	}
	so->fill++;
	entry->key = key;
	entry->hash = hash;
	so->used++;
}

269 270
/*
Restructure the table by allocating a new table and reinserting all
Raymond Hettinger's avatar
Raymond Hettinger committed
271
keys again.  When entries have been deleted, the new table may
272 273 274
actually be smaller than the old one.
*/
static int
Neal Norwitz's avatar
Neal Norwitz committed
275
set_table_resize(PySetObject *so, Py_ssize_t minused)
276
{
Neal Norwitz's avatar
Neal Norwitz committed
277
	Py_ssize_t newsize;
Raymond Hettinger's avatar
Raymond Hettinger committed
278
	setentry *oldtable, *newtable, *entry;
Neal Norwitz's avatar
Neal Norwitz committed
279
	Py_ssize_t i;
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
	int is_oldtable_malloced;
	setentry small_copy[PySet_MINSIZE];

	assert(minused >= 0);

	/* Find the smallest table size > minused. */
	for (newsize = PySet_MINSIZE;
	     newsize <= minused && newsize > 0;
	     newsize <<= 1)
		;
	if (newsize <= 0) {
		PyErr_NoMemory();
		return -1;
	}

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

	if (newsize == PySet_MINSIZE) {
		/* A large table is shrinking, or we can't get any smaller. */
		newtable = so->smalltable;
		if (newtable == oldtable) {
			if (so->fill == so->used) {
				/* No dummies, so no point doing anything. */
				return 0;
			}
			/* 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 set_lookkey needs at least one virgin slot to
			   terminate failing searches.  If fill < size, it's
			   merely desirable, as dummies slow searches. */
			assert(so->fill > so->used);
			memcpy(small_copy, oldtable, sizeof(small_copy));
			oldtable = small_copy;
		}
	}
	else {
		newtable = PyMem_NEW(setentry, newsize);
		if (newtable == NULL) {
			PyErr_NoMemory();
			return -1;
		}
	}

	/* Make the set empty, using the new table. */
	assert(newtable != oldtable);
	so->table = newtable;
	so->mask = newsize - 1;
	memset(newtable, 0, sizeof(setentry) * newsize);
	so->used = 0;
	i = so->fill;
	so->fill = 0;

	/* Copy the data over; this is refcount-neutral for active entries;
	   dummy entries aren't copied over, of course */
Raymond Hettinger's avatar
Raymond Hettinger committed
338 339
	for (entry = oldtable; i > 0; entry++) {
		if (entry->key == NULL) {
340 341
			/* UNUSED */
			;
Raymond Hettinger's avatar
Raymond Hettinger committed
342
		} else if (entry->key == dummy) {
343 344
			/* DUMMY */
			--i;
Raymond Hettinger's avatar
Raymond Hettinger committed
345 346
			assert(entry->key == dummy);
			Py_DECREF(entry->key);
347 348 349
		} else {
			/* ACTIVE */
			--i;
350
			set_insert_clean(so, entry->key, entry->hash);
351 352 353 354 355 356 357 358
		}
	}

	if (is_oldtable_malloced)
		PyMem_DEL(oldtable);
	return 0;
}

359 360 361 362 363
/* CAUTION: set_add_key/entry() must guarantee it won't resize the table */

static int
set_add_entry(register PySetObject *so, setentry *entry)
{
Neal Norwitz's avatar
Neal Norwitz committed
364
	register Py_ssize_t n_used;
365 366 367 368

	assert(so->fill <= so->mask);  /* at least one empty slot */
	n_used = so->used;
	Py_INCREF(entry->key);
369 370
	if (set_insert_key(so, entry->key, entry->hash) == -1) {
		Py_DECREF(entry->key);
371
		return -1;
372
	}
373 374 375 376 377
	if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2))
		return 0;
	return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
}

378
static int
379
set_add_key(register PySetObject *so, PyObject *key)
380 381
{
	register long hash;
Neal Norwitz's avatar
Neal Norwitz committed
382
	register Py_ssize_t n_used;
383

384 385
	if (!PyString_CheckExact(key) ||
	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
386 387 388 389 390 391 392
		hash = PyObject_Hash(key);
		if (hash == -1)
			return -1;
	}
	assert(so->fill <= so->mask);  /* at least one empty slot */
	n_used = so->used;
	Py_INCREF(key);
393 394 395 396
	if (set_insert_key(so, key, hash) == -1) {
		Py_DECREF(key);
		return -1;
	}
397 398
	if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2))
		return 0;
399
	return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
400 401 402 403 404 405
}

#define DISCARD_NOTFOUND 0
#define DISCARD_FOUND 1

static int
406 407 408 409 410
set_discard_entry(PySetObject *so, setentry *oldentry)
{	register setentry *entry;
	PyObject *old_key;

	entry = (so->lookup)(so, oldentry->key, oldentry->hash);
411 412
	if (entry == NULL)
		return -1;
413 414 415 416 417 418 419 420 421 422 423 424
	if (entry->key == NULL  ||  entry->key == dummy)
		return DISCARD_NOTFOUND;
	old_key = entry->key;
	Py_INCREF(dummy);
	entry->key = dummy;
	so->used--;
	Py_DECREF(old_key);
	return DISCARD_FOUND;
}

static int
set_discard_key(PySetObject *so, PyObject *key)
425 426
{
	register long hash;
Raymond Hettinger's avatar
Raymond Hettinger committed
427
	register setentry *entry;
428 429 430
	PyObject *old_key;

	assert (PyAnySet_Check(so));
431 432
	if (!PyString_CheckExact(key) ||
	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
433 434 435 436
		hash = PyObject_Hash(key);
		if (hash == -1)
			return -1;
	}
Raymond Hettinger's avatar
Raymond Hettinger committed
437
	entry = (so->lookup)(so, key, hash);
438 439
	if (entry == NULL)
		return -1;
Raymond Hettinger's avatar
Raymond Hettinger committed
440
	if (entry->key == NULL  ||  entry->key == dummy)
441
		return DISCARD_NOTFOUND;
Raymond Hettinger's avatar
Raymond Hettinger committed
442
	old_key = entry->key;
443
	Py_INCREF(dummy);
Raymond Hettinger's avatar
Raymond Hettinger committed
444
	entry->key = dummy;
445 446 447 448 449
	so->used--;
	Py_DECREF(old_key);
	return DISCARD_FOUND;
}

450
static int
451 452
set_clear_internal(PySetObject *so)
{
Raymond Hettinger's avatar
Raymond Hettinger committed
453
	setentry *entry, *table;
454
	int table_is_malloced;
Neal Norwitz's avatar
Neal Norwitz committed
455
	Py_ssize_t fill;
456 457
	setentry small_copy[PySet_MINSIZE];
#ifdef Py_DEBUG
Neal Norwitz's avatar
Neal Norwitz committed
458
	Py_ssize_t i, n;
459
	assert (PyAnySet_Check(so));
460

461 462 463 464 465 466 467 468 469 470 471
	n = so->mask + 1;
	i = 0;
#endif

	table = so->table;
	assert(table != NULL);
	table_is_malloced = table != so->smalltable;

	/* This is delicate.  During the process of clearing the set,
	 * decrefs can cause the set to mutate.  To avoid fatal confusion
	 * (voice of experience), we have to make the set empty before
472
	 * clearing the slots, and never refer to anything via so->ref while
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
	 * clearing.
	 */
	fill = so->fill;
	if (table_is_malloced)
		EMPTY_TO_MINSIZE(so);

	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 set entries into
		 * another small table first.
		 */
		memcpy(small_copy, table, sizeof(small_copy));
		table = small_copy;
		EMPTY_TO_MINSIZE(so);
	}
	/* 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.
	 */
Raymond Hettinger's avatar
Raymond Hettinger committed
494
	for (entry = table; fill > 0; ++entry) {
495 496 497 498
#ifdef Py_DEBUG
		assert(i < n);
		++i;
#endif
Raymond Hettinger's avatar
Raymond Hettinger committed
499
		if (entry->key) {
500
			--fill;
Raymond Hettinger's avatar
Raymond Hettinger committed
501
			Py_DECREF(entry->key);
502 503 504
		}
#ifdef Py_DEBUG
		else
505
			assert(entry->key == NULL);
506 507 508 509 510
#endif
	}

	if (table_is_malloced)
		PyMem_DEL(table);
511
	return 0;
512 513 514 515 516
}

/*
 * Iterate over a set table.  Use like so:
 *
Neal Norwitz's avatar
Neal Norwitz committed
517
 *     Py_ssize_t pos;
518
 *     setentry *entry;
519
 *     pos = 0;   # important!  pos should not otherwise be changed by you
520 521
 *     while (set_next(yourset, &pos, &entry)) {
 *              Refer to borrowed reference in entry->key.
522 523
 *     }
 *
524
 * CAUTION:  In general, it isn't safe to use set_next in a loop that
525 526 527
 * mutates the table.  
 */
static int
Martin v. Löwis's avatar
Martin v. Löwis committed
528
set_next(PySetObject *so, Py_ssize_t *pos_ptr, setentry **entry_ptr)
529
{
Martin v. Löwis's avatar
Martin v. Löwis committed
530
	Py_ssize_t i;
Neal Norwitz's avatar
Neal Norwitz committed
531
	Py_ssize_t mask;
532
	register setentry *table;
533 534

	assert (PyAnySet_Check(so));
535
	i = *pos_ptr;
536
	assert(i >= 0);
537
	table = so->table;
538
	mask = so->mask;
539
	while (i <= mask && (table[i].key == NULL || table[i].key == dummy))
540
		i++;
541
	*pos_ptr = i+1;
542 543
	if (i > mask)
		return 0;
544 545
	assert(table[i].key != NULL);
	*entry_ptr = &table[i];
546 547 548
	return 1;
}

549 550 551 552
static void
set_dealloc(PySetObject *so)
{
	register setentry *entry;
Neal Norwitz's avatar
Neal Norwitz committed
553
	Py_ssize_t fill = so->fill;
554 555 556 557 558 559 560 561 562 563 564 565 566
	PyObject_GC_UnTrack(so);
	Py_TRASHCAN_SAFE_BEGIN(so)
	if (so->weakreflist != NULL)
		PyObject_ClearWeakRefs((PyObject *) so);

	for (entry = so->table; fill > 0; entry++) {
		if (entry->key) {
			--fill;
			Py_DECREF(entry->key);
		}
	}
	if (so->table != so->smalltable)
		PyMem_DEL(so->table);
567 568
	if (numfree < PySet_MAXFREELIST && PyAnySet_CheckExact(so))
		free_list[numfree++] = so;
569
	else 
570
		Py_TYPE(so)->tp_free(so);
571 572 573 574 575 576 577
	Py_TRASHCAN_SAFE_END(so)
}

static int
set_tp_print(PySetObject *so, FILE *fp, int flags)
{
	setentry *entry;
Martin v. Löwis's avatar
Martin v. Löwis committed
578
	Py_ssize_t pos=0;
579 580
	char *emit = "";	/* No separator emitted on first pass */
	char *separator = ", ";
581 582 583 584 585
	int status = Py_ReprEnter((PyObject*)so);

	if (status != 0) {
		if (status < 0)
			return status;
586
		Py_BEGIN_ALLOW_THREADS
587
		fprintf(fp, "%s(...)", so->ob_type->tp_name);
588
		Py_END_ALLOW_THREADS
589 590
		return 0;
	}        
591

592
	Py_BEGIN_ALLOW_THREADS
593
	fprintf(fp, "%s([", so->ob_type->tp_name);
594
	Py_END_ALLOW_THREADS
595
	while (set_next(so, &pos, &entry)) {
596
		Py_BEGIN_ALLOW_THREADS
597
		fputs(emit, fp);
598
		Py_END_ALLOW_THREADS
599
		emit = separator;
600 601
		if (PyObject_Print(entry->key, fp, 0) != 0) {
			Py_ReprLeave((PyObject*)so);
602
			return -1;
603
		}
604
	}
605
	Py_BEGIN_ALLOW_THREADS
606
	fputs("])", fp);
607
	Py_END_ALLOW_THREADS
608
	Py_ReprLeave((PyObject*)so);        
609 610 611 612 613 614
	return 0;
}

static PyObject *
set_repr(PySetObject *so)
{
615 616 617 618 619 620
	PyObject *keys, *result=NULL, *listrepr;
	int status = Py_ReprEnter((PyObject*)so);

	if (status != 0) {
		if (status < 0)
			return NULL;
621
		return PyString_FromFormat("%s(...)", so->ob_type->tp_name);
622
	}
623 624 625

	keys = PySequence_List((PyObject *)so);
	if (keys == NULL)
626
		goto done;
627 628 629
	listrepr = PyObject_Repr(keys);
	Py_DECREF(keys);
	if (listrepr == NULL)
630
		goto done;
631

632 633
	result = PyString_FromFormat("%s(%s)", so->ob_type->tp_name,
		PyString_AS_STRING(listrepr));
634
	Py_DECREF(listrepr);
635 636
done:
	Py_ReprLeave((PyObject*)so);
637 638 639
	return result;
}

Martin v. Löwis's avatar
Martin v. Löwis committed
640
static Py_ssize_t
641 642 643 644 645
set_len(PyObject *so)
{
	return ((PySetObject *)so)->used;
}

646
static int
647
set_merge(PySetObject *so, PyObject *otherset)
648
{
649
	PySetObject *other;
Neal Norwitz's avatar
Neal Norwitz committed
650
	register Py_ssize_t i;
651
	register setentry *entry;
652 653

	assert (PyAnySet_Check(so));
Raymond Hettinger's avatar
Raymond Hettinger committed
654
	assert (PyAnySet_Check(otherset));
655

Raymond Hettinger's avatar
Raymond Hettinger committed
656
	other = (PySetObject*)otherset;
657 658 659 660
	if (other == so || other->used == 0)
		/* a.update(a) or a.update({}); nothing to do */
		return 0;
	/* Do one big resize at the start, rather than
Raymond Hettinger's avatar
Raymond Hettinger committed
661
	 * incrementally resizing as we insert new keys.  Expect
662 663 664 665 666 667
	 * that there will be no (or few) overlapping keys.
	 */
	if ((so->fill + other->used)*3 >= (so->mask+1)*2) {
	   if (set_table_resize(so, (so->used + other->used)*2) != 0)
		   return -1;
	}
668 669
	for (i = 0; i <= other->mask; i++) {
		entry = &other->table[i];
670 671 672
		if (entry->key != NULL && 
		    entry->key != dummy) {
			Py_INCREF(entry->key);
673 674 675 676
			if (set_insert_key(so, entry->key, entry->hash) == -1) {
				Py_DECREF(entry->key);
				return -1;
			}
677 678 679 680 681 682
		}
	}
	return 0;
}

static int
683
set_contains_key(PySetObject *so, PyObject *key)
684 685
{
	long hash;
686
	setentry *entry;
687

688 689
	if (!PyString_CheckExact(key) ||
	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
690 691 692 693
		hash = PyObject_Hash(key);
		if (hash == -1)
			return -1;
	}
694 695 696 697
	entry = (so->lookup)(so, key, hash);
	if (entry == NULL)
		return -1;
	key = entry->key;
698 699 700
	return key != NULL && key != dummy;
}

701 702 703 704
static int
set_contains_entry(PySetObject *so, setentry *entry)
{
	PyObject *key;
705
	setentry *lu_entry;
706

707 708 709 710
	lu_entry = (so->lookup)(so, entry->key, entry->hash);
	if (lu_entry == NULL)
		return -1;
	key = lu_entry->key; 
711 712 713
	return key != NULL && key != dummy;
}

714 715 716
static PyObject *
set_pop(PySetObject *so)
{
Neal Norwitz's avatar
Neal Norwitz committed
717
	register Py_ssize_t i = 0;
718 719
	register setentry *entry;
	PyObject *key;
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734

	assert (PyAnySet_Check(so));
	if (so->used == 0) {
		PyErr_SetString(PyExc_KeyError, "pop from an empty set");
		return NULL;
	}

	/* Set entry to "the first" unused or dummy set entry.  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,
	 * and we use its hash value as the first index to look.
	 */
	entry = &so->table[0];
	if (entry->key == NULL || entry->key == dummy) {
Neal Norwitz's avatar
Neal Norwitz committed
735
		i = entry->hash;
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
		/* 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.
		 */
		if (i > so->mask || i < 1)
			i = 1;	/* skip slot 0 */
		while ((entry = &so->table[i])->key == NULL || entry->key==dummy) {
			i++;
			if (i > so->mask)
				i = 1;
		}
	}
	key = entry->key;
	Py_INCREF(dummy);
	entry->key = dummy;
	so->used--;
	so->table[0].hash = i + 1;  /* next place to start */
	return key;
}

Benjamin Peterson's avatar
Benjamin Peterson committed
757 758
PyDoc_STRVAR(pop_doc, "Remove and return an arbitrary set element.\n\
Raises KeyError if the set is empty.");
759 760

static int
761
set_traverse(PySetObject *so, visitproc visit, void *arg)
762
{
Martin v. Löwis's avatar
Martin v. Löwis committed
763
	Py_ssize_t pos = 0;
764 765 766 767 768 769 770 771 772 773 774 775 776
	setentry *entry;

	while (set_next(so, &pos, &entry))
		Py_VISIT(entry->key);
	return 0;
}

static long
frozenset_hash(PyObject *self)
{
	PySetObject *so = (PySetObject *)self;
	long h, hash = 1927868237L;
	setentry *entry;
Martin v. Löwis's avatar
Martin v. Löwis committed
777
	Py_ssize_t pos = 0;
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798

	if (so->hash != -1)
		return so->hash;

	hash *= PySet_GET_SIZE(self) + 1;
	while (set_next(so, &pos, &entry)) {
		/* Work to increase the bit dispersion for closely spaced hash
		   values.  The is important because some use cases have many 
		   combinations of a small number of elements with nearby 
		   hashes so that many distinct combinations collapse to only 
		   a handful of distinct hash values. */
		h = entry->hash;
		hash ^= (h ^ (h << 16) ^ 89869747L)  * 3644798167u;
	}
	hash = hash * 69069L + 907133923L;
	if (hash == -1)
		hash = 590923713L;
	so->hash = hash;
	return hash;
}

799
/***** Set iterator type ***********************************************/
800 801 802 803

typedef struct {
	PyObject_HEAD
	PySetObject *si_set; /* Set to NULL when iterator is exhausted */
Neal Norwitz's avatar
Neal Norwitz committed
804 805 806
	Py_ssize_t si_used;
	Py_ssize_t si_pos;
	Py_ssize_t len;
807 808 809 810 811 812 813 814 815
} setiterobject;

static void
setiter_dealloc(setiterobject *si)
{
	Py_XDECREF(si->si_set);
	PyObject_Del(si);
}

816
static PyObject *
817 818
setiter_len(setiterobject *si)
{
Neal Norwitz's avatar
Neal Norwitz committed
819
	Py_ssize_t len = 0;
820
	if (si->si_set != NULL && si->si_used == si->si_set->used)
821 822
		len = si->len;
	return PyInt_FromLong(len);
823 824
}

825
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
826 827

static PyMethodDef setiter_methods[] = {
828
	{"__length_hint__", (PyCFunction)setiter_len, METH_NOARGS, length_hint_doc},
829
 	{NULL,		NULL}		/* sentinel */
830 831
};

Raymond Hettinger's avatar
Raymond Hettinger committed
832
static PyObject *setiter_iternext(setiterobject *si)
833 834
{
	PyObject *key;
Neal Norwitz's avatar
Neal Norwitz committed
835
	register Py_ssize_t i, mask;
Raymond Hettinger's avatar
Raymond Hettinger committed
836 837
	register setentry *entry;
	PySetObject *so = si->si_set;
838

Raymond Hettinger's avatar
Raymond Hettinger committed
839
	if (so == NULL)
840
		return NULL;
Raymond Hettinger's avatar
Raymond Hettinger committed
841
	assert (PyAnySet_Check(so));
842

Raymond Hettinger's avatar
Raymond Hettinger committed
843
	if (si->si_used != so->used) {
844 845 846 847 848 849 850
		PyErr_SetString(PyExc_RuntimeError,
				"Set changed size during iteration");
		si->si_used = -1; /* Make this state sticky */
		return NULL;
	}

	i = si->si_pos;
851
	assert(i>=0);
Raymond Hettinger's avatar
Raymond Hettinger committed
852 853 854
	entry = so->table;
	mask = so->mask;
	while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy))
855 856 857 858 859
		i++;
	si->si_pos = i+1;
	if (i > mask)
		goto fail;
	si->len--;
Raymond Hettinger's avatar
Raymond Hettinger committed
860
	key = entry[i].key;
861 862 863 864
	Py_INCREF(key);
	return key;

fail:
Raymond Hettinger's avatar
Raymond Hettinger committed
865
	Py_DECREF(so);
866 867 868 869
	si->si_set = NULL;
	return NULL;
}

870
static PyTypeObject PySetIter_Type = {
871
	PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger's avatar
Raymond Hettinger committed
872
	"setiterator",				/* tp_name */
873 874 875 876 877 878 879 880 881 882
	sizeof(setiterobject),			/* tp_basicsize */
	0,					/* tp_itemsize */
	/* methods */
	(destructor)setiter_dealloc, 		/* tp_dealloc */
	0,					/* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
	0,					/* tp_repr */
	0,					/* tp_as_number */
883
	0,					/* tp_as_sequence */
884 885 886 887 888 889 890 891 892 893 894 895 896 897
	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 */
Raymond Hettinger's avatar
Raymond Hettinger committed
898
	(iternextfunc)setiter_iternext,		/* tp_iternext */
899 900
	setiter_methods,			/* tp_methods */
	0,
901 902
};

903 904 905 906 907 908 909 910 911 912 913 914 915 916
static PyObject *
set_iter(PySetObject *so)
{
	setiterobject *si = PyObject_New(setiterobject, &PySetIter_Type);
	if (si == NULL)
		return NULL;
	Py_INCREF(so);
	si->si_set = so;
	si->si_used = so->used;
	si->si_pos = 0;
	si->len = so->used;
	return (PyObject *)si;
}

917 918
static int
set_update_internal(PySetObject *so, PyObject *other)
919
{
Raymond Hettinger's avatar
Raymond Hettinger committed
920
	PyObject *key, *it;
921

922
	if (PyAnySet_Check(other))
923
		return set_merge(so, other);
924

925
	if (PyDict_CheckExact(other)) {
926
		PyObject *value;
Martin v. Löwis's avatar
Martin v. Löwis committed
927
		Py_ssize_t pos = 0;
928
		long hash;
929
		Py_ssize_t dictsize = PyDict_Size(other);
930

931 932 933 934 935 936 937 938 939 940
		/* Do one big resize at the start, rather than
		* incrementally resizing as we insert new keys.  Expect
		* that there will be no (or few) overlapping keys.
		*/
		if (dictsize == -1)
			return -1;
		if ((so->fill + dictsize)*3 >= (so->mask+1)*2) {
			if (set_table_resize(so, (so->used + dictsize)*2) != 0)
				return -1;
		}
941 942 943 944 945 946
		while (_PyDict_Next(other, &pos, &key, &value, &hash)) {
			setentry an_entry;

			an_entry.hash = hash;
			an_entry.key = key;
			if (set_add_entry(so, &an_entry) == -1)
947
				return -1;
948
		}
949
		return 0;
950 951
	}

952 953
	it = PyObject_GetIter(other);
	if (it == NULL)
954
		return -1;
955

Raymond Hettinger's avatar
Raymond Hettinger committed
956
	while ((key = PyIter_Next(it)) != NULL) {
957
                if (set_add_key(so, key) == -1) {
958
			Py_DECREF(it);
Raymond Hettinger's avatar
Raymond Hettinger committed
959
			Py_DECREF(key);
960
			return -1;
961
                } 
Raymond Hettinger's avatar
Raymond Hettinger committed
962
		Py_DECREF(key);
963
	}
964
	Py_DECREF(it);
965
	if (PyErr_Occurred())
966 967 968 969 970
		return -1;
	return 0;
}

static PyObject *
971
set_update(PySetObject *so, PyObject *args)
972
{
973 974 975 976 977 978 979
	Py_ssize_t i;

	for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
		PyObject *other = PyTuple_GET_ITEM(args, i);
		if (set_update_internal(so, other) == -1)
			return NULL;
	}
980 981 982 983
	Py_RETURN_NONE;
}

PyDoc_STRVAR(update_doc, 
984
"Update a set with the union of itself and others.");
985 986 987 988

static PyObject *
make_new_set(PyTypeObject *type, PyObject *iterable)
{
989
	register PySetObject *so = NULL;
990

991
	if (dummy == NULL) { /* Auto-initialize dummy */
992
		dummy = PyString_FromString("<dummy key>");
993 994 995
		if (dummy == NULL)
			return NULL;
	}
996 997

	/* create PySetObject structure */
998
	if (numfree &&
999
	    (type == &PySet_Type  ||  type == &PyFrozenSet_Type)) {
1000
		so = free_list[--numfree];
1001
		assert (so != NULL && PyAnySet_CheckExact(so));
1002
		Py_TYPE(so) = type;
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
		_Py_NewReference((PyObject *)so);
		EMPTY_TO_MINSIZE(so);
		PyObject_GC_Track(so);
	} else {
		so = (PySetObject *)type->tp_alloc(type, 0);
		if (so == NULL)
			return NULL;
		/* tp_alloc has already zeroed the structure */
		assert(so->table == NULL && so->fill == 0 && so->used == 0);
		INIT_NONZERO_SET_SLOTS(so);
	}
1014 1015

	so->lookup = set_lookkey_string;
1016
	so->weakreflist = NULL;
1017

1018
	if (iterable != NULL) {
1019
		if (set_update_internal(so, iterable) == -1) {
1020 1021 1022 1023 1024
			Py_DECREF(so);
			return NULL;
		}
	}

1025 1026 1027
	return (PyObject *)so;
}

1028 1029 1030
/* The empty frozenset is a singleton */
static PyObject *emptyfrozenset = NULL;

1031
static PyObject *
1032
frozenset_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1033
{
1034
	PyObject *iterable = NULL, *result;
1035

1036
	if (type == &PyFrozenSet_Type && !_PyArg_NoKeywords("frozenset()", kwds))
1037 1038
		return NULL;

1039 1040
	if (!PyArg_UnpackTuple(args, type->tp_name, 0, 1, &iterable))
		return NULL;
1041 1042 1043 1044 1045 1046 1047 1048 1049

	if (type != &PyFrozenSet_Type)
		return make_new_set(type, iterable);

	if (iterable != NULL) {
		/* frozenset(f) is idempotent */
		if (PyFrozenSet_CheckExact(iterable)) {
			Py_INCREF(iterable);
			return iterable;
1050
		}
1051
		result = make_new_set(type, iterable);
1052
		if (result == NULL || PySet_GET_SIZE(result))
1053 1054
			return result;
		Py_DECREF(result);
1055
	}
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
	/* The empty frozenset is a singleton */
	if (emptyfrozenset == NULL)
		emptyfrozenset = make_new_set(type, NULL);
	Py_XINCREF(emptyfrozenset);
	return emptyfrozenset;
}

void
PySet_Fini(void)
{
1066 1067
	PySetObject *so;

1068 1069 1070
	while (numfree) {
		numfree--;
		so = free_list[numfree];
1071 1072
		PyObject_GC_Del(so);
	}
1073 1074
	Py_CLEAR(dummy);
	Py_CLEAR(emptyfrozenset);
1075 1076
}

1077 1078 1079
static PyObject *
set_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
1080
	if (type == &PySet_Type && !_PyArg_NoKeywords("set()", kwds))
1081 1082
		return NULL;
	
1083 1084 1085
	return make_new_set(type, NULL);
}

1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
/* set_swap_bodies() switches the contents of any two sets by moving their
   internal data pointers and, if needed, copying the internal smalltables.
   Semantically equivalent to:

     t=set(a); a.clear(); a.update(b); b.clear(); b.update(t); del t

   The function always succeeds and it leaves both objects in a stable state.
   Useful for creating temporary frozensets from sets for membership testing 
   in __contains__(), discard(), and remove().  Also useful for operations
   that update in-place (by allowing an intermediate result to be swapped 
1096
   into one of the original inputs).
1097 1098
*/

1099 1100
static void
set_swap_bodies(PySetObject *a, PySetObject *b)
1101
{
Neal Norwitz's avatar
Neal Norwitz committed
1102
	Py_ssize_t t;
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
	setentry *u;
	setentry *(*f)(PySetObject *so, PyObject *key, long hash);
	setentry tab[PySet_MINSIZE];
	long h;

	t = a->fill;     a->fill   = b->fill;        b->fill  = t;
	t = a->used;     a->used   = b->used;        b->used  = t;
	t = a->mask;     a->mask   = b->mask;        b->mask  = t;

	u = a->table;
	if (a->table == a->smalltable)
		u = b->smalltable;
	a->table  = b->table;
	if (b->table == b->smalltable)
		a->table = a->smalltable;
	b->table = u;

	f = a->lookup;   a->lookup = b->lookup;      b->lookup = f;

	if (a->table == a->smalltable || b->table == b->smalltable) {
		memcpy(tab, a->smalltable, sizeof(tab));
		memcpy(a->smalltable, b->smalltable, sizeof(tab));
		memcpy(b->smalltable, tab, sizeof(tab));
	}

1128 1129
	if (PyType_IsSubtype(Py_TYPE(a), &PyFrozenSet_Type)  &&
	    PyType_IsSubtype(Py_TYPE(b), &PyFrozenSet_Type)) {
1130 1131 1132 1133 1134
		h = a->hash;     a->hash = b->hash;  b->hash = h;
	} else {
		a->hash = -1;
		b->hash = -1;
	}
1135 1136 1137 1138 1139
}

static PyObject *
set_copy(PySetObject *so)
{
1140
	return make_new_set(Py_TYPE(so), (PyObject *)so);
1141 1142
}

1143 1144 1145
static PyObject *
frozenset_copy(PySetObject *so)
{
1146
	if (PyFrozenSet_CheckExact(so)) {
1147 1148 1149 1150 1151 1152
		Py_INCREF(so);
		return (PyObject *)so;
	}
	return set_copy(so);
}

1153 1154
PyDoc_STRVAR(copy_doc, "Return a shallow copy of a set.");

1155 1156 1157 1158 1159 1160 1161 1162 1163
static PyObject *
set_clear(PySetObject *so)
{
	set_clear_internal(so);
	Py_RETURN_NONE;
}

PyDoc_STRVAR(clear_doc, "Remove all elements from this set.");

1164
static PyObject *
1165
set_union(PySetObject *so, PyObject *args)
1166 1167
{
	PySetObject *result;
1168 1169
	PyObject *other;
	Py_ssize_t i;
1170 1171 1172 1173

	result = (PySetObject *)set_copy(so);
	if (result == NULL)
		return NULL;
1174 1175 1176 1177 1178 1179 1180 1181 1182

	for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
		other = PyTuple_GET_ITEM(args, i);
		if ((PyObject *)so == other)
			return (PyObject *)result;
		if (set_update_internal(result, other) == -1) {
			Py_DECREF(result);
			return NULL;
		}
1183 1184 1185 1186 1187
	}
	return (PyObject *)result;
}

PyDoc_STRVAR(union_doc,
1188
 "Return the union of sets as a new set.\n\
1189 1190 1191
\n\
(i.e. all elements that are in either set.)");

1192 1193 1194
static PyObject *
set_or(PySetObject *so, PyObject *other)
{
1195 1196
	PySetObject *result;

1197
	if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
1198 1199 1200
		Py_INCREF(Py_NotImplemented);
		return Py_NotImplemented;
	}
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211

	result = (PySetObject *)set_copy(so);
	if (result == NULL)
		return NULL;
	if ((PyObject *)so == other)
		return (PyObject *)result;
	if (set_update_internal(result, other) == -1) {
		Py_DECREF(result);
		return NULL;
	}
	return (PyObject *)result;
1212 1213 1214 1215 1216
}

static PyObject *
set_ior(PySetObject *so, PyObject *other)
{
1217
	if (!PyAnySet_Check(other)) {
1218 1219 1220
		Py_INCREF(Py_NotImplemented);
		return Py_NotImplemented;
	}
1221
	if (set_update_internal(so, other) == -1)
1222 1223 1224 1225 1226 1227 1228 1229 1230
		return NULL;
	Py_INCREF(so);
	return (PyObject *)so;
}

static PyObject *
set_intersection(PySetObject *so, PyObject *other)
{
	PySetObject *result;
Raymond Hettinger's avatar
Raymond Hettinger committed
1231
	PyObject *key, *it, *tmp;
1232

1233 1234
	if ((PyObject *)so == other)
		return set_copy(so);
1235

1236
	result = (PySetObject *)make_new_set(Py_TYPE(so), NULL);
1237 1238
	if (result == NULL)
		return NULL;
1239

1240
	if (PyAnySet_Check(other)) {		
Martin v. Löwis's avatar
Martin v. Löwis committed
1241
		Py_ssize_t pos = 0;
1242
		setentry *entry;
1243

1244
		if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) {
1245 1246 1247 1248 1249
			tmp = (PyObject *)so;
			so = (PySetObject *)other;
			other = tmp;
		}

1250
		while (set_next((PySetObject *)other, &pos, &entry)) {
1251 1252 1253 1254 1255 1256
			int rv = set_contains_entry(so, entry);
			if (rv == -1) {
				Py_DECREF(result);
				return NULL;
			}
			if (rv) {
1257
				if (set_add_entry(result, entry) == -1) {
1258 1259 1260 1261 1262 1263
					Py_DECREF(result);
					return NULL;
				}
			}
		}
		return (PyObject *)result;
1264 1265
	}

1266 1267 1268 1269 1270 1271
	it = PyObject_GetIter(other);
	if (it == NULL) {
		Py_DECREF(result);
		return NULL;
	}

Raymond Hettinger's avatar
Raymond Hettinger committed
1272
	while ((key = PyIter_Next(it)) != NULL) {
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
		int rv;
		setentry entry;
		long hash = PyObject_Hash(key);

		if (hash == -1) {
			Py_DECREF(it);
			Py_DECREF(result);
			Py_DECREF(key);
			return NULL;
		}
		entry.hash = hash;
		entry.key = key;
		rv = set_contains_entry(so, &entry);
1286 1287 1288 1289 1290 1291 1292
		if (rv == -1) {
			Py_DECREF(it);
			Py_DECREF(result);
			Py_DECREF(key);
			return NULL;
		}
		if (rv) {
1293
			if (set_add_entry(result, &entry) == -1) {
1294 1295
				Py_DECREF(it);
				Py_DECREF(result);
Raymond Hettinger's avatar
Raymond Hettinger committed
1296
				Py_DECREF(key);
1297 1298 1299
				return NULL;
			}
		}
Raymond Hettinger's avatar
Raymond Hettinger committed
1300
		Py_DECREF(key);
1301 1302 1303 1304 1305 1306 1307 1308 1309
	}
	Py_DECREF(it);
	if (PyErr_Occurred()) {
		Py_DECREF(result);
		return NULL;
	}
	return (PyObject *)result;
}

1310 1311 1312 1313 1314 1315
static PyObject *
set_intersection_multi(PySetObject *so, PyObject *args)
{
	Py_ssize_t i;
	PyObject *result = (PyObject *)so;

1316 1317 1318
	if (PyTuple_GET_SIZE(args) == 0)
		return set_copy(so);

1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
	Py_INCREF(so);
	for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
		PyObject *other = PyTuple_GET_ITEM(args, i);
		PyObject *newresult = set_intersection((PySetObject *)result, other);
		if (newresult == NULL) {
			Py_DECREF(result);
			return NULL;
		}
		Py_DECREF(result);
		result = newresult;
	}
	return result;
}

1333 1334 1335 1336 1337 1338 1339 1340
PyDoc_STRVAR(intersection_doc,
"Return the intersection of two sets as a new set.\n\
\n\
(i.e. all elements that are in both sets.)");

static PyObject *
set_intersection_update(PySetObject *so, PyObject *other)
{
1341
	PyObject *tmp;
1342

1343 1344
	tmp = set_intersection(so, other);
	if (tmp == NULL)
1345
		return NULL;
1346
	set_swap_bodies(so, (PySetObject *)tmp);
1347 1348 1349 1350
	Py_DECREF(tmp);
	Py_RETURN_NONE;
}

1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
static PyObject *
set_intersection_update_multi(PySetObject *so, PyObject *args)
{
	PyObject *tmp;

	tmp = set_intersection_multi(so, args);
	if (tmp == NULL)
		return NULL;
	set_swap_bodies(so, (PySetObject *)tmp);
	Py_DECREF(tmp);
	Py_RETURN_NONE;
}

1364 1365 1366 1367 1368 1369
PyDoc_STRVAR(intersection_update_doc,
"Update a set with the intersection of itself and another.");

static PyObject *
set_and(PySetObject *so, PyObject *other)
{
1370
	if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
		Py_INCREF(Py_NotImplemented);
		return Py_NotImplemented;
	}
	return set_intersection(so, other);
}

static PyObject *
set_iand(PySetObject *so, PyObject *other)
{
	PyObject *result;

1382
	if (!PyAnySet_Check(other)) {
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
		Py_INCREF(Py_NotImplemented);
		return Py_NotImplemented;
	}
	result = set_intersection_update(so, other);
	if (result == NULL)
		return NULL;
	Py_DECREF(result);
	Py_INCREF(so);
	return (PyObject *)so;
}

Raymond Hettinger's avatar
Raymond Hettinger committed
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
static PyObject *
set_isdisjoint(PySetObject *so, PyObject *other)
{
	PyObject *key, *it, *tmp;

	if ((PyObject *)so == other) {
		if (PySet_GET_SIZE(so) == 0)
			Py_RETURN_TRUE;
		else
			Py_RETURN_FALSE;
	}

	if (PyAnySet_CheckExact(other)) {		
		Py_ssize_t pos = 0;
		setentry *entry;

		if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) {
			tmp = (PyObject *)so;
			so = (PySetObject *)other;
			other = tmp;
		}
		while (set_next((PySetObject *)other, &pos, &entry)) {
			int rv = set_contains_entry(so, entry);
			if (rv == -1)
				return NULL;
			if (rv)
				Py_RETURN_FALSE;
		}
		Py_RETURN_TRUE;
	}

	it = PyObject_GetIter(other);
	if (it == NULL)
		return NULL;

	while ((key = PyIter_Next(it)) != NULL) {
		int rv;
		setentry entry;
		long hash = PyObject_Hash(key);

		if (hash == -1) {
1435
			Py_DECREF(key);
Raymond Hettinger's avatar
Raymond Hettinger committed
1436 1437 1438 1439 1440 1441
			Py_DECREF(it);
			return NULL;
		}
		entry.hash = hash;
		entry.key = key;
		rv = set_contains_entry(so, &entry);
1442
		Py_DECREF(key);
Raymond Hettinger's avatar
Raymond Hettinger committed
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
		if (rv == -1) {
			Py_DECREF(it);
			return NULL;
		}
		if (rv) {
			Py_DECREF(it);
			Py_RETURN_FALSE;
		}
	}
	Py_DECREF(it);
	if (PyErr_Occurred())
		return NULL;
	Py_RETURN_TRUE;
}

PyDoc_STRVAR(isdisjoint_doc,
"Return True if two sets have a null intersection.");

1461
static int
1462
set_difference_update_internal(PySetObject *so, PyObject *other)
1463
{
1464 1465
	if ((PyObject *)so == other)
		return set_clear_internal(so);
1466
	
1467
	if (PyAnySet_Check(other)) {
1468
		setentry *entry;
Martin v. Löwis's avatar
Martin v. Löwis committed
1469
		Py_ssize_t pos = 0;
1470

1471
		while (set_next((PySetObject *)other, &pos, &entry))
1472 1473
			if (set_discard_entry(so, entry) == -1)
				return -1;
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
	} else {
		PyObject *key, *it;
		it = PyObject_GetIter(other);
		if (it == NULL)
			return -1;

		while ((key = PyIter_Next(it)) != NULL) {
			if (set_discard_key(so, key) == -1) {
				Py_DECREF(it);
				Py_DECREF(key);
				return -1;
			}
Raymond Hettinger's avatar
Raymond Hettinger committed
1486
			Py_DECREF(key);
1487
		}
1488 1489 1490
		Py_DECREF(it);
		if (PyErr_Occurred())
			return -1;
1491
	}
1492 1493 1494 1495 1496 1497 1498
	/* If more than 1/5 are dummies, then resize them away. */
	if ((so->fill - so->used) * 5 < so->mask)
		return 0;
	return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
}

static PyObject *
1499
set_difference_update(PySetObject *so, PyObject *args)
1500
{
1501 1502 1503 1504 1505 1506 1507 1508
	Py_ssize_t i;

	for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
		PyObject *other = PyTuple_GET_ITEM(args, i);
		if (set_difference_update_internal(so, other) == -1)
			return NULL;
	}
	Py_RETURN_NONE;
1509 1510 1511 1512 1513
}

PyDoc_STRVAR(difference_update_doc,
"Remove all elements of another set from this set.");

1514 1515 1516
static PyObject *
set_difference(PySetObject *so, PyObject *other)
{
1517 1518
	PyObject *result;
	setentry *entry;
Martin v. Löwis's avatar
Martin v. Löwis committed
1519
	Py_ssize_t pos = 0;
1520

1521
	if (!PyAnySet_Check(other)  && !PyDict_CheckExact(other)) {
1522 1523
		result = set_copy(so);
		if (result == NULL)
1524 1525
			return NULL;
		if (set_difference_update_internal((PySetObject *)result, other) != -1)
1526 1527 1528 1529 1530
			return result;
		Py_DECREF(result);
		return NULL;
	}
	
1531
	result = make_new_set(Py_TYPE(so), NULL);
1532 1533 1534
	if (result == NULL)
		return NULL;

1535
	if (PyDict_CheckExact(other)) {
1536 1537 1538 1539
		while (set_next(so, &pos, &entry)) {
			setentry entrycopy;
			entrycopy.hash = entry->hash;
			entrycopy.key = entry->key;
1540
			if (!_PyDict_Contains(other, entry->key, entry->hash)) {
1541 1542
				if (set_add_entry((PySetObject *)result, &entrycopy) == -1) {
					Py_DECREF(result);
1543
					return NULL;
1544
				}
1545 1546 1547 1548 1549
			}
		}
		return result;
	}

1550
	while (set_next(so, &pos, &entry)) {
1551 1552 1553 1554 1555 1556 1557 1558
		int rv = set_contains_entry((PySetObject *)other, entry);
		if (rv == -1) {
			Py_DECREF(result);
			return NULL;
		}
		if (!rv) {
			if (set_add_entry((PySetObject *)result, entry) == -1) {
				Py_DECREF(result);
1559
				return NULL;
1560
			}
1561 1562 1563 1564 1565
		}
	}
	return result;
}

1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
static PyObject *
set_difference_multi(PySetObject *so, PyObject *args)
{
	Py_ssize_t i;
	PyObject *result, *other;

	if (PyTuple_GET_SIZE(args) == 0)
		return set_copy(so);

	other = PyTuple_GET_ITEM(args, 0);
	result = set_difference(so, other);
	if (result == NULL)
		return NULL;

	for (i=1 ; i<PyTuple_GET_SIZE(args) ; i++) {
		other = PyTuple_GET_ITEM(args, i);
		if (set_difference_update_internal((PySetObject *)result, other) == -1) {
			Py_DECREF(result);
			return NULL;
		}
	}
	return result;
}

1590
PyDoc_STRVAR(difference_doc,
1591
"Return the difference of two or more sets as a new set.\n\
1592
\n\
1593
(i.e. all elements that are in this set but not the others.)");
1594 1595 1596
static PyObject *
set_sub(PySetObject *so, PyObject *other)
{
1597
	if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
1598 1599 1600 1601 1602 1603 1604 1605 1606
		Py_INCREF(Py_NotImplemented);
		return Py_NotImplemented;
	}
	return set_difference(so, other);
}

static PyObject *
set_isub(PySetObject *so, PyObject *other)
{
1607
	if (!PyAnySet_Check(other)) {
1608 1609 1610
		Py_INCREF(Py_NotImplemented);
		return Py_NotImplemented;
	}
1611
	if (set_difference_update_internal(so, other) == -1)
1612 1613 1614 1615 1616 1617
		return NULL;
	Py_INCREF(so);
	return (PyObject *)so;
}

static PyObject *
1618
set_symmetric_difference_update(PySetObject *so, PyObject *other)
1619
{
1620 1621
	PySetObject *otherset;
	PyObject *key;
Martin v. Löwis's avatar
Martin v. Löwis committed
1622
	Py_ssize_t pos = 0;
1623 1624 1625 1626
	setentry *entry;

	if ((PyObject *)so == other)
		return set_clear(so);
1627

1628
	if (PyDict_CheckExact(other)) {
1629 1630
		PyObject *value;
		int rv;
1631 1632
		long hash;
		while (_PyDict_Next(other, &pos, &key, &value, &hash)) {
1633 1634 1635 1636 1637
			setentry an_entry;

			an_entry.hash = hash;
			an_entry.key = key;
			rv = set_discard_entry(so, &an_entry);
1638 1639 1640
			if (rv == -1)
				return NULL;
			if (rv == DISCARD_NOTFOUND) {
1641
				if (set_add_entry(so, &an_entry) == -1)
1642 1643 1644 1645 1646 1647
					return NULL;
			}
		}
		Py_RETURN_NONE;
	}

1648
	if (PyAnySet_Check(other)) {
1649 1650 1651
		Py_INCREF(other);
		otherset = (PySetObject *)other;
	} else {
1652
		otherset = (PySetObject *)make_new_set(Py_TYPE(so), other);
1653
		if (otherset == NULL)
1654
			return NULL;
1655
	}
1656

1657 1658
	while (set_next(otherset, &pos, &entry)) {
		int rv = set_discard_entry(so, entry);
1659
		if (rv == -1) {
1660
			Py_DECREF(otherset);
1661 1662 1663
			return NULL;
		}
		if (rv == DISCARD_NOTFOUND) {
1664
			if (set_add_entry(so, entry) == -1) {
1665
				Py_DECREF(otherset);
1666
				return NULL;
1667
			}
1668 1669
		}
	}
1670
	Py_DECREF(otherset);
1671
	Py_RETURN_NONE;
1672 1673
}

1674 1675
PyDoc_STRVAR(symmetric_difference_update_doc,
"Update a set with the symmetric difference of itself and another.");
1676 1677

static PyObject *
1678
set_symmetric_difference(PySetObject *so, PyObject *other)
1679
{
1680 1681
	PyObject *rv;
	PySetObject *otherset;
1682

1683
	otherset = (PySetObject *)make_new_set(Py_TYPE(so), other);
1684
	if (otherset == NULL)
1685
		return NULL;
1686 1687 1688 1689 1690
	rv = set_symmetric_difference_update(otherset, (PyObject *)so);
	if (rv == NULL)
		return NULL;
	Py_DECREF(rv);
	return (PyObject *)otherset;
1691 1692
}

1693 1694 1695 1696
PyDoc_STRVAR(symmetric_difference_doc,
"Return the symmetric difference of two sets as a new set.\n\
\n\
(i.e. all elements that are in exactly one of the sets.)");
1697 1698 1699 1700

static PyObject *
set_xor(PySetObject *so, PyObject *other)
{
1701
	if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
		Py_INCREF(Py_NotImplemented);
		return Py_NotImplemented;
	}
	return set_symmetric_difference(so, other);
}

static PyObject *
set_ixor(PySetObject *so, PyObject *other)
{
	PyObject *result;

1713
	if (!PyAnySet_Check(other)) {
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
		Py_INCREF(Py_NotImplemented);
		return Py_NotImplemented;
	}
	result = set_symmetric_difference_update(so, other);
	if (result == NULL)
		return NULL;
	Py_DECREF(result);
	Py_INCREF(so);
	return (PyObject *)so;
}

static PyObject *
set_issubset(PySetObject *so, PyObject *other)
{
1728
	setentry *entry;
Martin v. Löwis's avatar
Martin v. Löwis committed
1729
	Py_ssize_t pos = 0;
1730

1731
	if (!PyAnySet_Check(other)) {
1732
		PyObject *tmp, *result;
1733 1734 1735 1736 1737 1738
		tmp = make_new_set(&PySet_Type, other);
		if (tmp == NULL)
			return NULL;
		result = set_issubset(so, tmp);
		Py_DECREF(tmp);
		return result;
1739
	}
1740
	if (PySet_GET_SIZE(so) > PySet_GET_SIZE(other)) 
1741 1742
		Py_RETURN_FALSE;

1743
	while (set_next(so, &pos, &entry)) {
1744 1745 1746 1747
		int rv = set_contains_entry((PySetObject *)other, entry);
		if (rv == -1)
			return NULL;
		if (!rv)
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
			Py_RETURN_FALSE;
	}
	Py_RETURN_TRUE;
}

PyDoc_STRVAR(issubset_doc, "Report whether another set contains this set.");

static PyObject *
set_issuperset(PySetObject *so, PyObject *other)
{
1758 1759
	PyObject *tmp, *result;

1760
	if (!PyAnySet_Check(other)) {
1761 1762 1763 1764 1765 1766
		tmp = make_new_set(&PySet_Type, other);
		if (tmp == NULL)
			return NULL;
		result = set_issuperset(so, tmp);
		Py_DECREF(tmp);
		return result;
1767 1768 1769 1770 1771 1772 1773 1774 1775
	}
	return set_issubset((PySetObject *)other, (PyObject *)so);
}

PyDoc_STRVAR(issuperset_doc, "Report whether this set contains another set.");

static PyObject *
set_richcompare(PySetObject *v, PyObject *w, int op)
{
1776 1777
	PyObject *r1, *r2;

1778 1779 1780 1781 1782
	if(!PyAnySet_Check(w)) {
		if (op == Py_EQ)
			Py_RETURN_FALSE;
		if (op == Py_NE)
			Py_RETURN_TRUE;
1783 1784 1785 1786 1787
		PyErr_SetString(PyExc_TypeError, "can only compare to a set");
		return NULL;
	}
	switch (op) {
	case Py_EQ:
1788
		if (PySet_GET_SIZE(v) != PySet_GET_SIZE(w))
1789
			Py_RETURN_FALSE;
1790 1791 1792 1793
		if (v->hash != -1  &&
		    ((PySetObject *)w)->hash != -1 &&
		    v->hash != ((PySetObject *)w)->hash)
			Py_RETURN_FALSE;
1794
		return set_issubset(v, w);
1795
	case Py_NE:
1796 1797 1798
		r1 = set_richcompare(v, w, Py_EQ);
		if (r1 == NULL)
			return NULL;
1799 1800 1801
		r2 = PyBool_FromLong(PyObject_Not(r1));
		Py_DECREF(r1);
		return r2;
1802
	case Py_LE:
1803
		return set_issubset(v, w);
1804
	case Py_GE:
1805
		return set_issuperset(v, w);
1806
	case Py_LT:
1807
		if (PySet_GET_SIZE(v) >= PySet_GET_SIZE(w))
1808
			Py_RETURN_FALSE;		
1809
		return set_issubset(v, w);
1810
	case Py_GT:
1811
		if (PySet_GET_SIZE(v) <= PySet_GET_SIZE(w))
1812
			Py_RETURN_FALSE;
1813
		return set_issuperset(v, w);
1814 1815 1816 1817 1818
	}
	Py_INCREF(Py_NotImplemented);
	return Py_NotImplemented;
}

1819
static int
1820
set_nocmp(PyObject *self, PyObject *other)
1821 1822 1823 1824 1825
{
	PyErr_SetString(PyExc_TypeError, "cannot compare sets using cmp()");
	return -1;
}

1826
static PyObject *
Raymond Hettinger's avatar
Raymond Hettinger committed
1827
set_add(PySetObject *so, PyObject *key)
1828
{
1829
	if (set_add_key(so, key) == -1)
1830
		return NULL;
1831
	Py_RETURN_NONE;
1832 1833 1834 1835 1836 1837 1838
}

PyDoc_STRVAR(add_doc, 
"Add an element to a set.\n\
\n\
This has no effect if the element is already present.");

1839 1840 1841 1842 1843 1844 1845 1846
static int
set_contains(PySetObject *so, PyObject *key)
{
	PyObject *tmpkey;
	int rv;

	rv = set_contains_key(so, key);
	if (rv == -1) {
1847
		if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
			return -1;
		PyErr_Clear();
		tmpkey = make_new_set(&PyFrozenSet_Type, NULL);
		if (tmpkey == NULL)
			return -1;
		set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
		rv = set_contains(so, tmpkey);
		set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
		Py_DECREF(tmpkey);
	}
	return rv;
}

static PyObject *
set_direct_contains(PySetObject *so, PyObject *key)
{
	long result;

	result = set_contains(so, key);
	if (result == -1)
		return NULL;
	return PyBool_FromLong(result);
}

PyDoc_STRVAR(contains_doc, "x.__contains__(y) <==> y in x.");

1874
static PyObject *
Raymond Hettinger's avatar
Raymond Hettinger committed
1875
set_remove(PySetObject *so, PyObject *key)
1876
{
1877
	PyObject *tmpkey;
1878
	int rv;
1879

1880 1881
	rv = set_discard_key(so, key);
	if (rv == -1) {
1882
		if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
1883 1884
			return NULL;
		PyErr_Clear();
Raymond Hettinger's avatar
Raymond Hettinger committed
1885 1886
		tmpkey = make_new_set(&PyFrozenSet_Type, NULL);
		if (tmpkey == NULL)
1887
			return NULL;
1888
		set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
1889
		rv = set_discard_key(so, tmpkey);
1890
		set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
Raymond Hettinger's avatar
Raymond Hettinger committed
1891
		Py_DECREF(tmpkey);
1892 1893 1894 1895 1896
		if (rv == -1)
			return NULL;
	} 

	if (rv == DISCARD_NOTFOUND) {
1897
		set_key_error(key);
1898 1899
		return NULL;
	}
1900
	Py_RETURN_NONE;
1901 1902 1903 1904 1905 1906 1907 1908
}

PyDoc_STRVAR(remove_doc,
"Remove an element from a set; it must be a member.\n\
\n\
If the element is not a member, raise a KeyError.");

static PyObject *
Raymond Hettinger's avatar
Raymond Hettinger committed
1909
set_discard(PySetObject *so, PyObject *key)
1910
{
Raymond Hettinger's avatar
Raymond Hettinger committed
1911
	PyObject *tmpkey, *result;
1912
	int rv;
1913

1914 1915
	rv = set_discard_key(so, key);
	if (rv == -1) {
1916
		if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
1917 1918
			return NULL;
		PyErr_Clear();
Raymond Hettinger's avatar
Raymond Hettinger committed
1919 1920
		tmpkey = make_new_set(&PyFrozenSet_Type, NULL);
		if (tmpkey == NULL)
1921
			return NULL;
1922
		set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
Raymond Hettinger's avatar
Raymond Hettinger committed
1923
		result = set_discard(so, tmpkey);
1924
		set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
Raymond Hettinger's avatar
Raymond Hettinger committed
1925
		Py_DECREF(tmpkey);
1926 1927
		return result;
	}
1928
	Py_RETURN_NONE;
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
}

PyDoc_STRVAR(discard_doc,
"Remove an element from a set if it is a member.\n\
\n\
If the element is not a member, do nothing."); 

static PyObject *
set_reduce(PySetObject *so)
{
1939
	PyObject *keys=NULL, *args=NULL, *result=NULL, *dict=NULL;
1940

1941
	keys = PySequence_List((PyObject *)so);
1942 1943 1944 1945 1946
	if (keys == NULL)
		goto done;
	args = PyTuple_Pack(1, keys);
	if (args == NULL)
		goto done;
1947 1948 1949 1950 1951 1952
	dict = PyObject_GetAttrString((PyObject *)so, "__dict__");
	if (dict == NULL) {
		PyErr_Clear();
		dict = Py_None;
		Py_INCREF(dict);
	}
1953
	result = PyTuple_Pack(3, Py_TYPE(so), args, dict);
1954 1955 1956
done:
	Py_XDECREF(args);
	Py_XDECREF(keys);
1957
	Py_XDECREF(dict);
1958 1959 1960 1961 1962
	return result;
}

PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");

1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
static PyObject *
set_sizeof(PySetObject *so)
{
	Py_ssize_t res;

	res = sizeof(PySetObject);
	if (so->table != so->smalltable)
		res = res + (so->mask + 1) * sizeof(setentry);
	return PyInt_FromSsize_t(res);
}

PyDoc_STRVAR(sizeof_doc, "S.__sizeof__() -> size of S in memory, in bytes");
1975 1976 1977 1978 1979 1980 1981
static int
set_init(PySetObject *self, PyObject *args, PyObject *kwds)
{
	PyObject *iterable = NULL;

	if (!PyAnySet_Check(self))
		return -1;
1982
	if (!PyArg_UnpackTuple(args, Py_TYPE(self)->tp_name, 0, 1, &iterable))
1983
		return -1;
1984
	set_clear_internal(self);
1985 1986 1987
	self->hash = -1;
	if (iterable == NULL)
		return 0;
1988
	return set_update_internal(self, iterable);
1989 1990
}

1991
static PySequenceMethods set_as_sequence = {
1992
	set_len,			/* sq_length */
1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
	0,				/* sq_concat */
	0,				/* sq_repeat */
	0,				/* sq_item */
	0,				/* sq_slice */
	0,				/* sq_ass_item */
	0,				/* sq_ass_slice */
	(objobjproc)set_contains,	/* sq_contains */
};

/* set object ********************************************************/

2004 2005 2006 2007 2008 2009 2010
#ifdef Py_DEBUG
static PyObject *test_c_api(PySetObject *so);

PyDoc_STRVAR(test_c_api_doc, "Exercises C API.  Returns True.\n\
All is well if assertions don't fail.");
#endif

2011 2012 2013 2014 2015
static PyMethodDef set_methods[] = {
	{"add",		(PyCFunction)set_add,		METH_O,
	 add_doc},
	{"clear",	(PyCFunction)set_clear,		METH_NOARGS,
	 clear_doc},
2016
	{"__contains__",(PyCFunction)set_direct_contains,	METH_O | METH_COEXIST,
2017
	 contains_doc},
2018
	{"copy",	(PyCFunction)set_copy,		METH_NOARGS,
2019 2020 2021
	 copy_doc},
	{"discard",	(PyCFunction)set_discard,	METH_O,
	 discard_doc},
2022
	{"difference",	(PyCFunction)set_difference_multi,	METH_VARARGS,
2023
	 difference_doc},
2024
	{"difference_update",	(PyCFunction)set_difference_update,	METH_VARARGS,
2025
	 difference_update_doc},
2026
	{"intersection",(PyCFunction)set_intersection_multi,	METH_VARARGS,
2027
	 intersection_doc},
2028
	{"intersection_update",(PyCFunction)set_intersection_update_multi,	METH_VARARGS,
2029
	 intersection_update_doc},
Raymond Hettinger's avatar
Raymond Hettinger committed
2030 2031
	{"isdisjoint",	(PyCFunction)set_isdisjoint,	METH_O,
	 isdisjoint_doc},
2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
	{"issubset",	(PyCFunction)set_issubset,	METH_O,
	 issubset_doc},
	{"issuperset",	(PyCFunction)set_issuperset,	METH_O,
	 issuperset_doc},
	{"pop",		(PyCFunction)set_pop,		METH_NOARGS,
	 pop_doc},
	{"__reduce__",	(PyCFunction)set_reduce,	METH_NOARGS,
	 reduce_doc},
	{"remove",	(PyCFunction)set_remove,	METH_O,
	 remove_doc},
2042 2043
	{"__sizeof__",	(PyCFunction)set_sizeof,	METH_NOARGS,
	 sizeof_doc},
2044 2045 2046 2047
	{"symmetric_difference",(PyCFunction)set_symmetric_difference,	METH_O,
	 symmetric_difference_doc},
	{"symmetric_difference_update",(PyCFunction)set_symmetric_difference_update,	METH_O,
	 symmetric_difference_update_doc},
2048 2049 2050 2051
#ifdef Py_DEBUG
	{"test_c_api",	(PyCFunction)test_c_api,	METH_NOARGS,
	 test_c_api_doc},
#endif
2052
	{"union",	(PyCFunction)set_union,		METH_VARARGS,
2053
	 union_doc},
2054
	{"update",	(PyCFunction)set_update,	METH_VARARGS,
2055
	 update_doc},
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098
	{NULL,		NULL}	/* sentinel */
};

static PyNumberMethods set_as_number = {
	0,				/*nb_add*/
	(binaryfunc)set_sub,		/*nb_subtract*/
	0,				/*nb_multiply*/
	0,				/*nb_divide*/
	0,				/*nb_remainder*/
	0,				/*nb_divmod*/
	0,				/*nb_power*/
	0,				/*nb_negative*/
	0,				/*nb_positive*/
	0,				/*nb_absolute*/
	0,				/*nb_nonzero*/
	0,				/*nb_invert*/
	0,				/*nb_lshift*/
	0,				/*nb_rshift*/
	(binaryfunc)set_and,		/*nb_and*/
	(binaryfunc)set_xor,		/*nb_xor*/
	(binaryfunc)set_or,		/*nb_or*/
	0,				/*nb_coerce*/
	0,				/*nb_int*/
	0,				/*nb_long*/
	0,				/*nb_float*/
	0,				/*nb_oct*/
	0, 				/*nb_hex*/
	0,				/*nb_inplace_add*/
	(binaryfunc)set_isub,		/*nb_inplace_subtract*/
	0,				/*nb_inplace_multiply*/
	0,				/*nb_inplace_divide*/
	0,				/*nb_inplace_remainder*/
	0,				/*nb_inplace_power*/
	0,				/*nb_inplace_lshift*/
	0,				/*nb_inplace_rshift*/
	(binaryfunc)set_iand,		/*nb_inplace_and*/
	(binaryfunc)set_ixor,		/*nb_inplace_xor*/
	(binaryfunc)set_ior,		/*nb_inplace_or*/
};

PyDoc_STRVAR(set_doc,
"set(iterable) --> set object\n\
\n\
2099
Build an unordered collection of unique elements.");
2100 2101

PyTypeObject PySet_Type = {
2102
	PyVarObject_HEAD_INIT(&PyType_Type, 0)
2103 2104 2105 2106 2107 2108 2109 2110
	"set",				/* tp_name */
	sizeof(PySetObject),		/* tp_basicsize */
	0,				/* tp_itemsize */
	/* methods */
	(destructor)set_dealloc,	/* tp_dealloc */
	(printfunc)set_tp_print,	/* tp_print */
	0,				/* tp_getattr */
	0,				/* tp_setattr */
2111
	set_nocmp,			/* tp_compare */
2112 2113 2114 2115
	(reprfunc)set_repr,		/* tp_repr */
	&set_as_number,			/* tp_as_number */
	&set_as_sequence,		/* tp_as_sequence */
	0,				/* tp_as_mapping */
2116
	(hashfunc)PyObject_HashNotImplemented,	/* tp_hash */
2117 2118 2119 2120 2121
	0,				/* tp_call */
	0,				/* tp_str */
	PyObject_GenericGetAttr,	/* tp_getattro */
	0,				/* tp_setattro */
	0,				/* tp_as_buffer */
2122
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES |
2123
		Py_TPFLAGS_BASETYPE,	/* tp_flags */
2124
	set_doc,			/* tp_doc */
2125
	(traverseproc)set_traverse,	/* tp_traverse */
2126
	(inquiry)set_clear_internal,	/* tp_clear */
2127
	(richcmpfunc)set_richcompare,	/* tp_richcompare */
2128
	offsetof(PySetObject, weakreflist),	/* tp_weaklistoffset */
2129
	(getiterfunc)set_iter,	/* tp_iter */
2130 2131 2132 2133 2134 2135 2136 2137 2138
	0,				/* tp_iternext */
	set_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 */
2139
	(initproc)set_init,		/* tp_init */
2140 2141
	PyType_GenericAlloc,		/* tp_alloc */
	set_new,			/* tp_new */
2142
	PyObject_GC_Del,		/* tp_free */
2143 2144 2145 2146 2147 2148
};

/* frozenset object ********************************************************/


static PyMethodDef frozenset_methods[] = {
2149
	{"__contains__",(PyCFunction)set_direct_contains,	METH_O | METH_COEXIST,
2150
	 contains_doc},
2151
	{"copy",	(PyCFunction)frozenset_copy,	METH_NOARGS,
2152
	 copy_doc},
2153
	{"difference",	(PyCFunction)set_difference_multi,	METH_VARARGS,
2154
	 difference_doc},
2155
	{"intersection",(PyCFunction)set_intersection_multi,	METH_VARARGS,
2156
	 intersection_doc},
Raymond Hettinger's avatar
Raymond Hettinger committed
2157 2158
	{"isdisjoint",	(PyCFunction)set_isdisjoint,	METH_O,
	 isdisjoint_doc},
2159
	{"issubset",	(PyCFunction)set_issubset,	METH_O,
2160
	 issubset_doc},
2161
	{"issuperset",	(PyCFunction)set_issuperset,	METH_O,
2162 2163 2164
	 issuperset_doc},
	{"__reduce__",	(PyCFunction)set_reduce,	METH_NOARGS,
	 reduce_doc},
2165 2166
	{"__sizeof__",	(PyCFunction)set_sizeof,	METH_NOARGS,
	 sizeof_doc},
2167 2168
	{"symmetric_difference",(PyCFunction)set_symmetric_difference,	METH_O,
	 symmetric_difference_doc},
2169
	{"union",	(PyCFunction)set_union,		METH_VARARGS,
2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196
	 union_doc},
	{NULL,		NULL}	/* sentinel */
};

static PyNumberMethods frozenset_as_number = {
	0,				/*nb_add*/
	(binaryfunc)set_sub,		/*nb_subtract*/
	0,				/*nb_multiply*/
	0,				/*nb_divide*/
	0,				/*nb_remainder*/
	0,				/*nb_divmod*/
	0,				/*nb_power*/
	0,				/*nb_negative*/
	0,				/*nb_positive*/
	0,				/*nb_absolute*/
	0,				/*nb_nonzero*/
	0,				/*nb_invert*/
	0,				/*nb_lshift*/
	0,				/*nb_rshift*/
	(binaryfunc)set_and,		/*nb_and*/
	(binaryfunc)set_xor,		/*nb_xor*/
	(binaryfunc)set_or,		/*nb_or*/
};

PyDoc_STRVAR(frozenset_doc,
"frozenset(iterable) --> frozenset object\n\
\n\
2197
Build an immutable unordered collection of unique elements.");
2198 2199

PyTypeObject PyFrozenSet_Type = {
2200
	PyVarObject_HEAD_INIT(&PyType_Type, 0)
2201 2202
	"frozenset",			/* tp_name */
	sizeof(PySetObject),		/* tp_basicsize */
2203 2204
	0,				/* tp_itemsize */
	/* methods */
2205 2206 2207 2208
	(destructor)set_dealloc,	/* tp_dealloc */
	(printfunc)set_tp_print,	/* tp_print */
	0,				/* tp_getattr */
	0,				/* tp_setattr */
2209
	set_nocmp,			/* tp_compare */
2210 2211 2212 2213 2214 2215 2216 2217 2218 2219
	(reprfunc)set_repr,		/* tp_repr */
	&frozenset_as_number,		/* tp_as_number */
	&set_as_sequence,		/* tp_as_sequence */
	0,				/* tp_as_mapping */
	frozenset_hash,			/* tp_hash */
	0,				/* tp_call */
	0,				/* tp_str */
	PyObject_GenericGetAttr,	/* tp_getattro */
	0,				/* tp_setattro */
	0,				/* tp_as_buffer */
2220
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES |
2221
		Py_TPFLAGS_BASETYPE,	/* tp_flags */
2222
	frozenset_doc,			/* tp_doc */
2223
	(traverseproc)set_traverse,	/* tp_traverse */
2224
	(inquiry)set_clear_internal,	/* tp_clear */
2225
	(richcmpfunc)set_richcompare,	/* tp_richcompare */
2226
	offsetof(PySetObject, weakreflist),	/* tp_weaklistoffset */
2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238
	(getiterfunc)set_iter,		/* tp_iter */
	0,				/* tp_iternext */
	frozenset_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 */
	0,				/* tp_init */
	PyType_GenericAlloc,		/* tp_alloc */
2239
	frozenset_new,			/* tp_new */
2240
	PyObject_GC_Del,		/* tp_free */
2241
};
2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254


/***** C API functions *************************************************/

PyObject *
PySet_New(PyObject *iterable)
{
	return make_new_set(&PySet_Type, iterable);
}

PyObject *
PyFrozenSet_New(PyObject *iterable)
{
2255
	return make_new_set(&PyFrozenSet_Type, iterable);
2256 2257
}

2258
Py_ssize_t
2259 2260 2261 2262 2263 2264
PySet_Size(PyObject *anyset)
{
	if (!PyAnySet_Check(anyset)) {
		PyErr_BadInternalCall();
		return -1;
	}
2265
	return PySet_GET_SIZE(anyset);
2266 2267
}

2268 2269 2270
int
PySet_Clear(PyObject *set)
{
2271
	if (!PySet_Check(set)) {
2272 2273 2274 2275 2276 2277
		PyErr_BadInternalCall();
		return -1;
	}
	return set_clear_internal((PySetObject *)set);
}

2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288
int
PySet_Contains(PyObject *anyset, PyObject *key)
{
	if (!PyAnySet_Check(anyset)) {
		PyErr_BadInternalCall();
		return -1;
	}
	return set_contains_key((PySetObject *)anyset, key);
}

int
2289
PySet_Discard(PyObject *set, PyObject *key)
2290
{
2291
	if (!PySet_Check(set)) {
2292 2293 2294
		PyErr_BadInternalCall();
		return -1;
	}
2295
	return set_discard_key((PySetObject *)set, key);
2296 2297 2298
}

int
2299
PySet_Add(PyObject *anyset, PyObject *key)
2300
{
2301 2302
	if (!PySet_Check(anyset) && 
	    (!PyFrozenSet_Check(anyset) || Py_REFCNT(anyset) != 1)) {
2303 2304 2305
		PyErr_BadInternalCall();
		return -1;
	}
2306
	return set_add_key((PySetObject *)anyset, key);
2307 2308
}

2309
int
2310
_PySet_Next(PyObject *set, Py_ssize_t *pos, PyObject **key)
2311 2312 2313 2314 2315 2316 2317 2318 2319
{
	setentry *entry_ptr;

	if (!PyAnySet_Check(set)) {
		PyErr_BadInternalCall();
		return -1;
	}
	if (set_next((PySetObject *)set, pos, &entry_ptr) == 0)
		return 0;
2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
	*key = entry_ptr->key;
	return 1;
}

int
_PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, long *hash)
{
	setentry *entry;

	if (!PyAnySet_Check(set)) {
		PyErr_BadInternalCall();
		return -1;
	}
	if (set_next((PySetObject *)set, pos, &entry) == 0)
		return 0;
	*key = entry->key;
	*hash = entry->hash;
2337 2338 2339
	return 1;
}

2340 2341 2342
PyObject *
PySet_Pop(PyObject *set)
{
2343
	if (!PySet_Check(set)) {
2344 2345 2346 2347 2348
		PyErr_BadInternalCall();
		return NULL;
	}
	return set_pop((PySetObject *)set);
}
2349

2350 2351 2352
int
_PySet_Update(PyObject *set, PyObject *iterable)
{
2353
	if (!PySet_Check(set)) {
2354 2355 2356 2357 2358
		PyErr_BadInternalCall();
		return -1;
	}
	return set_update_internal((PySetObject *)set, iterable);
}
2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374

#ifdef Py_DEBUG

/* Test code to be called with any three element set. 
   Returns True and original set is restored. */

#define assertRaises(call_return_value, exception)		\
	do {							\
		assert(call_return_value);			\
		assert(PyErr_ExceptionMatches(exception));	\
		PyErr_Clear();					\
	} while(0)

static PyObject *
test_c_api(PySetObject *so)
{
Neal Norwitz's avatar
Neal Norwitz committed
2375
	Py_ssize_t count;
2376 2377
	char *s;
	Py_ssize_t i;
2378
	PyObject *elem=NULL, *dup=NULL, *t, *f, *dup2, *x;
2379
	PyObject *ob = (PyObject *)so;
2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409

	/* Verify preconditions and exercise type/size checks */
	assert(PyAnySet_Check(ob));
	assert(PyAnySet_CheckExact(ob));
	assert(!PyFrozenSet_CheckExact(ob));
	assert(PySet_Size(ob) == 3);
	assert(PySet_GET_SIZE(ob) == 3);

	/* Raise TypeError for non-iterable constructor arguments */
	assertRaises(PySet_New(Py_None) == NULL, PyExc_TypeError);
	assertRaises(PyFrozenSet_New(Py_None) == NULL, PyExc_TypeError);

	/* Raise TypeError for unhashable key */
	dup = PySet_New(ob);
	assertRaises(PySet_Discard(ob, dup) == -1, PyExc_TypeError);
	assertRaises(PySet_Contains(ob, dup) == -1, PyExc_TypeError);
	assertRaises(PySet_Add(ob, dup) == -1, PyExc_TypeError);

	/* Exercise successful pop, contains, add, and discard */
	elem = PySet_Pop(ob);
	assert(PySet_Contains(ob, elem) == 0);
	assert(PySet_GET_SIZE(ob) == 2);
	assert(PySet_Add(ob, elem) == 0);
	assert(PySet_Contains(ob, elem) == 1);
	assert(PySet_GET_SIZE(ob) == 3);
	assert(PySet_Discard(ob, elem) == 1);
	assert(PySet_GET_SIZE(ob) == 2);
	assert(PySet_Discard(ob, elem) == 0);
	assert(PySet_GET_SIZE(ob) == 2);

2410 2411 2412 2413 2414 2415 2416 2417 2418 2419
	/* Exercise clear */
	dup2 = PySet_New(dup);
	assert(PySet_Clear(dup2) == 0);
	assert(PySet_Size(dup2) == 0);
	Py_DECREF(dup2);

	/* Raise SystemError on clear or update of frozen set */
	f = PyFrozenSet_New(dup);
	assertRaises(PySet_Clear(f) == -1, PyExc_SystemError);
	assertRaises(_PySet_Update(f, dup) == -1, PyExc_SystemError);
2420 2421 2422 2423
	assert(PySet_Add(f, elem) == 0);
	Py_INCREF(f);
	assertRaises(PySet_Add(f, elem) == -1, PyExc_SystemError);
	Py_DECREF(f);
2424 2425 2426 2427
	Py_DECREF(f);

	/* Exercise direct iteration */
	i = 0, count = 0;
2428
	while (_PySet_Next((PyObject *)dup, &i, &x)) {
2429
		s = PyString_AsString(x);
2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442
		assert(s && (s[0] == 'a' || s[0] == 'b' || s[0] == 'c'));
		count++;
	}
	assert(count == 3);

	/* Exercise updates */
	dup2 = PySet_New(NULL);
	assert(_PySet_Update(dup2, dup) == 0);
	assert(PySet_Size(dup2) == 3);
	assert(_PySet_Update(dup2, dup) == 0);
	assert(PySet_Size(dup2) == 3);
	Py_DECREF(dup2);

2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457
	/* Raise SystemError when self argument is not a set or frozenset. */
	t = PyTuple_New(0);
	assertRaises(PySet_Size(t) == -1, PyExc_SystemError);
	assertRaises(PySet_Contains(t, elem) == -1, PyExc_SystemError);
	Py_DECREF(t);

	/* Raise SystemError when self argument is not a set. */
	f = PyFrozenSet_New(dup);
	assert(PySet_Size(f) == 3);
	assert(PyFrozenSet_CheckExact(f));
	assertRaises(PySet_Discard(f, elem) == -1, PyExc_SystemError);
	assertRaises(PySet_Pop(f) == NULL, PyExc_SystemError);
	Py_DECREF(f);

	/* Raise KeyError when popping from an empty set */
2458 2459
	assert(PyNumber_InPlaceSubtract(ob, ob) == ob);
	Py_DECREF(ob);
2460 2461 2462
	assert(PySet_GET_SIZE(ob) == 0);
	assertRaises(PySet_Pop(ob) == NULL, PyExc_KeyError);

2463 2464 2465
	/* Restore the set from the copy using the PyNumber API */
	assert(PyNumber_InPlaceOr(ob, dup) == ob);
	Py_DECREF(ob);
2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482

	/* Verify constructors accept NULL arguments */
	f = PySet_New(NULL);
	assert(f != NULL);
	assert(PySet_GET_SIZE(f) == 0);
	Py_DECREF(f);
	f = PyFrozenSet_New(NULL);
	assert(f != NULL);
	assert(PyFrozenSet_CheckExact(f));
	assert(PySet_GET_SIZE(f) == 0);
	Py_DECREF(f);

	Py_DECREF(elem);
	Py_DECREF(dup);
	Py_RETURN_TRUE;
}

2483 2484
#undef assertRaises

2485
#endif