2 /* set object implementation
3 Written and maintained by Raymond D. Hettinger <python@rcn.com>
4 Derived from Lib/sets.py and Objects/dictobject.c.
6 Copyright (c) 2003-2007 Python Software Foundation.
11 #include "structmember.h"
13 /* Set a key error with the specified argument, wrapping it in a
14 * tuple automatically so that tuple keys are not unpacked as the
15 * exception arguments. */
17 set_key_error(PyObject *arg)
20 tup = PyTuple_Pack(1, arg);
22 return; /* caller will expect error to be set anyway */
23 PyErr_SetObject(PyExc_KeyError, tup);
27 /* This must be >= 1. */
28 #define PERTURB_SHIFT 5
30 /* Object used as dummy key to fill deleted entries */
31 static PyObject *dummy = NULL; /* Initialized by first call to make_new_set() */
41 #define INIT_NONZERO_SET_SLOTS(so) do { \
42 (so)->table = (so)->smalltable; \
43 (so)->mask = PySet_MINSIZE - 1; \
47 #define EMPTY_TO_MINSIZE(so) do { \
48 memset((so)->smalltable, 0, sizeof((so)->smalltable)); \
49 (so)->used = (so)->fill = 0; \
50 INIT_NONZERO_SET_SLOTS(so); \
53 /* Reuse scheme to save calls to malloc, free, and memset */
54 #ifndef PySet_MAXFREELIST
55 #define PySet_MAXFREELIST 80
57 static PySetObject *free_list[PySet_MAXFREELIST];
58 static int numfree = 0;
61 The basic lookup function used by all operations.
62 This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
63 Open addressing is preferred over chaining since the link overhead for
64 chaining would be substantial (100% with typical malloc overhead).
66 The initial probe index is computed as hash mod the table size. Subsequent
67 probe indices are computed as explained in Objects/dictobject.c.
69 All arithmetic on hash should ignore overflow.
71 Unlike the dictionary implementation, the lookkey functions can return
72 NULL if the rich comparison returns an error.
76 set_lookkey(PySetObject *so, PyObject *key, register long hash)
78 register Py_ssize_t i;
79 register size_t perturb;
80 register setentry *freeslot;
81 register size_t mask = so->mask;
82 setentry *table = so->table;
83 register setentry *entry;
89 if (entry->key == NULL || entry->key == key)
92 if (entry->key == dummy)
95 if (entry->hash == hash) {
96 startkey = entry->key;
98 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
102 if (table == so->table && entry->key == startkey) {
107 /* The compare did major nasty stuff to the
110 return set_lookkey(so, key, hash);
116 /* In the loop, key == dummy is by far (factor of 100s) the
117 least likely outcome, so test for that last. */
118 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
119 i = (i << 2) + i + perturb + 1;
120 entry = &table[i & mask];
121 if (entry->key == NULL) {
122 if (freeslot != NULL)
126 if (entry->key == key)
128 if (entry->hash == hash && entry->key != dummy) {
129 startkey = entry->key;
131 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
135 if (table == so->table && entry->key == startkey) {
140 /* The compare did major nasty stuff to the
143 return set_lookkey(so, key, hash);
146 else if (entry->key == dummy && freeslot == NULL)
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.
158 set_lookkey_string(PySetObject *so, PyObject *key, register long hash)
160 register Py_ssize_t i;
161 register size_t perturb;
162 register setentry *freeslot;
163 register size_t mask = so->mask;
164 setentry *table = so->table;
165 register setentry *entry;
167 /* Make sure this function doesn't have to handle non-string keys,
168 including subclasses of str; e.g., one reason to subclass
169 strings is to override __eq__, and for speed we don't cater to
171 if (!PyString_CheckExact(key)) {
172 so->lookup = set_lookkey;
173 return set_lookkey(so, key, hash);
177 if (entry->key == NULL || entry->key == key)
179 if (entry->key == dummy)
182 if (entry->hash == hash && _PyString_Eq(entry->key, key))
187 /* In the loop, key == dummy is by far (factor of 100s) the
188 least likely outcome, so test for that last. */
189 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
190 i = (i << 2) + i + perturb + 1;
191 entry = &table[i & mask];
192 if (entry->key == NULL)
193 return freeslot == NULL ? entry : freeslot;
194 if (entry->key == key
195 || (entry->hash == hash
196 && entry->key != dummy
197 && _PyString_Eq(entry->key, key)))
199 if (entry->key == dummy && freeslot == NULL)
202 assert(0); /* NOT REACHED */
207 Internal routine to insert a new key into the table.
208 Used by the public insert routine.
209 Eats a reference to key.
212 set_insert_key(register PySetObject *so, PyObject *key, long hash)
214 register setentry *entry;
215 typedef setentry *(*lookupfunc)(PySetObject *, PyObject *, long);
217 assert(so->lookup != NULL);
218 entry = so->lookup(so, key, hash);
221 if (entry->key == NULL) {
227 } else if (entry->key == dummy) {
241 Internal routine used by set_table_resize() to insert an item which is
242 known to be absent from the set. This routine also assumes that
243 the set contains no deleted entries. Besides the performance benefit,
244 using set_insert_clean() in set_table_resize() is dangerous (SF bug #1456209).
245 Note that no refcounts are changed by this routine; if needed, the caller
246 is responsible for incref'ing `key`.
249 set_insert_clean(register PySetObject *so, PyObject *key, long hash)
252 register size_t perturb;
253 register size_t mask = (size_t)so->mask;
254 setentry *table = so->table;
255 register setentry *entry;
259 for (perturb = hash; entry->key != NULL; perturb >>= PERTURB_SHIFT) {
260 i = (i << 2) + i + perturb + 1;
261 entry = &table[i & mask];
270 Restructure the table by allocating a new table and reinserting all
271 keys again. When entries have been deleted, the new table may
272 actually be smaller than the old one.
275 set_table_resize(PySetObject *so, Py_ssize_t minused)
278 setentry *oldtable, *newtable, *entry;
280 int is_oldtable_malloced;
281 setentry small_copy[PySet_MINSIZE];
283 assert(minused >= 0);
285 /* Find the smallest table size > minused. */
286 for (newsize = PySet_MINSIZE;
287 newsize <= minused && newsize > 0;
295 /* Get space for a new table. */
296 oldtable = so->table;
297 assert(oldtable != NULL);
298 is_oldtable_malloced = oldtable != so->smalltable;
300 if (newsize == PySet_MINSIZE) {
301 /* A large table is shrinking, or we can't get any smaller. */
302 newtable = so->smalltable;
303 if (newtable == oldtable) {
304 if (so->fill == so->used) {
305 /* No dummies, so no point doing anything. */
308 /* We're not going to resize it, but rebuild the
309 table anyway to purge old dummy entries.
310 Subtle: This is *necessary* if fill==size,
311 as set_lookkey needs at least one virgin slot to
312 terminate failing searches. If fill < size, it's
313 merely desirable, as dummies slow searches. */
314 assert(so->fill > so->used);
315 memcpy(small_copy, oldtable, sizeof(small_copy));
316 oldtable = small_copy;
320 newtable = PyMem_NEW(setentry, newsize);
321 if (newtable == NULL) {
327 /* Make the set empty, using the new table. */
328 assert(newtable != oldtable);
329 so->table = newtable;
330 so->mask = newsize - 1;
331 memset(newtable, 0, sizeof(setentry) * newsize);
336 /* Copy the data over; this is refcount-neutral for active entries;
337 dummy entries aren't copied over, of course */
338 for (entry = oldtable; i > 0; entry++) {
339 if (entry->key == NULL) {
342 } else if (entry->key == dummy) {
345 assert(entry->key == dummy);
346 Py_DECREF(entry->key);
350 set_insert_clean(so, entry->key, entry->hash);
354 if (is_oldtable_malloced)
359 /* CAUTION: set_add_key/entry() must guarantee it won't resize the table */
362 set_add_entry(register PySetObject *so, setentry *entry)
364 register Py_ssize_t n_used;
365 PyObject *key = entry->key;
366 long hash = entry->hash;
368 assert(so->fill <= so->mask); /* at least one empty slot */
371 if (set_insert_key(so, key, hash) == -1) {
375 if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2))
377 return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
381 set_add_key(register PySetObject *so, PyObject *key)
384 register Py_ssize_t n_used;
386 if (!PyString_CheckExact(key) ||
387 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
388 hash = PyObject_Hash(key);
392 assert(so->fill <= so->mask); /* at least one empty slot */
395 if (set_insert_key(so, key, hash) == -1) {
399 if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2))
401 return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
404 #define DISCARD_NOTFOUND 0
405 #define DISCARD_FOUND 1
408 set_discard_entry(PySetObject *so, setentry *oldentry)
409 { register setentry *entry;
412 entry = (so->lookup)(so, oldentry->key, oldentry->hash);
415 if (entry->key == NULL || entry->key == dummy)
416 return DISCARD_NOTFOUND;
417 old_key = entry->key;
422 return DISCARD_FOUND;
426 set_discard_key(PySetObject *so, PyObject *key)
429 register setentry *entry;
432 assert (PyAnySet_Check(so));
433 if (!PyString_CheckExact(key) ||
434 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
435 hash = PyObject_Hash(key);
439 entry = (so->lookup)(so, key, hash);
442 if (entry->key == NULL || entry->key == dummy)
443 return DISCARD_NOTFOUND;
444 old_key = entry->key;
449 return DISCARD_FOUND;
453 set_clear_internal(PySetObject *so)
455 setentry *entry, *table;
456 int table_is_malloced;
458 setentry small_copy[PySet_MINSIZE];
461 assert (PyAnySet_Check(so));
468 assert(table != NULL);
469 table_is_malloced = table != so->smalltable;
471 /* This is delicate. During the process of clearing the set,
472 * decrefs can cause the set to mutate. To avoid fatal confusion
473 * (voice of experience), we have to make the set empty before
474 * clearing the slots, and never refer to anything via so->ref while
478 if (table_is_malloced)
479 EMPTY_TO_MINSIZE(so);
482 /* It's a small table with something that needs to be cleared.
483 * Afraid the only safe way is to copy the set entries into
484 * another small table first.
486 memcpy(small_copy, table, sizeof(small_copy));
488 EMPTY_TO_MINSIZE(so);
490 /* else it's a small table that's already empty */
492 /* Now we can finally clear things. If C had refcounts, we could
493 * assert that the refcount on table is 1 now, i.e. that this function
494 * has unique access to it, so decref side-effects can't alter it.
496 for (entry = table; fill > 0; ++entry) {
503 Py_DECREF(entry->key);
507 assert(entry->key == NULL);
511 if (table_is_malloced)
517 * Iterate over a set table. Use like so:
521 * pos = 0; # important! pos should not otherwise be changed by you
522 * while (set_next(yourset, &pos, &entry)) {
523 * Refer to borrowed reference in entry->key.
526 * CAUTION: In general, it isn't safe to use set_next in a loop that
530 set_next(PySetObject *so, Py_ssize_t *pos_ptr, setentry **entry_ptr)
534 register setentry *table;
536 assert (PyAnySet_Check(so));
541 while (i <= mask && (table[i].key == NULL || table[i].key == dummy))
546 assert(table[i].key != NULL);
547 *entry_ptr = &table[i];
552 set_dealloc(PySetObject *so)
554 register setentry *entry;
555 Py_ssize_t fill = so->fill;
556 PyObject_GC_UnTrack(so);
557 Py_TRASHCAN_SAFE_BEGIN(so)
558 if (so->weakreflist != NULL)
559 PyObject_ClearWeakRefs((PyObject *) so);
561 for (entry = so->table; fill > 0; entry++) {
564 Py_DECREF(entry->key);
567 if (so->table != so->smalltable)
568 PyMem_DEL(so->table);
569 if (numfree < PySet_MAXFREELIST && PyAnySet_CheckExact(so))
570 free_list[numfree++] = so;
572 Py_TYPE(so)->tp_free(so);
573 Py_TRASHCAN_SAFE_END(so)
577 set_tp_print(PySetObject *so, FILE *fp, int flags)
581 char *emit = ""; /* No separator emitted on first pass */
582 char *separator = ", ";
583 int status = Py_ReprEnter((PyObject*)so);
588 Py_BEGIN_ALLOW_THREADS
589 fprintf(fp, "%s(...)", so->ob_type->tp_name);
594 Py_BEGIN_ALLOW_THREADS
595 fprintf(fp, "%s([", so->ob_type->tp_name);
597 while (set_next(so, &pos, &entry)) {
598 Py_BEGIN_ALLOW_THREADS
602 if (PyObject_Print(entry->key, fp, 0) != 0) {
603 Py_ReprLeave((PyObject*)so);
607 Py_BEGIN_ALLOW_THREADS
610 Py_ReprLeave((PyObject*)so);
615 set_repr(PySetObject *so)
617 PyObject *keys, *result=NULL, *listrepr;
618 int status = Py_ReprEnter((PyObject*)so);
623 return PyString_FromFormat("%s(...)", so->ob_type->tp_name);
626 keys = PySequence_List((PyObject *)so);
629 listrepr = PyObject_Repr(keys);
631 if (listrepr == NULL)
634 result = PyString_FromFormat("%s(%s)", so->ob_type->tp_name,
635 PyString_AS_STRING(listrepr));
638 Py_ReprLeave((PyObject*)so);
643 set_len(PyObject *so)
645 return ((PySetObject *)so)->used;
649 set_merge(PySetObject *so, PyObject *otherset)
654 register Py_ssize_t i;
655 register setentry *entry;
657 assert (PyAnySet_Check(so));
658 assert (PyAnySet_Check(otherset));
660 other = (PySetObject*)otherset;
661 if (other == so || other->used == 0)
662 /* a.update(a) or a.update({}); nothing to do */
664 /* Do one big resize at the start, rather than
665 * incrementally resizing as we insert new keys. Expect
666 * that there will be no (or few) overlapping keys.
668 if ((so->fill + other->used)*3 >= (so->mask+1)*2) {
669 if (set_table_resize(so, (so->used + other->used)*2) != 0)
672 for (i = 0; i <= other->mask; i++) {
673 entry = &other->table[i];
679 if (set_insert_key(so, key, hash) == -1) {
689 set_contains_key(PySetObject *so, PyObject *key)
694 if (!PyString_CheckExact(key) ||
695 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
696 hash = PyObject_Hash(key);
700 entry = (so->lookup)(so, key, hash);
704 return key != NULL && key != dummy;
708 set_contains_entry(PySetObject *so, setentry *entry)
713 lu_entry = (so->lookup)(so, entry->key, entry->hash);
714 if (lu_entry == NULL)
717 return key != NULL && key != dummy;
721 set_pop(PySetObject *so)
723 register Py_ssize_t i = 0;
724 register setentry *entry;
727 assert (PyAnySet_Check(so));
729 PyErr_SetString(PyExc_KeyError, "pop from an empty set");
733 /* Set entry to "the first" unused or dummy set entry. We abuse
734 * the hash field of slot 0 to hold a search finger:
735 * If slot 0 has a value, use slot 0.
736 * Else slot 0 is being used to hold a search finger,
737 * and we use its hash value as the first index to look.
739 entry = &so->table[0];
740 if (entry->key == NULL || entry->key == dummy) {
742 /* The hash field may be a real hash value, or it may be a
743 * legit search finger, or it may be a once-legit search
744 * finger that's out of bounds now because it wrapped around
745 * or the table shrunk -- simply make sure it's in bounds now.
747 if (i > so->mask || i < 1)
748 i = 1; /* skip slot 0 */
749 while ((entry = &so->table[i])->key == NULL || entry->key==dummy) {
759 so->table[0].hash = i + 1; /* next place to start */
763 PyDoc_STRVAR(pop_doc, "Remove and return an arbitrary set element.\n\
764 Raises KeyError if the set is empty.");
767 set_traverse(PySetObject *so, visitproc visit, void *arg)
772 while (set_next(so, &pos, &entry))
773 Py_VISIT(entry->key);
778 frozenset_hash(PyObject *self)
780 PySetObject *so = (PySetObject *)self;
781 long h, hash = 1927868237L;
788 hash *= PySet_GET_SIZE(self) + 1;
789 while (set_next(so, &pos, &entry)) {
790 /* Work to increase the bit dispersion for closely spaced hash
791 values. The is important because some use cases have many
792 combinations of a small number of elements with nearby
793 hashes so that many distinct combinations collapse to only
794 a handful of distinct hash values. */
796 hash ^= (h ^ (h << 16) ^ 89869747L) * 3644798167u;
798 hash = hash * 69069L + 907133923L;
805 /***** Set iterator type ***********************************************/
809 PySetObject *si_set; /* Set to NULL when iterator is exhausted */
816 setiter_dealloc(setiterobject *si)
818 Py_XDECREF(si->si_set);
823 setiter_traverse(setiterobject *si, visitproc visit, void *arg)
825 Py_VISIT(si->si_set);
830 setiter_len(setiterobject *si)
833 if (si->si_set != NULL && si->si_used == si->si_set->used)
835 return PyInt_FromLong(len);
838 PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
840 static PyMethodDef setiter_methods[] = {
841 {"__length_hint__", (PyCFunction)setiter_len, METH_NOARGS, length_hint_doc},
842 {NULL, NULL} /* sentinel */
845 static PyObject *setiter_iternext(setiterobject *si)
848 register Py_ssize_t i, mask;
849 register setentry *entry;
850 PySetObject *so = si->si_set;
854 assert (PyAnySet_Check(so));
856 if (si->si_used != so->used) {
857 PyErr_SetString(PyExc_RuntimeError,
858 "Set changed size during iteration");
859 si->si_used = -1; /* Make this state sticky */
867 while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy))
883 static PyTypeObject PySetIter_Type = {
884 PyVarObject_HEAD_INIT(&PyType_Type, 0)
885 "setiterator", /* tp_name */
886 sizeof(setiterobject), /* tp_basicsize */
889 (destructor)setiter_dealloc, /* tp_dealloc */
895 0, /* tp_as_number */
896 0, /* tp_as_sequence */
897 0, /* tp_as_mapping */
901 PyObject_GenericGetAttr, /* tp_getattro */
903 0, /* tp_as_buffer */
904 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
906 (traverseproc)setiter_traverse, /* tp_traverse */
908 0, /* tp_richcompare */
909 0, /* tp_weaklistoffset */
910 PyObject_SelfIter, /* tp_iter */
911 (iternextfunc)setiter_iternext, /* tp_iternext */
912 setiter_methods, /* tp_methods */
917 set_iter(PySetObject *so)
919 setiterobject *si = PyObject_GC_New(setiterobject, &PySetIter_Type);
924 si->si_used = so->used;
927 _PyObject_GC_TRACK(si);
928 return (PyObject *)si;
932 set_update_internal(PySetObject *so, PyObject *other)
936 if (PyAnySet_Check(other))
937 return set_merge(so, other);
939 if (PyDict_CheckExact(other)) {
943 Py_ssize_t dictsize = PyDict_Size(other);
945 /* Do one big resize at the start, rather than
946 * incrementally resizing as we insert new keys. Expect
947 * that there will be no (or few) overlapping keys.
951 if ((so->fill + dictsize)*3 >= (so->mask+1)*2) {
952 if (set_table_resize(so, (so->used + dictsize)*2) != 0)
955 while (_PyDict_Next(other, &pos, &key, &value, &hash)) {
958 an_entry.hash = hash;
960 if (set_add_entry(so, &an_entry) == -1)
966 it = PyObject_GetIter(other);
970 while ((key = PyIter_Next(it)) != NULL) {
971 if (set_add_key(so, key) == -1) {
979 if (PyErr_Occurred())
985 set_update(PySetObject *so, PyObject *args)
989 for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
990 PyObject *other = PyTuple_GET_ITEM(args, i);
991 if (set_update_internal(so, other) == -1)
997 PyDoc_STRVAR(update_doc,
998 "Update a set with the union of itself and others.");
1001 make_new_set(PyTypeObject *type, PyObject *iterable)
1003 register PySetObject *so = NULL;
1005 if (dummy == NULL) { /* Auto-initialize dummy */
1006 dummy = PyString_FromString("<dummy key>");
1011 /* create PySetObject structure */
1013 (type == &PySet_Type || type == &PyFrozenSet_Type)) {
1014 so = free_list[--numfree];
1015 assert (so != NULL && PyAnySet_CheckExact(so));
1017 _Py_NewReference((PyObject *)so);
1018 EMPTY_TO_MINSIZE(so);
1019 PyObject_GC_Track(so);
1021 so = (PySetObject *)type->tp_alloc(type, 0);
1024 /* tp_alloc has already zeroed the structure */
1025 assert(so->table == NULL && so->fill == 0 && so->used == 0);
1026 INIT_NONZERO_SET_SLOTS(so);
1029 so->lookup = set_lookkey_string;
1030 so->weakreflist = NULL;
1032 if (iterable != NULL) {
1033 if (set_update_internal(so, iterable) == -1) {
1039 return (PyObject *)so;
1042 /* The empty frozenset is a singleton */
1043 static PyObject *emptyfrozenset = NULL;
1046 frozenset_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1048 PyObject *iterable = NULL, *result;
1050 if (type == &PyFrozenSet_Type && !_PyArg_NoKeywords("frozenset()", kwds))
1053 if (!PyArg_UnpackTuple(args, type->tp_name, 0, 1, &iterable))
1056 if (type != &PyFrozenSet_Type)
1057 return make_new_set(type, iterable);
1059 if (iterable != NULL) {
1060 /* frozenset(f) is idempotent */
1061 if (PyFrozenSet_CheckExact(iterable)) {
1062 Py_INCREF(iterable);
1065 result = make_new_set(type, iterable);
1066 if (result == NULL || PySet_GET_SIZE(result))
1070 /* The empty frozenset is a singleton */
1071 if (emptyfrozenset == NULL)
1072 emptyfrozenset = make_new_set(type, NULL);
1073 Py_XINCREF(emptyfrozenset);
1074 return emptyfrozenset;
1084 so = free_list[numfree];
1085 PyObject_GC_Del(so);
1088 Py_CLEAR(emptyfrozenset);
1092 set_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1094 if (type == &PySet_Type && !_PyArg_NoKeywords("set()", kwds))
1097 return make_new_set(type, NULL);
1100 /* set_swap_bodies() switches the contents of any two sets by moving their
1101 internal data pointers and, if needed, copying the internal smalltables.
1102 Semantically equivalent to:
1104 t=set(a); a.clear(); a.update(b); b.clear(); b.update(t); del t
1106 The function always succeeds and it leaves both objects in a stable state.
1107 Useful for creating temporary frozensets from sets for membership testing
1108 in __contains__(), discard(), and remove(). Also useful for operations
1109 that update in-place (by allowing an intermediate result to be swapped
1110 into one of the original inputs).
1114 set_swap_bodies(PySetObject *a, PySetObject *b)
1118 setentry *(*f)(PySetObject *so, PyObject *key, long hash);
1119 setentry tab[PySet_MINSIZE];
1122 t = a->fill; a->fill = b->fill; b->fill = t;
1123 t = a->used; a->used = b->used; b->used = t;
1124 t = a->mask; a->mask = b->mask; b->mask = t;
1127 if (a->table == a->smalltable)
1129 a->table = b->table;
1130 if (b->table == b->smalltable)
1131 a->table = a->smalltable;
1134 f = a->lookup; a->lookup = b->lookup; b->lookup = f;
1136 if (a->table == a->smalltable || b->table == b->smalltable) {
1137 memcpy(tab, a->smalltable, sizeof(tab));
1138 memcpy(a->smalltable, b->smalltable, sizeof(tab));
1139 memcpy(b->smalltable, tab, sizeof(tab));
1142 if (PyType_IsSubtype(Py_TYPE(a), &PyFrozenSet_Type) &&
1143 PyType_IsSubtype(Py_TYPE(b), &PyFrozenSet_Type)) {
1144 h = a->hash; a->hash = b->hash; b->hash = h;
1152 set_copy(PySetObject *so)
1154 return make_new_set(Py_TYPE(so), (PyObject *)so);
1158 frozenset_copy(PySetObject *so)
1160 if (PyFrozenSet_CheckExact(so)) {
1162 return (PyObject *)so;
1164 return set_copy(so);
1167 PyDoc_STRVAR(copy_doc, "Return a shallow copy of a set.");
1170 set_clear(PySetObject *so)
1172 set_clear_internal(so);
1176 PyDoc_STRVAR(clear_doc, "Remove all elements from this set.");
1179 set_union(PySetObject *so, PyObject *args)
1181 PySetObject *result;
1185 result = (PySetObject *)set_copy(so);
1189 for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
1190 other = PyTuple_GET_ITEM(args, i);
1191 if ((PyObject *)so == other)
1193 if (set_update_internal(result, other) == -1) {
1198 return (PyObject *)result;
1201 PyDoc_STRVAR(union_doc,
1202 "Return the union of sets as a new set.\n\
1204 (i.e. all elements that are in either set.)");
1207 set_or(PySetObject *so, PyObject *other)
1209 PySetObject *result;
1211 if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
1212 Py_INCREF(Py_NotImplemented);
1213 return Py_NotImplemented;
1216 result = (PySetObject *)set_copy(so);
1219 if ((PyObject *)so == other)
1220 return (PyObject *)result;
1221 if (set_update_internal(result, other) == -1) {
1225 return (PyObject *)result;
1229 set_ior(PySetObject *so, PyObject *other)
1231 if (!PyAnySet_Check(other)) {
1232 Py_INCREF(Py_NotImplemented);
1233 return Py_NotImplemented;
1235 if (set_update_internal(so, other) == -1)
1238 return (PyObject *)so;
1242 set_intersection(PySetObject *so, PyObject *other)
1244 PySetObject *result;
1245 PyObject *key, *it, *tmp;
1247 if ((PyObject *)so == other)
1248 return set_copy(so);
1250 result = (PySetObject *)make_new_set(Py_TYPE(so), NULL);
1254 if (PyAnySet_Check(other)) {
1258 if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) {
1259 tmp = (PyObject *)so;
1260 so = (PySetObject *)other;
1264 while (set_next((PySetObject *)other, &pos, &entry)) {
1265 int rv = set_contains_entry(so, entry);
1271 if (set_add_entry(result, entry) == -1) {
1277 return (PyObject *)result;
1280 it = PyObject_GetIter(other);
1286 while ((key = PyIter_Next(it)) != NULL) {
1289 long hash = PyObject_Hash(key);
1299 rv = set_contains_entry(so, &entry);
1307 if (set_add_entry(result, &entry) == -1) {
1317 if (PyErr_Occurred()) {
1321 return (PyObject *)result;
1325 set_intersection_multi(PySetObject *so, PyObject *args)
1328 PyObject *result = (PyObject *)so;
1330 if (PyTuple_GET_SIZE(args) == 0)
1331 return set_copy(so);
1334 for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
1335 PyObject *other = PyTuple_GET_ITEM(args, i);
1336 PyObject *newresult = set_intersection((PySetObject *)result, other);
1337 if (newresult == NULL) {
1347 PyDoc_STRVAR(intersection_doc,
1348 "Return the intersection of two or more sets as a new set.\n\
1350 (i.e. elements that are common to all of the sets.)");
1353 set_intersection_update(PySetObject *so, PyObject *other)
1357 tmp = set_intersection(so, other);
1360 set_swap_bodies(so, (PySetObject *)tmp);
1366 set_intersection_update_multi(PySetObject *so, PyObject *args)
1370 tmp = set_intersection_multi(so, args);
1373 set_swap_bodies(so, (PySetObject *)tmp);
1378 PyDoc_STRVAR(intersection_update_doc,
1379 "Update a set with the intersection of itself and another.");
1382 set_and(PySetObject *so, PyObject *other)
1384 if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
1385 Py_INCREF(Py_NotImplemented);
1386 return Py_NotImplemented;
1388 return set_intersection(so, other);
1392 set_iand(PySetObject *so, PyObject *other)
1396 if (!PyAnySet_Check(other)) {
1397 Py_INCREF(Py_NotImplemented);
1398 return Py_NotImplemented;
1400 result = set_intersection_update(so, other);
1405 return (PyObject *)so;
1409 set_isdisjoint(PySetObject *so, PyObject *other)
1411 PyObject *key, *it, *tmp;
1413 if ((PyObject *)so == other) {
1414 if (PySet_GET_SIZE(so) == 0)
1420 if (PyAnySet_CheckExact(other)) {
1424 if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) {
1425 tmp = (PyObject *)so;
1426 so = (PySetObject *)other;
1429 while (set_next((PySetObject *)other, &pos, &entry)) {
1430 int rv = set_contains_entry(so, entry);
1439 it = PyObject_GetIter(other);
1443 while ((key = PyIter_Next(it)) != NULL) {
1446 long hash = PyObject_Hash(key);
1455 rv = set_contains_entry(so, &entry);
1467 if (PyErr_Occurred())
1472 PyDoc_STRVAR(isdisjoint_doc,
1473 "Return True if two sets have a null intersection.");
1476 set_difference_update_internal(PySetObject *so, PyObject *other)
1478 if ((PyObject *)so == other)
1479 return set_clear_internal(so);
1481 if (PyAnySet_Check(other)) {
1485 while (set_next((PySetObject *)other, &pos, &entry))
1486 if (set_discard_entry(so, entry) == -1)
1490 it = PyObject_GetIter(other);
1494 while ((key = PyIter_Next(it)) != NULL) {
1495 if (set_discard_key(so, key) == -1) {
1503 if (PyErr_Occurred())
1506 /* If more than 1/5 are dummies, then resize them away. */
1507 if ((so->fill - so->used) * 5 < so->mask)
1509 return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
1513 set_difference_update(PySetObject *so, PyObject *args)
1517 for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
1518 PyObject *other = PyTuple_GET_ITEM(args, i);
1519 if (set_difference_update_internal(so, other) == -1)
1525 PyDoc_STRVAR(difference_update_doc,
1526 "Remove all elements of another set from this set.");
1529 set_difference(PySetObject *so, PyObject *other)
1535 if (!PyAnySet_Check(other) && !PyDict_CheckExact(other)) {
1536 result = set_copy(so);
1539 if (set_difference_update_internal((PySetObject *)result, other) != -1)
1545 result = make_new_set(Py_TYPE(so), NULL);
1549 if (PyDict_CheckExact(other)) {
1550 while (set_next(so, &pos, &entry)) {
1552 entrycopy.hash = entry->hash;
1553 entrycopy.key = entry->key;
1554 if (!_PyDict_Contains(other, entry->key, entry->hash)) {
1555 if (set_add_entry((PySetObject *)result, &entrycopy) == -1) {
1564 while (set_next(so, &pos, &entry)) {
1565 int rv = set_contains_entry((PySetObject *)other, entry);
1571 if (set_add_entry((PySetObject *)result, entry) == -1) {
1581 set_difference_multi(PySetObject *so, PyObject *args)
1584 PyObject *result, *other;
1586 if (PyTuple_GET_SIZE(args) == 0)
1587 return set_copy(so);
1589 other = PyTuple_GET_ITEM(args, 0);
1590 result = set_difference(so, other);
1594 for (i=1 ; i<PyTuple_GET_SIZE(args) ; i++) {
1595 other = PyTuple_GET_ITEM(args, i);
1596 if (set_difference_update_internal((PySetObject *)result, other) == -1) {
1604 PyDoc_STRVAR(difference_doc,
1605 "Return the difference of two or more sets as a new set.\n\
1607 (i.e. all elements that are in this set but not the others.)");
1609 set_sub(PySetObject *so, PyObject *other)
1611 if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
1612 Py_INCREF(Py_NotImplemented);
1613 return Py_NotImplemented;
1615 return set_difference(so, other);
1619 set_isub(PySetObject *so, PyObject *other)
1621 if (!PyAnySet_Check(other)) {
1622 Py_INCREF(Py_NotImplemented);
1623 return Py_NotImplemented;
1625 if (set_difference_update_internal(so, other) == -1)
1628 return (PyObject *)so;
1632 set_symmetric_difference_update(PySetObject *so, PyObject *other)
1634 PySetObject *otherset;
1639 if ((PyObject *)so == other)
1640 return set_clear(so);
1642 if (PyDict_CheckExact(other)) {
1646 while (_PyDict_Next(other, &pos, &key, &value, &hash)) {
1650 an_entry.hash = hash;
1653 rv = set_discard_entry(so, &an_entry);
1658 if (rv == DISCARD_NOTFOUND) {
1659 if (set_add_entry(so, &an_entry) == -1) {
1669 if (PyAnySet_Check(other)) {
1671 otherset = (PySetObject *)other;
1673 otherset = (PySetObject *)make_new_set(Py_TYPE(so), other);
1674 if (otherset == NULL)
1678 while (set_next(otherset, &pos, &entry)) {
1679 int rv = set_discard_entry(so, entry);
1681 Py_DECREF(otherset);
1684 if (rv == DISCARD_NOTFOUND) {
1685 if (set_add_entry(so, entry) == -1) {
1686 Py_DECREF(otherset);
1691 Py_DECREF(otherset);
1695 PyDoc_STRVAR(symmetric_difference_update_doc,
1696 "Update a set with the symmetric difference of itself and another.");
1699 set_symmetric_difference(PySetObject *so, PyObject *other)
1702 PySetObject *otherset;
1704 otherset = (PySetObject *)make_new_set(Py_TYPE(so), other);
1705 if (otherset == NULL)
1707 rv = set_symmetric_difference_update(otherset, (PyObject *)so);
1711 return (PyObject *)otherset;
1714 PyDoc_STRVAR(symmetric_difference_doc,
1715 "Return the symmetric difference of two sets as a new set.\n\
1717 (i.e. all elements that are in exactly one of the sets.)");
1720 set_xor(PySetObject *so, PyObject *other)
1722 if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
1723 Py_INCREF(Py_NotImplemented);
1724 return Py_NotImplemented;
1726 return set_symmetric_difference(so, other);
1730 set_ixor(PySetObject *so, PyObject *other)
1734 if (!PyAnySet_Check(other)) {
1735 Py_INCREF(Py_NotImplemented);
1736 return Py_NotImplemented;
1738 result = set_symmetric_difference_update(so, other);
1743 return (PyObject *)so;
1747 set_issubset(PySetObject *so, PyObject *other)
1752 if (!PyAnySet_Check(other)) {
1753 PyObject *tmp, *result;
1754 tmp = make_new_set(&PySet_Type, other);
1757 result = set_issubset(so, tmp);
1761 if (PySet_GET_SIZE(so) > PySet_GET_SIZE(other))
1764 while (set_next(so, &pos, &entry)) {
1765 int rv = set_contains_entry((PySetObject *)other, entry);
1774 PyDoc_STRVAR(issubset_doc, "Report whether another set contains this set.");
1777 set_issuperset(PySetObject *so, PyObject *other)
1779 PyObject *tmp, *result;
1781 if (!PyAnySet_Check(other)) {
1782 tmp = make_new_set(&PySet_Type, other);
1785 result = set_issuperset(so, tmp);
1789 return set_issubset((PySetObject *)other, (PyObject *)so);
1792 PyDoc_STRVAR(issuperset_doc, "Report whether this set contains another set.");
1795 set_richcompare(PySetObject *v, PyObject *w, int op)
1799 if(!PyAnySet_Check(w)) {
1804 PyErr_SetString(PyExc_TypeError, "can only compare to a set");
1809 if (PySet_GET_SIZE(v) != PySet_GET_SIZE(w))
1811 if (v->hash != -1 &&
1812 ((PySetObject *)w)->hash != -1 &&
1813 v->hash != ((PySetObject *)w)->hash)
1815 return set_issubset(v, w);
1817 r1 = set_richcompare(v, w, Py_EQ);
1820 r2 = PyBool_FromLong(PyObject_Not(r1));
1824 return set_issubset(v, w);
1826 return set_issuperset(v, w);
1828 if (PySet_GET_SIZE(v) >= PySet_GET_SIZE(w))
1830 return set_issubset(v, w);
1832 if (PySet_GET_SIZE(v) <= PySet_GET_SIZE(w))
1834 return set_issuperset(v, w);
1836 Py_INCREF(Py_NotImplemented);
1837 return Py_NotImplemented;
1841 set_nocmp(PyObject *self, PyObject *other)
1843 PyErr_SetString(PyExc_TypeError, "cannot compare sets using cmp()");
1848 set_add(PySetObject *so, PyObject *key)
1850 if (set_add_key(so, key) == -1)
1855 PyDoc_STRVAR(add_doc,
1856 "Add an element to a set.\n\
1858 This has no effect if the element is already present.");
1861 set_contains(PySetObject *so, PyObject *key)
1866 rv = set_contains_key(so, key);
1868 if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
1871 tmpkey = make_new_set(&PyFrozenSet_Type, key);
1874 rv = set_contains_key(so, tmpkey);
1881 set_direct_contains(PySetObject *so, PyObject *key)
1885 result = set_contains(so, key);
1888 return PyBool_FromLong(result);
1891 PyDoc_STRVAR(contains_doc, "x.__contains__(y) <==> y in x.");
1894 set_remove(PySetObject *so, PyObject *key)
1899 rv = set_discard_key(so, key);
1901 if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
1904 tmpkey = make_new_set(&PyFrozenSet_Type, key);
1907 rv = set_discard_key(so, tmpkey);
1913 if (rv == DISCARD_NOTFOUND) {
1920 PyDoc_STRVAR(remove_doc,
1921 "Remove an element from a set; it must be a member.\n\
1923 If the element is not a member, raise a KeyError.");
1926 set_discard(PySetObject *so, PyObject *key)
1931 rv = set_discard_key(so, key);
1933 if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
1936 tmpkey = make_new_set(&PyFrozenSet_Type, key);
1939 rv = set_discard_key(so, tmpkey);
1947 PyDoc_STRVAR(discard_doc,
1948 "Remove an element from a set if it is a member.\n\
1950 If the element is not a member, do nothing.");
1953 set_reduce(PySetObject *so)
1955 PyObject *keys=NULL, *args=NULL, *result=NULL, *dict=NULL;
1957 keys = PySequence_List((PyObject *)so);
1960 args = PyTuple_Pack(1, keys);
1963 dict = PyObject_GetAttrString((PyObject *)so, "__dict__");
1969 result = PyTuple_Pack(3, Py_TYPE(so), args, dict);
1977 PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1980 set_sizeof(PySetObject *so)
1984 res = sizeof(PySetObject);
1985 if (so->table != so->smalltable)
1986 res = res + (so->mask + 1) * sizeof(setentry);
1987 return PyInt_FromSsize_t(res);
1990 PyDoc_STRVAR(sizeof_doc, "S.__sizeof__() -> size of S in memory, in bytes");
1992 set_init(PySetObject *self, PyObject *args, PyObject *kwds)
1994 PyObject *iterable = NULL;
1996 if (!PyAnySet_Check(self))
1998 if (PySet_Check(self) && !_PyArg_NoKeywords("set()", kwds))
2000 if (!PyArg_UnpackTuple(args, Py_TYPE(self)->tp_name, 0, 1, &iterable))
2002 set_clear_internal(self);
2004 if (iterable == NULL)
2006 return set_update_internal(self, iterable);
2009 static PySequenceMethods set_as_sequence = {
2010 set_len, /* sq_length */
2015 0, /* sq_ass_item */
2016 0, /* sq_ass_slice */
2017 (objobjproc)set_contains, /* sq_contains */
2020 /* set object ********************************************************/
2023 static PyObject *test_c_api(PySetObject *so);
2025 PyDoc_STRVAR(test_c_api_doc, "Exercises C API. Returns True.\n\
2026 All is well if assertions don't fail.");
2029 static PyMethodDef set_methods[] = {
2030 {"add", (PyCFunction)set_add, METH_O,
2032 {"clear", (PyCFunction)set_clear, METH_NOARGS,
2034 {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST,
2036 {"copy", (PyCFunction)set_copy, METH_NOARGS,
2038 {"discard", (PyCFunction)set_discard, METH_O,
2040 {"difference", (PyCFunction)set_difference_multi, METH_VARARGS,
2042 {"difference_update", (PyCFunction)set_difference_update, METH_VARARGS,
2043 difference_update_doc},
2044 {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS,
2046 {"intersection_update",(PyCFunction)set_intersection_update_multi, METH_VARARGS,
2047 intersection_update_doc},
2048 {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O,
2050 {"issubset", (PyCFunction)set_issubset, METH_O,
2052 {"issuperset", (PyCFunction)set_issuperset, METH_O,
2054 {"pop", (PyCFunction)set_pop, METH_NOARGS,
2056 {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS,
2058 {"remove", (PyCFunction)set_remove, METH_O,
2060 {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS,
2062 {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O,
2063 symmetric_difference_doc},
2064 {"symmetric_difference_update",(PyCFunction)set_symmetric_difference_update, METH_O,
2065 symmetric_difference_update_doc},
2067 {"test_c_api", (PyCFunction)test_c_api, METH_NOARGS,
2070 {"union", (PyCFunction)set_union, METH_VARARGS,
2072 {"update", (PyCFunction)set_update, METH_VARARGS,
2074 {NULL, NULL} /* sentinel */
2077 static PyNumberMethods set_as_number = {
2079 (binaryfunc)set_sub, /*nb_subtract*/
2092 (binaryfunc)set_and, /*nb_and*/
2093 (binaryfunc)set_xor, /*nb_xor*/
2094 (binaryfunc)set_or, /*nb_or*/
2101 0, /*nb_inplace_add*/
2102 (binaryfunc)set_isub, /*nb_inplace_subtract*/
2103 0, /*nb_inplace_multiply*/
2104 0, /*nb_inplace_divide*/
2105 0, /*nb_inplace_remainder*/
2106 0, /*nb_inplace_power*/
2107 0, /*nb_inplace_lshift*/
2108 0, /*nb_inplace_rshift*/
2109 (binaryfunc)set_iand, /*nb_inplace_and*/
2110 (binaryfunc)set_ixor, /*nb_inplace_xor*/
2111 (binaryfunc)set_ior, /*nb_inplace_or*/
2114 PyDoc_STRVAR(set_doc,
2115 "set() -> new empty set object\n\
2116 set(iterable) -> new set object\n\
2118 Build an unordered collection of unique elements.");
2120 PyTypeObject PySet_Type = {
2121 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2122 "set", /* tp_name */
2123 sizeof(PySetObject), /* tp_basicsize */
2124 0, /* tp_itemsize */
2126 (destructor)set_dealloc, /* tp_dealloc */
2127 (printfunc)set_tp_print, /* tp_print */
2130 set_nocmp, /* tp_compare */
2131 (reprfunc)set_repr, /* tp_repr */
2132 &set_as_number, /* tp_as_number */
2133 &set_as_sequence, /* tp_as_sequence */
2134 0, /* tp_as_mapping */
2135 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
2138 PyObject_GenericGetAttr, /* tp_getattro */
2139 0, /* tp_setattro */
2140 0, /* tp_as_buffer */
2141 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES |
2142 Py_TPFLAGS_BASETYPE, /* tp_flags */
2143 set_doc, /* tp_doc */
2144 (traverseproc)set_traverse, /* tp_traverse */
2145 (inquiry)set_clear_internal, /* tp_clear */
2146 (richcmpfunc)set_richcompare, /* tp_richcompare */
2147 offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */
2148 (getiterfunc)set_iter, /* tp_iter */
2149 0, /* tp_iternext */
2150 set_methods, /* tp_methods */
2155 0, /* tp_descr_get */
2156 0, /* tp_descr_set */
2157 0, /* tp_dictoffset */
2158 (initproc)set_init, /* tp_init */
2159 PyType_GenericAlloc, /* tp_alloc */
2160 set_new, /* tp_new */
2161 PyObject_GC_Del, /* tp_free */
2164 /* frozenset object ********************************************************/
2167 static PyMethodDef frozenset_methods[] = {
2168 {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST,
2170 {"copy", (PyCFunction)frozenset_copy, METH_NOARGS,
2172 {"difference", (PyCFunction)set_difference_multi, METH_VARARGS,
2174 {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS,
2176 {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O,
2178 {"issubset", (PyCFunction)set_issubset, METH_O,
2180 {"issuperset", (PyCFunction)set_issuperset, METH_O,
2182 {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS,
2184 {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS,
2186 {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O,
2187 symmetric_difference_doc},
2188 {"union", (PyCFunction)set_union, METH_VARARGS,
2190 {NULL, NULL} /* sentinel */
2193 static PyNumberMethods frozenset_as_number = {
2195 (binaryfunc)set_sub, /*nb_subtract*/
2208 (binaryfunc)set_and, /*nb_and*/
2209 (binaryfunc)set_xor, /*nb_xor*/
2210 (binaryfunc)set_or, /*nb_or*/
2213 PyDoc_STRVAR(frozenset_doc,
2214 "frozenset() -> empty frozenset object\n\
2215 frozenset(iterable) -> frozenset object\n\
2217 Build an immutable unordered collection of unique elements.");
2219 PyTypeObject PyFrozenSet_Type = {
2220 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2221 "frozenset", /* tp_name */
2222 sizeof(PySetObject), /* tp_basicsize */
2223 0, /* tp_itemsize */
2225 (destructor)set_dealloc, /* tp_dealloc */
2226 (printfunc)set_tp_print, /* tp_print */
2229 set_nocmp, /* tp_compare */
2230 (reprfunc)set_repr, /* tp_repr */
2231 &frozenset_as_number, /* tp_as_number */
2232 &set_as_sequence, /* tp_as_sequence */
2233 0, /* tp_as_mapping */
2234 frozenset_hash, /* tp_hash */
2237 PyObject_GenericGetAttr, /* tp_getattro */
2238 0, /* tp_setattro */
2239 0, /* tp_as_buffer */
2240 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES |
2241 Py_TPFLAGS_BASETYPE, /* tp_flags */
2242 frozenset_doc, /* tp_doc */
2243 (traverseproc)set_traverse, /* tp_traverse */
2244 (inquiry)set_clear_internal, /* tp_clear */
2245 (richcmpfunc)set_richcompare, /* tp_richcompare */
2246 offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */
2247 (getiterfunc)set_iter, /* tp_iter */
2248 0, /* tp_iternext */
2249 frozenset_methods, /* tp_methods */
2254 0, /* tp_descr_get */
2255 0, /* tp_descr_set */
2256 0, /* tp_dictoffset */
2258 PyType_GenericAlloc, /* tp_alloc */
2259 frozenset_new, /* tp_new */
2260 PyObject_GC_Del, /* tp_free */
2264 /***** C API functions *************************************************/
2267 PySet_New(PyObject *iterable)
2269 return make_new_set(&PySet_Type, iterable);
2273 PyFrozenSet_New(PyObject *iterable)
2275 return make_new_set(&PyFrozenSet_Type, iterable);
2279 PySet_Size(PyObject *anyset)
2281 if (!PyAnySet_Check(anyset)) {
2282 PyErr_BadInternalCall();
2285 return PySet_GET_SIZE(anyset);
2289 PySet_Clear(PyObject *set)
2291 if (!PySet_Check(set)) {
2292 PyErr_BadInternalCall();
2295 return set_clear_internal((PySetObject *)set);
2299 PySet_Contains(PyObject *anyset, PyObject *key)
2301 if (!PyAnySet_Check(anyset)) {
2302 PyErr_BadInternalCall();
2305 return set_contains_key((PySetObject *)anyset, key);
2309 PySet_Discard(PyObject *set, PyObject *key)
2311 if (!PySet_Check(set)) {
2312 PyErr_BadInternalCall();
2315 return set_discard_key((PySetObject *)set, key);
2319 PySet_Add(PyObject *anyset, PyObject *key)
2321 if (!PySet_Check(anyset) &&
2322 (!PyFrozenSet_Check(anyset) || Py_REFCNT(anyset) != 1)) {
2323 PyErr_BadInternalCall();
2326 return set_add_key((PySetObject *)anyset, key);
2330 _PySet_Next(PyObject *set, Py_ssize_t *pos, PyObject **key)
2332 setentry *entry_ptr;
2334 if (!PyAnySet_Check(set)) {
2335 PyErr_BadInternalCall();
2338 if (set_next((PySetObject *)set, pos, &entry_ptr) == 0)
2340 *key = entry_ptr->key;
2345 _PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, long *hash)
2349 if (!PyAnySet_Check(set)) {
2350 PyErr_BadInternalCall();
2353 if (set_next((PySetObject *)set, pos, &entry) == 0)
2356 *hash = entry->hash;
2361 PySet_Pop(PyObject *set)
2363 if (!PySet_Check(set)) {
2364 PyErr_BadInternalCall();
2367 return set_pop((PySetObject *)set);
2371 _PySet_Update(PyObject *set, PyObject *iterable)
2373 if (!PySet_Check(set)) {
2374 PyErr_BadInternalCall();
2377 return set_update_internal((PySetObject *)set, iterable);
2382 /* Test code to be called with any three element set.
2383 Returns True and original set is restored. */
2385 #define assertRaises(call_return_value, exception) \
2387 assert(call_return_value); \
2388 assert(PyErr_ExceptionMatches(exception)); \
2393 test_c_api(PySetObject *so)
2398 PyObject *elem=NULL, *dup=NULL, *t, *f, *dup2, *x;
2399 PyObject *ob = (PyObject *)so;
2402 /* Verify preconditions */
2403 assert(PyAnySet_Check(ob));
2404 assert(PyAnySet_CheckExact(ob));
2405 assert(!PyFrozenSet_CheckExact(ob));
2407 /* so.clear(); so |= set("abc"); */
2408 str = PyString_FromString("abc");
2411 set_clear_internal(so);
2412 if (set_update_internal(so, str) == -1) {
2418 /* Exercise type/size checks */
2419 assert(PySet_Size(ob) == 3);
2420 assert(PySet_GET_SIZE(ob) == 3);
2422 /* Raise TypeError for non-iterable constructor arguments */
2423 assertRaises(PySet_New(Py_None) == NULL, PyExc_TypeError);
2424 assertRaises(PyFrozenSet_New(Py_None) == NULL, PyExc_TypeError);
2426 /* Raise TypeError for unhashable key */
2427 dup = PySet_New(ob);
2428 assertRaises(PySet_Discard(ob, dup) == -1, PyExc_TypeError);
2429 assertRaises(PySet_Contains(ob, dup) == -1, PyExc_TypeError);
2430 assertRaises(PySet_Add(ob, dup) == -1, PyExc_TypeError);
2432 /* Exercise successful pop, contains, add, and discard */
2433 elem = PySet_Pop(ob);
2434 assert(PySet_Contains(ob, elem) == 0);
2435 assert(PySet_GET_SIZE(ob) == 2);
2436 assert(PySet_Add(ob, elem) == 0);
2437 assert(PySet_Contains(ob, elem) == 1);
2438 assert(PySet_GET_SIZE(ob) == 3);
2439 assert(PySet_Discard(ob, elem) == 1);
2440 assert(PySet_GET_SIZE(ob) == 2);
2441 assert(PySet_Discard(ob, elem) == 0);
2442 assert(PySet_GET_SIZE(ob) == 2);
2444 /* Exercise clear */
2445 dup2 = PySet_New(dup);
2446 assert(PySet_Clear(dup2) == 0);
2447 assert(PySet_Size(dup2) == 0);
2450 /* Raise SystemError on clear or update of frozen set */
2451 f = PyFrozenSet_New(dup);
2452 assertRaises(PySet_Clear(f) == -1, PyExc_SystemError);
2453 assertRaises(_PySet_Update(f, dup) == -1, PyExc_SystemError);
2454 assert(PySet_Add(f, elem) == 0);
2456 assertRaises(PySet_Add(f, elem) == -1, PyExc_SystemError);
2460 /* Exercise direct iteration */
2462 while (_PySet_Next((PyObject *)dup, &i, &x)) {
2463 s = PyString_AsString(x);
2464 assert(s && (s[0] == 'a' || s[0] == 'b' || s[0] == 'c'));
2469 /* Exercise updates */
2470 dup2 = PySet_New(NULL);
2471 assert(_PySet_Update(dup2, dup) == 0);
2472 assert(PySet_Size(dup2) == 3);
2473 assert(_PySet_Update(dup2, dup) == 0);
2474 assert(PySet_Size(dup2) == 3);
2477 /* Raise SystemError when self argument is not a set or frozenset. */
2479 assertRaises(PySet_Size(t) == -1, PyExc_SystemError);
2480 assertRaises(PySet_Contains(t, elem) == -1, PyExc_SystemError);
2483 /* Raise SystemError when self argument is not a set. */
2484 f = PyFrozenSet_New(dup);
2485 assert(PySet_Size(f) == 3);
2486 assert(PyFrozenSet_CheckExact(f));
2487 assertRaises(PySet_Discard(f, elem) == -1, PyExc_SystemError);
2488 assertRaises(PySet_Pop(f) == NULL, PyExc_SystemError);
2491 /* Raise KeyError when popping from an empty set */
2492 assert(PyNumber_InPlaceSubtract(ob, ob) == ob);
2494 assert(PySet_GET_SIZE(ob) == 0);
2495 assertRaises(PySet_Pop(ob) == NULL, PyExc_KeyError);
2497 /* Restore the set from the copy using the PyNumber API */
2498 assert(PyNumber_InPlaceOr(ob, dup) == ob);
2501 /* Verify constructors accept NULL arguments */
2502 f = PySet_New(NULL);
2504 assert(PySet_GET_SIZE(f) == 0);
2506 f = PyFrozenSet_New(NULL);
2508 assert(PyFrozenSet_CheckExact(f));
2509 assert(PySet_GET_SIZE(f) == 0);