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-6 Python Software Foundation.
11 #include "structmember.h"
13 /* This must be >= 1. */
14 #define PERTURB_SHIFT 5
16 /* Object used as dummy key to fill deleted entries */
17 static PyObject
*dummy
= NULL
; /* Initialized by first call to make_new_set() */
27 #define INIT_NONZERO_SET_SLOTS(so) do { \
28 (so)->table = (so)->smalltable; \
29 (so)->mask = PySet_MINSIZE - 1; \
33 #define EMPTY_TO_MINSIZE(so) do { \
34 memset((so)->smalltable, 0, sizeof((so)->smalltable)); \
35 (so)->used = (so)->fill = 0; \
36 INIT_NONZERO_SET_SLOTS(so); \
39 /* Reuse scheme to save calls to malloc, free, and memset */
40 #define MAXFREESETS 80
41 static PySetObject
*free_sets
[MAXFREESETS
];
42 static int num_free_sets
= 0;
45 The basic lookup function used by all operations.
46 This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
47 Open addressing is preferred over chaining since the link overhead for
48 chaining would be substantial (100% with typical malloc overhead).
50 The initial probe index is computed as hash mod the table size. Subsequent
51 probe indices are computed as explained in Objects/dictobject.c.
53 All arithmetic on hash should ignore overflow.
55 Unlike the dictionary implementation, the lookkey functions can return
56 NULL if the rich comparison returns an error.
60 set_lookkey(PySetObject
*so
, PyObject
*key
, register long hash
)
62 register Py_ssize_t i
;
63 register size_t perturb
;
64 register setentry
*freeslot
;
65 register size_t mask
= so
->mask
;
66 setentry
*table
= so
->table
;
67 register setentry
*entry
;
73 if (entry
->key
== NULL
|| entry
->key
== key
)
76 if (entry
->key
== dummy
)
79 if (entry
->hash
== hash
) {
80 startkey
= entry
->key
;
81 cmp
= PyObject_RichCompareBool(startkey
, key
, Py_EQ
);
84 if (table
== so
->table
&& entry
->key
== startkey
) {
89 /* The compare did major nasty stuff to the
92 return set_lookkey(so
, key
, hash
);
98 /* In the loop, key == dummy is by far (factor of 100s) the
99 least likely outcome, so test for that last. */
100 for (perturb
= hash
; ; perturb
>>= PERTURB_SHIFT
) {
101 i
= (i
<< 2) + i
+ perturb
+ 1;
102 entry
= &table
[i
& mask
];
103 if (entry
->key
== NULL
) {
104 if (freeslot
!= NULL
)
108 if (entry
->key
== key
)
110 if (entry
->hash
== hash
&& entry
->key
!= dummy
) {
111 startkey
= entry
->key
;
112 cmp
= PyObject_RichCompareBool(startkey
, key
, Py_EQ
);
115 if (table
== so
->table
&& entry
->key
== startkey
) {
120 /* The compare did major nasty stuff to the
123 return set_lookkey(so
, key
, hash
);
126 else if (entry
->key
== dummy
&& freeslot
== NULL
)
133 * Hacked up version of set_lookkey which can assume keys are always strings;
134 * This means we can always use _PyString_Eq directly and not have to check to
135 * see if the comparison altered the table.
138 set_lookkey_string(PySetObject
*so
, PyObject
*key
, register long hash
)
140 register Py_ssize_t i
;
141 register size_t perturb
;
142 register setentry
*freeslot
;
143 register size_t mask
= so
->mask
;
144 setentry
*table
= so
->table
;
145 register setentry
*entry
;
147 /* Make sure this function doesn't have to handle non-string keys,
148 including subclasses of str; e.g., one reason to subclass
149 strings is to override __eq__, and for speed we don't cater to
151 if (!PyString_CheckExact(key
)) {
152 so
->lookup
= set_lookkey
;
153 return set_lookkey(so
, key
, hash
);
157 if (entry
->key
== NULL
|| entry
->key
== key
)
159 if (entry
->key
== dummy
)
162 if (entry
->hash
== hash
&& _PyString_Eq(entry
->key
, key
))
167 /* In the loop, key == dummy is by far (factor of 100s) the
168 least likely outcome, so test for that last. */
169 for (perturb
= hash
; ; perturb
>>= PERTURB_SHIFT
) {
170 i
= (i
<< 2) + i
+ perturb
+ 1;
171 entry
= &table
[i
& mask
];
172 if (entry
->key
== NULL
)
173 return freeslot
== NULL
? entry
: freeslot
;
174 if (entry
->key
== key
175 || (entry
->hash
== hash
176 && entry
->key
!= dummy
177 && _PyString_Eq(entry
->key
, key
)))
179 if (entry
->key
== dummy
&& freeslot
== NULL
)
185 Internal routine to insert a new key into the table.
186 Used both by the internal resize routine and by the public insert routine.
187 Eats a reference to key.
190 set_insert_key(register PySetObject
*so
, PyObject
*key
, long hash
)
192 register setentry
*entry
;
193 typedef setentry
*(*lookupfunc
)(PySetObject
*, PyObject
*, long);
195 assert(so
->lookup
!= NULL
);
196 entry
= so
->lookup(so
, key
, hash
);
199 if (entry
->key
== NULL
) {
205 } else if (entry
->key
== dummy
) {
219 Restructure the table by allocating a new table and reinserting all
220 keys again. When entries have been deleted, the new table may
221 actually be smaller than the old one.
224 set_table_resize(PySetObject
*so
, Py_ssize_t minused
)
227 setentry
*oldtable
, *newtable
, *entry
;
229 int is_oldtable_malloced
;
230 setentry small_copy
[PySet_MINSIZE
];
232 assert(minused
>= 0);
234 /* Find the smallest table size > minused. */
235 for (newsize
= PySet_MINSIZE
;
236 newsize
<= minused
&& newsize
> 0;
244 /* Get space for a new table. */
245 oldtable
= so
->table
;
246 assert(oldtable
!= NULL
);
247 is_oldtable_malloced
= oldtable
!= so
->smalltable
;
249 if (newsize
== PySet_MINSIZE
) {
250 /* A large table is shrinking, or we can't get any smaller. */
251 newtable
= so
->smalltable
;
252 if (newtable
== oldtable
) {
253 if (so
->fill
== so
->used
) {
254 /* No dummies, so no point doing anything. */
257 /* We're not going to resize it, but rebuild the
258 table anyway to purge old dummy entries.
259 Subtle: This is *necessary* if fill==size,
260 as set_lookkey needs at least one virgin slot to
261 terminate failing searches. If fill < size, it's
262 merely desirable, as dummies slow searches. */
263 assert(so
->fill
> so
->used
);
264 memcpy(small_copy
, oldtable
, sizeof(small_copy
));
265 oldtable
= small_copy
;
269 newtable
= PyMem_NEW(setentry
, newsize
);
270 if (newtable
== NULL
) {
276 /* Make the set empty, using the new table. */
277 assert(newtable
!= oldtable
);
278 so
->table
= newtable
;
279 so
->mask
= newsize
- 1;
280 memset(newtable
, 0, sizeof(setentry
) * newsize
);
285 /* Copy the data over; this is refcount-neutral for active entries;
286 dummy entries aren't copied over, of course */
287 for (entry
= oldtable
; i
> 0; entry
++) {
288 if (entry
->key
== NULL
) {
291 } else if (entry
->key
== dummy
) {
294 assert(entry
->key
== dummy
);
295 Py_DECREF(entry
->key
);
299 if(set_insert_key(so
, entry
->key
, entry
->hash
) == -1) {
300 if (is_oldtable_malloced
)
307 if (is_oldtable_malloced
)
312 /* CAUTION: set_add_key/entry() must guarantee it won't resize the table */
315 set_add_entry(register PySetObject
*so
, setentry
*entry
)
317 register Py_ssize_t n_used
;
319 assert(so
->fill
<= so
->mask
); /* at least one empty slot */
321 Py_INCREF(entry
->key
);
322 if (set_insert_key(so
, entry
->key
, entry
->hash
) == -1)
324 if (!(so
->used
> n_used
&& so
->fill
*3 >= (so
->mask
+1)*2))
326 return set_table_resize(so
, so
->used
>50000 ? so
->used
*2 : so
->used
*4);
330 set_add_key(register PySetObject
*so
, PyObject
*key
)
333 register Py_ssize_t n_used
;
335 if (!PyString_CheckExact(key
) ||
336 (hash
= ((PyStringObject
*) key
)->ob_shash
) == -1) {
337 hash
= PyObject_Hash(key
);
341 assert(so
->fill
<= so
->mask
); /* at least one empty slot */
344 if (set_insert_key(so
, key
, hash
) == -1) {
348 if (!(so
->used
> n_used
&& so
->fill
*3 >= (so
->mask
+1)*2))
350 return set_table_resize(so
, so
->used
>50000 ? so
->used
*2 : so
->used
*4);
353 #define DISCARD_NOTFOUND 0
354 #define DISCARD_FOUND 1
357 set_discard_entry(PySetObject
*so
, setentry
*oldentry
)
358 { register setentry
*entry
;
361 entry
= (so
->lookup
)(so
, oldentry
->key
, oldentry
->hash
);
364 if (entry
->key
== NULL
|| entry
->key
== dummy
)
365 return DISCARD_NOTFOUND
;
366 old_key
= entry
->key
;
371 return DISCARD_FOUND
;
375 set_discard_key(PySetObject
*so
, PyObject
*key
)
378 register setentry
*entry
;
381 assert (PyAnySet_Check(so
));
382 if (!PyString_CheckExact(key
) ||
383 (hash
= ((PyStringObject
*) key
)->ob_shash
) == -1) {
384 hash
= PyObject_Hash(key
);
388 entry
= (so
->lookup
)(so
, key
, hash
);
391 if (entry
->key
== NULL
|| entry
->key
== dummy
)
392 return DISCARD_NOTFOUND
;
393 old_key
= entry
->key
;
398 return DISCARD_FOUND
;
402 set_clear_internal(PySetObject
*so
)
404 setentry
*entry
, *table
;
405 int table_is_malloced
;
407 setentry small_copy
[PySet_MINSIZE
];
410 assert (PyAnySet_Check(so
));
417 assert(table
!= NULL
);
418 table_is_malloced
= table
!= so
->smalltable
;
420 /* This is delicate. During the process of clearing the set,
421 * decrefs can cause the set to mutate. To avoid fatal confusion
422 * (voice of experience), we have to make the set empty before
423 * clearing the slots, and never refer to anything via so->ref while
427 if (table_is_malloced
)
428 EMPTY_TO_MINSIZE(so
);
431 /* It's a small table with something that needs to be cleared.
432 * Afraid the only safe way is to copy the set entries into
433 * another small table first.
435 memcpy(small_copy
, table
, sizeof(small_copy
));
437 EMPTY_TO_MINSIZE(so
);
439 /* else it's a small table that's already empty */
441 /* Now we can finally clear things. If C had refcounts, we could
442 * assert that the refcount on table is 1 now, i.e. that this function
443 * has unique access to it, so decref side-effects can't alter it.
445 for (entry
= table
; fill
> 0; ++entry
) {
452 Py_DECREF(entry
->key
);
456 assert(entry
->key
== NULL
);
460 if (table_is_malloced
)
466 * Iterate over a set table. Use like so:
470 * pos = 0; # important! pos should not otherwise be changed by you
471 * while (set_next(yourset, &pos, &entry)) {
472 * Refer to borrowed reference in entry->key.
475 * CAUTION: In general, it isn't safe to use set_next in a loop that
479 set_next(PySetObject
*so
, Py_ssize_t
*pos_ptr
, setentry
**entry_ptr
)
483 register setentry
*table
;
485 assert (PyAnySet_Check(so
));
490 while (i
<= mask
&& (table
[i
].key
== NULL
|| table
[i
].key
== dummy
))
495 assert(table
[i
].key
!= NULL
);
496 *entry_ptr
= &table
[i
];
501 set_dealloc(PySetObject
*so
)
503 register setentry
*entry
;
504 Py_ssize_t fill
= so
->fill
;
505 PyObject_GC_UnTrack(so
);
506 Py_TRASHCAN_SAFE_BEGIN(so
)
507 if (so
->weakreflist
!= NULL
)
508 PyObject_ClearWeakRefs((PyObject
*) so
);
510 for (entry
= so
->table
; fill
> 0; entry
++) {
513 Py_DECREF(entry
->key
);
516 if (so
->table
!= so
->smalltable
)
517 PyMem_DEL(so
->table
);
518 if (num_free_sets
< MAXFREESETS
&& PyAnySet_CheckExact(so
))
519 free_sets
[num_free_sets
++] = so
;
521 so
->ob_type
->tp_free(so
);
522 Py_TRASHCAN_SAFE_END(so
)
526 set_tp_print(PySetObject
*so
, FILE *fp
, int flags
)
530 char *emit
= ""; /* No separator emitted on first pass */
531 char *separator
= ", ";
533 fprintf(fp
, "%s([", so
->ob_type
->tp_name
);
534 while (set_next(so
, &pos
, &entry
)) {
537 if (PyObject_Print(entry
->key
, fp
, 0) != 0)
545 set_repr(PySetObject
*so
)
547 PyObject
*keys
, *result
, *listrepr
;
549 keys
= PySequence_List((PyObject
*)so
);
552 listrepr
= PyObject_Repr(keys
);
554 if (listrepr
== NULL
)
557 result
= PyString_FromFormat("%s(%s)", so
->ob_type
->tp_name
,
558 PyString_AS_STRING(listrepr
));
564 set_len(PyObject
*so
)
566 return ((PySetObject
*)so
)->used
;
570 set_merge(PySetObject
*so
, PyObject
*otherset
)
573 register Py_ssize_t i
;
574 register setentry
*entry
;
576 assert (PyAnySet_Check(so
));
577 assert (PyAnySet_Check(otherset
));
579 other
= (PySetObject
*)otherset
;
580 if (other
== so
|| other
->used
== 0)
581 /* a.update(a) or a.update({}); nothing to do */
583 /* Do one big resize at the start, rather than
584 * incrementally resizing as we insert new keys. Expect
585 * that there will be no (or few) overlapping keys.
587 if ((so
->fill
+ other
->used
)*3 >= (so
->mask
+1)*2) {
588 if (set_table_resize(so
, (so
->used
+ other
->used
)*2) != 0)
591 for (i
= 0; i
<= other
->mask
; i
++) {
592 entry
= &other
->table
[i
];
593 if (entry
->key
!= NULL
&&
594 entry
->key
!= dummy
) {
595 Py_INCREF(entry
->key
);
596 if (set_insert_key(so
, entry
->key
, entry
->hash
) == -1) {
597 Py_DECREF(entry
->key
);
606 set_contains_key(PySetObject
*so
, PyObject
*key
)
611 if (!PyString_CheckExact(key
) ||
612 (hash
= ((PyStringObject
*) key
)->ob_shash
) == -1) {
613 hash
= PyObject_Hash(key
);
617 entry
= (so
->lookup
)(so
, key
, hash
);
621 return key
!= NULL
&& key
!= dummy
;
625 set_contains_entry(PySetObject
*so
, setentry
*entry
)
630 lu_entry
= (so
->lookup
)(so
, entry
->key
, entry
->hash
);
631 if (lu_entry
== NULL
)
634 return key
!= NULL
&& key
!= dummy
;
638 set_pop(PySetObject
*so
)
640 register Py_ssize_t i
= 0;
641 register setentry
*entry
;
644 assert (PyAnySet_Check(so
));
646 PyErr_SetString(PyExc_KeyError
, "pop from an empty set");
650 /* Set entry to "the first" unused or dummy set entry. We abuse
651 * the hash field of slot 0 to hold a search finger:
652 * If slot 0 has a value, use slot 0.
653 * Else slot 0 is being used to hold a search finger,
654 * and we use its hash value as the first index to look.
656 entry
= &so
->table
[0];
657 if (entry
->key
== NULL
|| entry
->key
== dummy
) {
659 /* The hash field may be a real hash value, or it may be a
660 * legit search finger, or it may be a once-legit search
661 * finger that's out of bounds now because it wrapped around
662 * or the table shrunk -- simply make sure it's in bounds now.
664 if (i
> so
->mask
|| i
< 1)
665 i
= 1; /* skip slot 0 */
666 while ((entry
= &so
->table
[i
])->key
== NULL
|| entry
->key
==dummy
) {
676 so
->table
[0].hash
= i
+ 1; /* next place to start */
680 PyDoc_STRVAR(pop_doc
, "Remove and return an arbitrary set element.");
683 set_traverse(PySetObject
*so
, visitproc visit
, void *arg
)
688 while (set_next(so
, &pos
, &entry
))
689 Py_VISIT(entry
->key
);
694 frozenset_hash(PyObject
*self
)
696 PySetObject
*so
= (PySetObject
*)self
;
697 long h
, hash
= 1927868237L;
704 hash
*= PySet_GET_SIZE(self
) + 1;
705 while (set_next(so
, &pos
, &entry
)) {
706 /* Work to increase the bit dispersion for closely spaced hash
707 values. The is important because some use cases have many
708 combinations of a small number of elements with nearby
709 hashes so that many distinct combinations collapse to only
710 a handful of distinct hash values. */
712 hash
^= (h
^ (h
<< 16) ^ 89869747L) * 3644798167u;
714 hash
= hash
* 69069L + 907133923L;
722 set_nohash(PyObject
*self
)
724 PyErr_SetString(PyExc_TypeError
, "set objects are unhashable");
728 /***** Set iterator type ***********************************************/
732 PySetObject
*si_set
; /* Set to NULL when iterator is exhausted */
739 setiter_dealloc(setiterobject
*si
)
741 Py_XDECREF(si
->si_set
);
746 setiter_len(setiterobject
*si
)
749 if (si
->si_set
!= NULL
&& si
->si_used
== si
->si_set
->used
)
751 return PyInt_FromLong(len
);
754 PyDoc_STRVAR(length_hint_doc
, "Private method returning an estimate of len(list(it)).");
756 static PyMethodDef setiter_methods
[] = {
757 {"__length_hint__", (PyCFunction
)setiter_len
, METH_NOARGS
, length_hint_doc
},
758 {NULL
, NULL
} /* sentinel */
761 static PyObject
*setiter_iternext(setiterobject
*si
)
764 register Py_ssize_t i
, mask
;
765 register setentry
*entry
;
766 PySetObject
*so
= si
->si_set
;
770 assert (PyAnySet_Check(so
));
772 if (si
->si_used
!= so
->used
) {
773 PyErr_SetString(PyExc_RuntimeError
,
774 "Set changed size during iteration");
775 si
->si_used
= -1; /* Make this state sticky */
783 while (i
<= mask
&& (entry
[i
].key
== NULL
|| entry
[i
].key
== dummy
))
799 static PyTypeObject PySetIter_Type
= {
800 PyObject_HEAD_INIT(&PyType_Type
)
802 "setiterator", /* tp_name */
803 sizeof(setiterobject
), /* tp_basicsize */
806 (destructor
)setiter_dealloc
, /* tp_dealloc */
812 0, /* tp_as_number */
813 0, /* tp_as_sequence */
814 0, /* tp_as_mapping */
818 PyObject_GenericGetAttr
, /* tp_getattro */
820 0, /* tp_as_buffer */
821 Py_TPFLAGS_DEFAULT
, /* tp_flags */
825 0, /* tp_richcompare */
826 0, /* tp_weaklistoffset */
827 PyObject_SelfIter
, /* tp_iter */
828 (iternextfunc
)setiter_iternext
, /* tp_iternext */
829 setiter_methods
, /* tp_methods */
834 set_iter(PySetObject
*so
)
836 setiterobject
*si
= PyObject_New(setiterobject
, &PySetIter_Type
);
841 si
->si_used
= so
->used
;
844 return (PyObject
*)si
;
848 set_update_internal(PySetObject
*so
, PyObject
*other
)
852 if (PyAnySet_Check(other
))
853 return set_merge(so
, other
);
855 if (PyDict_Check(other
)) {
858 while (PyDict_Next(other
, &pos
, &key
, &value
)) {
859 if (set_add_key(so
, key
) == -1)
865 it
= PyObject_GetIter(other
);
869 while ((key
= PyIter_Next(it
)) != NULL
) {
870 if (set_add_key(so
, key
) == -1) {
878 if (PyErr_Occurred())
884 set_update(PySetObject
*so
, PyObject
*other
)
886 if (set_update_internal(so
, other
) == -1)
891 PyDoc_STRVAR(update_doc
,
892 "Update a set with the union of itself and another.");
895 make_new_set(PyTypeObject
*type
, PyObject
*iterable
)
897 register PySetObject
*so
= NULL
;
899 if (dummy
== NULL
) { /* Auto-initialize dummy */
900 dummy
= PyString_FromString("<dummy key>");
905 /* create PySetObject structure */
907 (type
== &PySet_Type
|| type
== &PyFrozenSet_Type
)) {
908 so
= free_sets
[--num_free_sets
];
909 assert (so
!= NULL
&& PyAnySet_CheckExact(so
));
911 _Py_NewReference((PyObject
*)so
);
912 EMPTY_TO_MINSIZE(so
);
913 PyObject_GC_Track(so
);
915 so
= (PySetObject
*)type
->tp_alloc(type
, 0);
918 /* tp_alloc has already zeroed the structure */
919 assert(so
->table
== NULL
&& so
->fill
== 0 && so
->used
== 0);
920 INIT_NONZERO_SET_SLOTS(so
);
923 so
->lookup
= set_lookkey_string
;
924 so
->weakreflist
= NULL
;
926 if (iterable
!= NULL
) {
927 if (set_update_internal(so
, iterable
) == -1) {
933 return (PyObject
*)so
;
936 /* The empty frozenset is a singleton */
937 static PyObject
*emptyfrozenset
= NULL
;
940 frozenset_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
942 PyObject
*iterable
= NULL
, *result
;
944 if (!_PyArg_NoKeywords("frozenset()", kwds
))
947 if (!PyArg_UnpackTuple(args
, type
->tp_name
, 0, 1, &iterable
))
950 if (type
!= &PyFrozenSet_Type
)
951 return make_new_set(type
, iterable
);
953 if (iterable
!= NULL
) {
954 /* frozenset(f) is idempotent */
955 if (PyFrozenSet_CheckExact(iterable
)) {
959 result
= make_new_set(type
, iterable
);
960 if (result
== NULL
|| PySet_GET_SIZE(result
))
964 /* The empty frozenset is a singleton */
965 if (emptyfrozenset
== NULL
)
966 emptyfrozenset
= make_new_set(type
, NULL
);
967 Py_XINCREF(emptyfrozenset
);
968 return emptyfrozenset
;
976 while (num_free_sets
) {
978 so
= free_sets
[num_free_sets
];
982 Py_CLEAR(emptyfrozenset
);
986 set_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
988 if (!_PyArg_NoKeywords("set()", kwds
))
991 return make_new_set(type
, NULL
);
994 /* set_swap_bodies() switches the contents of any two sets by moving their
995 internal data pointers and, if needed, copying the internal smalltables.
996 Semantically equivalent to:
998 t=set(a); a.clear(); a.update(b); b.clear(); b.update(t); del t
1000 The function always succeeds and it leaves both objects in a stable state.
1001 Useful for creating temporary frozensets from sets for membership testing
1002 in __contains__(), discard(), and remove(). Also useful for operations
1003 that update in-place (by allowing an intermediate result to be swapped
1004 into one of the original inputs).
1008 set_swap_bodies(PySetObject
*a
, PySetObject
*b
)
1012 setentry
*(*f
)(PySetObject
*so
, PyObject
*key
, long hash
);
1013 setentry tab
[PySet_MINSIZE
];
1016 t
= a
->fill
; a
->fill
= b
->fill
; b
->fill
= t
;
1017 t
= a
->used
; a
->used
= b
->used
; b
->used
= t
;
1018 t
= a
->mask
; a
->mask
= b
->mask
; b
->mask
= t
;
1021 if (a
->table
== a
->smalltable
)
1023 a
->table
= b
->table
;
1024 if (b
->table
== b
->smalltable
)
1025 a
->table
= a
->smalltable
;
1028 f
= a
->lookup
; a
->lookup
= b
->lookup
; b
->lookup
= f
;
1030 if (a
->table
== a
->smalltable
|| b
->table
== b
->smalltable
) {
1031 memcpy(tab
, a
->smalltable
, sizeof(tab
));
1032 memcpy(a
->smalltable
, b
->smalltable
, sizeof(tab
));
1033 memcpy(b
->smalltable
, tab
, sizeof(tab
));
1036 if (PyType_IsSubtype(a
->ob_type
, &PyFrozenSet_Type
) &&
1037 PyType_IsSubtype(b
->ob_type
, &PyFrozenSet_Type
)) {
1038 h
= a
->hash
; a
->hash
= b
->hash
; b
->hash
= h
;
1046 set_copy(PySetObject
*so
)
1048 return make_new_set(so
->ob_type
, (PyObject
*)so
);
1052 frozenset_copy(PySetObject
*so
)
1054 if (PyFrozenSet_CheckExact(so
)) {
1056 return (PyObject
*)so
;
1058 return set_copy(so
);
1061 PyDoc_STRVAR(copy_doc
, "Return a shallow copy of a set.");
1064 set_clear(PySetObject
*so
)
1066 set_clear_internal(so
);
1070 PyDoc_STRVAR(clear_doc
, "Remove all elements from this set.");
1073 set_union(PySetObject
*so
, PyObject
*other
)
1075 PySetObject
*result
;
1077 result
= (PySetObject
*)set_copy(so
);
1080 if ((PyObject
*)so
== other
)
1081 return (PyObject
*)result
;
1082 if (set_update_internal(result
, other
) == -1) {
1086 return (PyObject
*)result
;
1089 PyDoc_STRVAR(union_doc
,
1090 "Return the union of two sets as a new set.\n\
1092 (i.e. all elements that are in either set.)");
1095 set_or(PySetObject
*so
, PyObject
*other
)
1097 if (!PyAnySet_Check(so
) || !PyAnySet_Check(other
)) {
1098 Py_INCREF(Py_NotImplemented
);
1099 return Py_NotImplemented
;
1101 return set_union(so
, other
);
1105 set_ior(PySetObject
*so
, PyObject
*other
)
1107 if (!PyAnySet_Check(other
)) {
1108 Py_INCREF(Py_NotImplemented
);
1109 return Py_NotImplemented
;
1111 if (set_update_internal(so
, other
) == -1)
1114 return (PyObject
*)so
;
1118 set_intersection(PySetObject
*so
, PyObject
*other
)
1120 PySetObject
*result
;
1121 PyObject
*key
, *it
, *tmp
;
1123 if ((PyObject
*)so
== other
)
1124 return set_copy(so
);
1126 result
= (PySetObject
*)make_new_set(so
->ob_type
, NULL
);
1130 if (PyAnySet_Check(other
)) {
1134 if (PySet_GET_SIZE(other
) > PySet_GET_SIZE(so
)) {
1135 tmp
= (PyObject
*)so
;
1136 so
= (PySetObject
*)other
;
1140 while (set_next((PySetObject
*)other
, &pos
, &entry
)) {
1141 if (set_contains_entry(so
, entry
)) {
1142 if (set_add_entry(result
, entry
) == -1) {
1148 return (PyObject
*)result
;
1151 it
= PyObject_GetIter(other
);
1157 while ((key
= PyIter_Next(it
)) != NULL
) {
1158 if (set_contains_key(so
, key
)) {
1159 if (set_add_key(result
, key
) == -1) {
1169 if (PyErr_Occurred()) {
1173 return (PyObject
*)result
;
1176 PyDoc_STRVAR(intersection_doc
,
1177 "Return the intersection of two sets as a new set.\n\
1179 (i.e. all elements that are in both sets.)");
1182 set_intersection_update(PySetObject
*so
, PyObject
*other
)
1186 tmp
= set_intersection(so
, other
);
1189 set_swap_bodies(so
, (PySetObject
*)tmp
);
1194 PyDoc_STRVAR(intersection_update_doc
,
1195 "Update a set with the intersection of itself and another.");
1198 set_and(PySetObject
*so
, PyObject
*other
)
1200 if (!PyAnySet_Check(so
) || !PyAnySet_Check(other
)) {
1201 Py_INCREF(Py_NotImplemented
);
1202 return Py_NotImplemented
;
1204 return set_intersection(so
, other
);
1208 set_iand(PySetObject
*so
, PyObject
*other
)
1212 if (!PyAnySet_Check(other
)) {
1213 Py_INCREF(Py_NotImplemented
);
1214 return Py_NotImplemented
;
1216 result
= set_intersection_update(so
, other
);
1221 return (PyObject
*)so
;
1225 set_difference_update_internal(PySetObject
*so
, PyObject
*other
)
1227 if ((PyObject
*)so
== other
)
1228 return set_clear_internal(so
);
1230 if (PyAnySet_Check(other
)) {
1234 while (set_next((PySetObject
*)other
, &pos
, &entry
))
1235 set_discard_entry(so
, entry
);
1238 it
= PyObject_GetIter(other
);
1242 while ((key
= PyIter_Next(it
)) != NULL
) {
1243 if (set_discard_key(so
, key
) == -1) {
1251 if (PyErr_Occurred())
1254 /* If more than 1/5 are dummies, then resize them away. */
1255 if ((so
->fill
- so
->used
) * 5 < so
->mask
)
1257 return set_table_resize(so
, so
->used
>50000 ? so
->used
*2 : so
->used
*4);
1261 set_difference_update(PySetObject
*so
, PyObject
*other
)
1263 if (set_difference_update_internal(so
, other
) != -1)
1268 PyDoc_STRVAR(difference_update_doc
,
1269 "Remove all elements of another set from this set.");
1272 set_difference(PySetObject
*so
, PyObject
*other
)
1278 if (!PyAnySet_Check(other
) && !PyDict_Check(other
)) {
1279 result
= set_copy(so
);
1282 if (set_difference_update_internal((PySetObject
*)result
, other
) != -1)
1288 result
= make_new_set(so
->ob_type
, NULL
);
1292 if (PyDict_Check(other
)) {
1293 while (set_next(so
, &pos
, &entry
)) {
1295 entrycopy
.hash
= entry
->hash
;
1296 entrycopy
.key
= entry
->key
;
1297 if (!PyDict_Contains(other
, entry
->key
)) {
1298 if (set_add_entry((PySetObject
*)result
, &entrycopy
) == -1)
1305 while (set_next(so
, &pos
, &entry
)) {
1306 if (!set_contains_entry((PySetObject
*)other
, entry
)) {
1307 if (set_add_entry((PySetObject
*)result
, entry
) == -1)
1314 PyDoc_STRVAR(difference_doc
,
1315 "Return the difference of two sets as a new set.\n\
1317 (i.e. all elements that are in this set but not the other.)");
1319 set_sub(PySetObject
*so
, PyObject
*other
)
1321 if (!PyAnySet_Check(so
) || !PyAnySet_Check(other
)) {
1322 Py_INCREF(Py_NotImplemented
);
1323 return Py_NotImplemented
;
1325 return set_difference(so
, other
);
1329 set_isub(PySetObject
*so
, PyObject
*other
)
1333 if (!PyAnySet_Check(other
)) {
1334 Py_INCREF(Py_NotImplemented
);
1335 return Py_NotImplemented
;
1337 result
= set_difference_update(so
, other
);
1342 return (PyObject
*)so
;
1346 set_symmetric_difference_update(PySetObject
*so
, PyObject
*other
)
1348 PySetObject
*otherset
;
1353 if ((PyObject
*)so
== other
)
1354 return set_clear(so
);
1356 if (PyDict_Check(other
)) {
1359 while (PyDict_Next(other
, &pos
, &key
, &value
)) {
1360 rv
= set_discard_key(so
, key
);
1363 if (rv
== DISCARD_NOTFOUND
) {
1364 if (set_add_key(so
, key
) == -1)
1371 if (PyAnySet_Check(other
)) {
1373 otherset
= (PySetObject
*)other
;
1375 otherset
= (PySetObject
*)make_new_set(so
->ob_type
, other
);
1376 if (otherset
== NULL
)
1380 while (set_next(otherset
, &pos
, &entry
)) {
1381 int rv
= set_discard_entry(so
, entry
);
1383 Py_XDECREF(otherset
);
1386 if (rv
== DISCARD_NOTFOUND
) {
1387 if (set_add_entry(so
, entry
) == -1) {
1388 Py_XDECREF(otherset
);
1393 Py_DECREF(otherset
);
1397 PyDoc_STRVAR(symmetric_difference_update_doc
,
1398 "Update a set with the symmetric difference of itself and another.");
1401 set_symmetric_difference(PySetObject
*so
, PyObject
*other
)
1404 PySetObject
*otherset
;
1406 otherset
= (PySetObject
*)make_new_set(so
->ob_type
, other
);
1407 if (otherset
== NULL
)
1409 rv
= set_symmetric_difference_update(otherset
, (PyObject
*)so
);
1413 return (PyObject
*)otherset
;
1416 PyDoc_STRVAR(symmetric_difference_doc
,
1417 "Return the symmetric difference of two sets as a new set.\n\
1419 (i.e. all elements that are in exactly one of the sets.)");
1422 set_xor(PySetObject
*so
, PyObject
*other
)
1424 if (!PyAnySet_Check(so
) || !PyAnySet_Check(other
)) {
1425 Py_INCREF(Py_NotImplemented
);
1426 return Py_NotImplemented
;
1428 return set_symmetric_difference(so
, other
);
1432 set_ixor(PySetObject
*so
, PyObject
*other
)
1436 if (!PyAnySet_Check(other
)) {
1437 Py_INCREF(Py_NotImplemented
);
1438 return Py_NotImplemented
;
1440 result
= set_symmetric_difference_update(so
, other
);
1445 return (PyObject
*)so
;
1449 set_issubset(PySetObject
*so
, PyObject
*other
)
1454 if (!PyAnySet_Check(other
)) {
1455 PyObject
*tmp
, *result
;
1456 tmp
= make_new_set(&PySet_Type
, other
);
1459 result
= set_issubset(so
, tmp
);
1463 if (PySet_GET_SIZE(so
) > PySet_GET_SIZE(other
))
1466 while (set_next(so
, &pos
, &entry
)) {
1467 if (!set_contains_entry((PySetObject
*)other
, entry
))
1473 PyDoc_STRVAR(issubset_doc
, "Report whether another set contains this set.");
1476 set_issuperset(PySetObject
*so
, PyObject
*other
)
1478 PyObject
*tmp
, *result
;
1480 if (!PyAnySet_Check(other
)) {
1481 tmp
= make_new_set(&PySet_Type
, other
);
1484 result
= set_issuperset(so
, tmp
);
1488 return set_issubset((PySetObject
*)other
, (PyObject
*)so
);
1491 PyDoc_STRVAR(issuperset_doc
, "Report whether this set contains another set.");
1494 set_richcompare(PySetObject
*v
, PyObject
*w
, int op
)
1498 if(!PyAnySet_Check(w
)) {
1503 PyErr_SetString(PyExc_TypeError
, "can only compare to a set");
1508 if (PySet_GET_SIZE(v
) != PySet_GET_SIZE(w
))
1510 if (v
->hash
!= -1 &&
1511 ((PySetObject
*)w
)->hash
!= -1 &&
1512 v
->hash
!= ((PySetObject
*)w
)->hash
)
1514 return set_issubset(v
, w
);
1516 r1
= set_richcompare(v
, w
, Py_EQ
);
1519 r2
= PyBool_FromLong(PyObject_Not(r1
));
1523 return set_issubset(v
, w
);
1525 return set_issuperset(v
, w
);
1527 if (PySet_GET_SIZE(v
) >= PySet_GET_SIZE(w
))
1529 return set_issubset(v
, w
);
1531 if (PySet_GET_SIZE(v
) <= PySet_GET_SIZE(w
))
1533 return set_issuperset(v
, w
);
1535 Py_INCREF(Py_NotImplemented
);
1536 return Py_NotImplemented
;
1540 set_nocmp(PyObject
*self
, PyObject
*other
)
1542 PyErr_SetString(PyExc_TypeError
, "cannot compare sets using cmp()");
1547 set_add(PySetObject
*so
, PyObject
*key
)
1549 if (set_add_key(so
, key
) == -1)
1554 PyDoc_STRVAR(add_doc
,
1555 "Add an element to a set.\n\
1557 This has no effect if the element is already present.");
1560 set_contains(PySetObject
*so
, PyObject
*key
)
1565 rv
= set_contains_key(so
, key
);
1567 if (!PyAnySet_Check(key
) || !PyErr_ExceptionMatches(PyExc_TypeError
))
1570 tmpkey
= make_new_set(&PyFrozenSet_Type
, NULL
);
1573 set_swap_bodies((PySetObject
*)tmpkey
, (PySetObject
*)key
);
1574 rv
= set_contains(so
, tmpkey
);
1575 set_swap_bodies((PySetObject
*)tmpkey
, (PySetObject
*)key
);
1582 set_direct_contains(PySetObject
*so
, PyObject
*key
)
1586 result
= set_contains(so
, key
);
1589 return PyBool_FromLong(result
);
1592 PyDoc_STRVAR(contains_doc
, "x.__contains__(y) <==> y in x.");
1595 set_remove(PySetObject
*so
, PyObject
*key
)
1597 PyObject
*tmpkey
, *result
;
1600 rv
= set_discard_key(so
, key
);
1602 if (!PyAnySet_Check(key
) || !PyErr_ExceptionMatches(PyExc_TypeError
))
1605 tmpkey
= make_new_set(&PyFrozenSet_Type
, NULL
);
1608 set_swap_bodies((PySetObject
*)tmpkey
, (PySetObject
*)key
);
1609 result
= set_remove(so
, tmpkey
);
1610 set_swap_bodies((PySetObject
*)tmpkey
, (PySetObject
*)key
);
1613 } else if (rv
== DISCARD_NOTFOUND
) {
1614 PyErr_SetObject(PyExc_KeyError
, key
);
1620 PyDoc_STRVAR(remove_doc
,
1621 "Remove an element from a set; it must be a member.\n\
1623 If the element is not a member, raise a KeyError.");
1626 set_discard(PySetObject
*so
, PyObject
*key
)
1628 PyObject
*tmpkey
, *result
;
1631 rv
= set_discard_key(so
, key
);
1633 if (!PyAnySet_Check(key
) || !PyErr_ExceptionMatches(PyExc_TypeError
))
1636 tmpkey
= make_new_set(&PyFrozenSet_Type
, NULL
);
1639 set_swap_bodies((PySetObject
*)tmpkey
, (PySetObject
*)key
);
1640 result
= set_discard(so
, tmpkey
);
1641 set_swap_bodies((PySetObject
*)tmpkey
, (PySetObject
*)key
);
1648 PyDoc_STRVAR(discard_doc
,
1649 "Remove an element from a set if it is a member.\n\
1651 If the element is not a member, do nothing.");
1654 set_reduce(PySetObject
*so
)
1656 PyObject
*keys
=NULL
, *args
=NULL
, *result
=NULL
, *dict
=NULL
;
1658 keys
= PySequence_List((PyObject
*)so
);
1661 args
= PyTuple_Pack(1, keys
);
1664 dict
= PyObject_GetAttrString((PyObject
*)so
, "__dict__");
1670 result
= PyTuple_Pack(3, so
->ob_type
, args
, dict
);
1678 PyDoc_STRVAR(reduce_doc
, "Return state information for pickling.");
1681 set_init(PySetObject
*self
, PyObject
*args
, PyObject
*kwds
)
1683 PyObject
*iterable
= NULL
;
1685 if (!PyAnySet_Check(self
))
1687 if (!PyArg_UnpackTuple(args
, self
->ob_type
->tp_name
, 0, 1, &iterable
))
1689 set_clear_internal(self
);
1691 if (iterable
== NULL
)
1693 return set_update_internal(self
, iterable
);
1696 static PySequenceMethods set_as_sequence
= {
1697 set_len
, /* sq_length */
1702 0, /* sq_ass_item */
1703 0, /* sq_ass_slice */
1704 (objobjproc
)set_contains
, /* sq_contains */
1707 /* set object ********************************************************/
1710 static PyObject
*test_c_api(PySetObject
*so
);
1712 PyDoc_STRVAR(test_c_api_doc
, "Exercises C API. Returns True.\n\
1713 All is well if assertions don't fail.");
1716 static PyMethodDef set_methods
[] = {
1717 {"add", (PyCFunction
)set_add
, METH_O
,
1719 {"clear", (PyCFunction
)set_clear
, METH_NOARGS
,
1721 {"__contains__",(PyCFunction
)set_direct_contains
, METH_O
| METH_COEXIST
,
1723 {"copy", (PyCFunction
)set_copy
, METH_NOARGS
,
1725 {"discard", (PyCFunction
)set_discard
, METH_O
,
1727 {"difference", (PyCFunction
)set_difference
, METH_O
,
1729 {"difference_update", (PyCFunction
)set_difference_update
, METH_O
,
1730 difference_update_doc
},
1731 {"intersection",(PyCFunction
)set_intersection
, METH_O
,
1733 {"intersection_update",(PyCFunction
)set_intersection_update
, METH_O
,
1734 intersection_update_doc
},
1735 {"issubset", (PyCFunction
)set_issubset
, METH_O
,
1737 {"issuperset", (PyCFunction
)set_issuperset
, METH_O
,
1739 {"pop", (PyCFunction
)set_pop
, METH_NOARGS
,
1741 {"__reduce__", (PyCFunction
)set_reduce
, METH_NOARGS
,
1743 {"remove", (PyCFunction
)set_remove
, METH_O
,
1745 {"symmetric_difference",(PyCFunction
)set_symmetric_difference
, METH_O
,
1746 symmetric_difference_doc
},
1747 {"symmetric_difference_update",(PyCFunction
)set_symmetric_difference_update
, METH_O
,
1748 symmetric_difference_update_doc
},
1750 {"test_c_api", (PyCFunction
)test_c_api
, METH_NOARGS
,
1753 {"union", (PyCFunction
)set_union
, METH_O
,
1755 {"update", (PyCFunction
)set_update
, METH_O
,
1757 {NULL
, NULL
} /* sentinel */
1760 static PyNumberMethods set_as_number
= {
1762 (binaryfunc
)set_sub
, /*nb_subtract*/
1775 (binaryfunc
)set_and
, /*nb_and*/
1776 (binaryfunc
)set_xor
, /*nb_xor*/
1777 (binaryfunc
)set_or
, /*nb_or*/
1784 0, /*nb_inplace_add*/
1785 (binaryfunc
)set_isub
, /*nb_inplace_subtract*/
1786 0, /*nb_inplace_multiply*/
1787 0, /*nb_inplace_divide*/
1788 0, /*nb_inplace_remainder*/
1789 0, /*nb_inplace_power*/
1790 0, /*nb_inplace_lshift*/
1791 0, /*nb_inplace_rshift*/
1792 (binaryfunc
)set_iand
, /*nb_inplace_and*/
1793 (binaryfunc
)set_ixor
, /*nb_inplace_xor*/
1794 (binaryfunc
)set_ior
, /*nb_inplace_or*/
1797 PyDoc_STRVAR(set_doc
,
1798 "set(iterable) --> set object\n\
1800 Build an unordered collection.");
1802 PyTypeObject PySet_Type
= {
1803 PyObject_HEAD_INIT(&PyType_Type
)
1805 "set", /* tp_name */
1806 sizeof(PySetObject
), /* tp_basicsize */
1807 0, /* tp_itemsize */
1809 (destructor
)set_dealloc
, /* tp_dealloc */
1810 (printfunc
)set_tp_print
, /* tp_print */
1813 set_nocmp
, /* tp_compare */
1814 (reprfunc
)set_repr
, /* tp_repr */
1815 &set_as_number
, /* tp_as_number */
1816 &set_as_sequence
, /* tp_as_sequence */
1817 0, /* tp_as_mapping */
1818 set_nohash
, /* tp_hash */
1821 PyObject_GenericGetAttr
, /* tp_getattro */
1822 0, /* tp_setattro */
1823 0, /* tp_as_buffer */
1824 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
| Py_TPFLAGS_CHECKTYPES
|
1825 Py_TPFLAGS_BASETYPE
, /* tp_flags */
1826 set_doc
, /* tp_doc */
1827 (traverseproc
)set_traverse
, /* tp_traverse */
1828 (inquiry
)set_clear_internal
, /* tp_clear */
1829 (richcmpfunc
)set_richcompare
, /* tp_richcompare */
1830 offsetof(PySetObject
, weakreflist
), /* tp_weaklistoffset */
1831 (getiterfunc
)set_iter
, /* tp_iter */
1832 0, /* tp_iternext */
1833 set_methods
, /* tp_methods */
1838 0, /* tp_descr_get */
1839 0, /* tp_descr_set */
1840 0, /* tp_dictoffset */
1841 (initproc
)set_init
, /* tp_init */
1842 PyType_GenericAlloc
, /* tp_alloc */
1843 set_new
, /* tp_new */
1844 PyObject_GC_Del
, /* tp_free */
1847 /* frozenset object ********************************************************/
1850 static PyMethodDef frozenset_methods
[] = {
1851 {"__contains__",(PyCFunction
)set_direct_contains
, METH_O
| METH_COEXIST
,
1853 {"copy", (PyCFunction
)frozenset_copy
, METH_NOARGS
,
1855 {"difference", (PyCFunction
)set_difference
, METH_O
,
1857 {"intersection",(PyCFunction
)set_intersection
, METH_O
,
1859 {"issubset", (PyCFunction
)set_issubset
, METH_O
,
1861 {"issuperset", (PyCFunction
)set_issuperset
, METH_O
,
1863 {"__reduce__", (PyCFunction
)set_reduce
, METH_NOARGS
,
1865 {"symmetric_difference",(PyCFunction
)set_symmetric_difference
, METH_O
,
1866 symmetric_difference_doc
},
1867 {"union", (PyCFunction
)set_union
, METH_O
,
1869 {NULL
, NULL
} /* sentinel */
1872 static PyNumberMethods frozenset_as_number
= {
1874 (binaryfunc
)set_sub
, /*nb_subtract*/
1887 (binaryfunc
)set_and
, /*nb_and*/
1888 (binaryfunc
)set_xor
, /*nb_xor*/
1889 (binaryfunc
)set_or
, /*nb_or*/
1892 PyDoc_STRVAR(frozenset_doc
,
1893 "frozenset(iterable) --> frozenset object\n\
1895 Build an immutable unordered collection.");
1897 PyTypeObject PyFrozenSet_Type
= {
1898 PyObject_HEAD_INIT(&PyType_Type
)
1900 "frozenset", /* tp_name */
1901 sizeof(PySetObject
), /* tp_basicsize */
1902 0, /* tp_itemsize */
1904 (destructor
)set_dealloc
, /* tp_dealloc */
1905 (printfunc
)set_tp_print
, /* tp_print */
1908 set_nocmp
, /* tp_compare */
1909 (reprfunc
)set_repr
, /* tp_repr */
1910 &frozenset_as_number
, /* tp_as_number */
1911 &set_as_sequence
, /* tp_as_sequence */
1912 0, /* tp_as_mapping */
1913 frozenset_hash
, /* tp_hash */
1916 PyObject_GenericGetAttr
, /* tp_getattro */
1917 0, /* tp_setattro */
1918 0, /* tp_as_buffer */
1919 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
| Py_TPFLAGS_CHECKTYPES
|
1920 Py_TPFLAGS_BASETYPE
, /* tp_flags */
1921 frozenset_doc
, /* tp_doc */
1922 (traverseproc
)set_traverse
, /* tp_traverse */
1923 (inquiry
)set_clear_internal
, /* tp_clear */
1924 (richcmpfunc
)set_richcompare
, /* tp_richcompare */
1925 offsetof(PySetObject
, weakreflist
), /* tp_weaklistoffset */
1926 (getiterfunc
)set_iter
, /* tp_iter */
1927 0, /* tp_iternext */
1928 frozenset_methods
, /* tp_methods */
1933 0, /* tp_descr_get */
1934 0, /* tp_descr_set */
1935 0, /* tp_dictoffset */
1937 PyType_GenericAlloc
, /* tp_alloc */
1938 frozenset_new
, /* tp_new */
1939 PyObject_GC_Del
, /* tp_free */
1943 /***** C API functions *************************************************/
1946 PySet_New(PyObject
*iterable
)
1948 return make_new_set(&PySet_Type
, iterable
);
1952 PyFrozenSet_New(PyObject
*iterable
)
1954 PyObject
*args
, *result
;
1956 if (iterable
== NULL
)
1957 args
= PyTuple_New(0);
1959 args
= PyTuple_Pack(1, iterable
);
1962 result
= frozenset_new(&PyFrozenSet_Type
, args
, NULL
);
1968 PySet_Size(PyObject
*anyset
)
1970 if (!PyAnySet_Check(anyset
)) {
1971 PyErr_BadInternalCall();
1974 return PySet_GET_SIZE(anyset
);
1978 PySet_Clear(PyObject
*set
)
1980 if (!PyType_IsSubtype(set
->ob_type
, &PySet_Type
)) {
1981 PyErr_BadInternalCall();
1984 return set_clear_internal((PySetObject
*)set
);
1988 PySet_Contains(PyObject
*anyset
, PyObject
*key
)
1990 if (!PyAnySet_Check(anyset
)) {
1991 PyErr_BadInternalCall();
1994 return set_contains_key((PySetObject
*)anyset
, key
);
1998 PySet_Discard(PyObject
*set
, PyObject
*key
)
2000 if (!PyType_IsSubtype(set
->ob_type
, &PySet_Type
)) {
2001 PyErr_BadInternalCall();
2004 return set_discard_key((PySetObject
*)set
, key
);
2008 PySet_Add(PyObject
*set
, PyObject
*key
)
2010 if (!PyType_IsSubtype(set
->ob_type
, &PySet_Type
)) {
2011 PyErr_BadInternalCall();
2014 return set_add_key((PySetObject
*)set
, key
);
2018 _PySet_Next(PyObject
*set
, Py_ssize_t
*pos
, PyObject
**entry
)
2020 setentry
*entry_ptr
;
2022 if (!PyAnySet_Check(set
)) {
2023 PyErr_BadInternalCall();
2026 if (set_next((PySetObject
*)set
, pos
, &entry_ptr
) == 0)
2028 *entry
= entry_ptr
->key
;
2033 PySet_Pop(PyObject
*set
)
2035 if (!PyType_IsSubtype(set
->ob_type
, &PySet_Type
)) {
2036 PyErr_BadInternalCall();
2039 return set_pop((PySetObject
*)set
);
2043 _PySet_Update(PyObject
*set
, PyObject
*iterable
)
2045 if (!PyType_IsSubtype(set
->ob_type
, &PySet_Type
)) {
2046 PyErr_BadInternalCall();
2049 return set_update_internal((PySetObject
*)set
, iterable
);
2054 /* Test code to be called with any three element set.
2055 Returns True and original set is restored. */
2057 #define assertRaises(call_return_value, exception) \
2059 assert(call_return_value); \
2060 assert(PyErr_ExceptionMatches(exception)); \
2065 test_c_api(PySetObject
*so
)
2070 PyObject
*elem
, *dup
, *t
, *f
, *dup2
;
2071 PyObject
*ob
= (PyObject
*)so
;
2073 /* Verify preconditions and exercise type/size checks */
2074 assert(PyAnySet_Check(ob
));
2075 assert(PyAnySet_CheckExact(ob
));
2076 assert(!PyFrozenSet_CheckExact(ob
));
2077 assert(PySet_Size(ob
) == 3);
2078 assert(PySet_GET_SIZE(ob
) == 3);
2080 /* Raise TypeError for non-iterable constructor arguments */
2081 assertRaises(PySet_New(Py_None
) == NULL
, PyExc_TypeError
);
2082 assertRaises(PyFrozenSet_New(Py_None
) == NULL
, PyExc_TypeError
);
2084 /* Raise TypeError for unhashable key */
2085 dup
= PySet_New(ob
);
2086 assertRaises(PySet_Discard(ob
, dup
) == -1, PyExc_TypeError
);
2087 assertRaises(PySet_Contains(ob
, dup
) == -1, PyExc_TypeError
);
2088 assertRaises(PySet_Add(ob
, dup
) == -1, PyExc_TypeError
);
2090 /* Exercise successful pop, contains, add, and discard */
2091 elem
= PySet_Pop(ob
);
2092 assert(PySet_Contains(ob
, elem
) == 0);
2093 assert(PySet_GET_SIZE(ob
) == 2);
2094 assert(PySet_Add(ob
, elem
) == 0);
2095 assert(PySet_Contains(ob
, elem
) == 1);
2096 assert(PySet_GET_SIZE(ob
) == 3);
2097 assert(PySet_Discard(ob
, elem
) == 1);
2098 assert(PySet_GET_SIZE(ob
) == 2);
2099 assert(PySet_Discard(ob
, elem
) == 0);
2100 assert(PySet_GET_SIZE(ob
) == 2);
2102 /* Exercise clear */
2103 dup2
= PySet_New(dup
);
2104 assert(PySet_Clear(dup2
) == 0);
2105 assert(PySet_Size(dup2
) == 0);
2108 /* Raise SystemError on clear or update of frozen set */
2109 f
= PyFrozenSet_New(dup
);
2110 assertRaises(PySet_Clear(f
) == -1, PyExc_SystemError
);
2111 assertRaises(_PySet_Update(f
, dup
) == -1, PyExc_SystemError
);
2114 /* Exercise direct iteration */
2116 while (_PySet_Next((PyObject
*)dup
, &i
, &elem
)) {
2117 s
= PyString_AsString(elem
);
2118 assert(s
&& (s
[0] == 'a' || s
[0] == 'b' || s
[0] == 'c'));
2123 /* Exercise updates */
2124 dup2
= PySet_New(NULL
);
2125 assert(_PySet_Update(dup2
, dup
) == 0);
2126 assert(PySet_Size(dup2
) == 3);
2127 assert(_PySet_Update(dup2
, dup
) == 0);
2128 assert(PySet_Size(dup2
) == 3);
2131 /* Raise SystemError when self argument is not a set or frozenset. */
2133 assertRaises(PySet_Size(t
) == -1, PyExc_SystemError
);
2134 assertRaises(PySet_Contains(t
, elem
) == -1, PyExc_SystemError
);
2137 /* Raise SystemError when self argument is not a set. */
2138 f
= PyFrozenSet_New(dup
);
2139 assert(PySet_Size(f
) == 3);
2140 assert(PyFrozenSet_CheckExact(f
));
2141 assertRaises(PySet_Add(f
, elem
) == -1, PyExc_SystemError
);
2142 assertRaises(PySet_Discard(f
, elem
) == -1, PyExc_SystemError
);
2143 assertRaises(PySet_Pop(f
) == NULL
, PyExc_SystemError
);
2146 /* Raise KeyError when popping from an empty set */
2147 assert(PyNumber_InPlaceSubtract(ob
, ob
) == ob
);
2149 assert(PySet_GET_SIZE(ob
) == 0);
2150 assertRaises(PySet_Pop(ob
) == NULL
, PyExc_KeyError
);
2152 /* Restore the set from the copy using the PyNumber API */
2153 assert(PyNumber_InPlaceOr(ob
, dup
) == ob
);
2156 /* Verify constructors accept NULL arguments */
2157 f
= PySet_New(NULL
);
2159 assert(PySet_GET_SIZE(f
) == 0);
2161 f
= PyFrozenSet_New(NULL
);
2163 assert(PyFrozenSet_CheckExact(f
));
2164 assert(PySet_GET_SIZE(f
) == 0);