PageRenderTime 314ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 1ms

/Objects/setobject.c

http://unladen-swallow.googlecode.com/
C | 2493 lines | 2042 code | 274 blank | 177 comment | 583 complexity | 83aa6706f588590611971490b493aaa4 MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. /* set object implementation
  2. Written and maintained by Raymond D. Hettinger <python@rcn.com>
  3. Derived from Lib/sets.py and Objects/dictobject.c.
  4. Copyright (c) 2003-2007 Python Software Foundation.
  5. All rights reserved.
  6. */
  7. #include "Python.h"
  8. #include "structmember.h"
  9. /* Set a key error with the specified argument, wrapping it in a
  10. * tuple automatically so that tuple keys are not unpacked as the
  11. * exception arguments. */
  12. static void
  13. set_key_error(PyObject *arg)
  14. {
  15. PyObject *tup;
  16. tup = PyTuple_Pack(1, arg);
  17. if (!tup)
  18. return; /* caller will expect error to be set anyway */
  19. PyErr_SetObject(PyExc_KeyError, tup);
  20. Py_DECREF(tup);
  21. }
  22. /* This must be >= 1. */
  23. #define PERTURB_SHIFT 5
  24. /* Object used as dummy key to fill deleted entries */
  25. static PyObject *dummy = NULL; /* Initialized by first call to make_new_set() */
  26. #ifdef Py_REF_DEBUG
  27. PyObject *
  28. _PySet_Dummy(void)
  29. {
  30. return dummy;
  31. }
  32. #endif
  33. #define INIT_NONZERO_SET_SLOTS(so) do { \
  34. (so)->table = (so)->smalltable; \
  35. (so)->mask = PySet_MINSIZE - 1; \
  36. (so)->hash = -1; \
  37. } while(0)
  38. #define EMPTY_TO_MINSIZE(so) do { \
  39. memset((so)->smalltable, 0, sizeof((so)->smalltable)); \
  40. (so)->used = (so)->fill = 0; \
  41. INIT_NONZERO_SET_SLOTS(so); \
  42. } while(0)
  43. /* Reuse scheme to save calls to malloc, free, and memset */
  44. #ifndef PySet_MAXFREELIST
  45. #define PySet_MAXFREELIST 80
  46. #endif
  47. static PySetObject *free_list[PySet_MAXFREELIST];
  48. static int numfree = 0;
  49. /*
  50. The basic lookup function used by all operations.
  51. This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
  52. Open addressing is preferred over chaining since the link overhead for
  53. chaining would be substantial (100% with typical malloc overhead).
  54. The initial probe index is computed as hash mod the table size. Subsequent
  55. probe indices are computed as explained in Objects/dictobject.c.
  56. All arithmetic on hash should ignore overflow.
  57. Unlike the dictionary implementation, the lookkey functions can return
  58. NULL if the rich comparison returns an error.
  59. */
  60. static setentry *
  61. set_lookkey(PySetObject *so, PyObject *key, register long hash)
  62. {
  63. register Py_ssize_t i;
  64. register size_t perturb;
  65. register setentry *freeslot;
  66. register size_t mask = so->mask;
  67. setentry *table = so->table;
  68. register setentry *entry;
  69. register int cmp;
  70. PyObject *startkey;
  71. i = hash & mask;
  72. entry = &table[i];
  73. if (entry->key == NULL || entry->key == key)
  74. return entry;
  75. if (entry->key == dummy)
  76. freeslot = entry;
  77. else {
  78. if (entry->hash == hash) {
  79. startkey = entry->key;
  80. Py_INCREF(startkey);
  81. cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
  82. Py_DECREF(startkey);
  83. if (cmp < 0)
  84. return NULL;
  85. if (table == so->table && entry->key == startkey) {
  86. if (cmp > 0)
  87. return entry;
  88. }
  89. else {
  90. /* The compare did major nasty stuff to the
  91. * set: start over.
  92. */
  93. return set_lookkey(so, key, hash);
  94. }
  95. }
  96. freeslot = NULL;
  97. }
  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)
  105. entry = freeslot;
  106. break;
  107. }
  108. if (entry->key == key)
  109. break;
  110. if (entry->hash == hash && entry->key != dummy) {
  111. startkey = entry->key;
  112. Py_INCREF(startkey);
  113. cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
  114. Py_DECREF(startkey);
  115. if (cmp < 0)
  116. return NULL;
  117. if (table == so->table && entry->key == startkey) {
  118. if (cmp > 0)
  119. break;
  120. }
  121. else {
  122. /* The compare did major nasty stuff to the
  123. * set: start over.
  124. */
  125. return set_lookkey(so, key, hash);
  126. }
  127. }
  128. else if (entry->key == dummy && freeslot == NULL)
  129. freeslot = entry;
  130. }
  131. return entry;
  132. }
  133. /*
  134. * Hacked up version of set_lookkey which can assume keys are always strings;
  135. * This means we can always use _PyString_Eq directly and not have to check to
  136. * see if the comparison altered the table.
  137. */
  138. static setentry *
  139. set_lookkey_string(PySetObject *so, PyObject *key, register long hash)
  140. {
  141. register Py_ssize_t i;
  142. register size_t perturb;
  143. register setentry *freeslot;
  144. register size_t mask = so->mask;
  145. setentry *table = so->table;
  146. 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
  150. that here. */
  151. if (!PyString_CheckExact(key)) {
  152. so->lookup = set_lookkey;
  153. return set_lookkey(so, key, hash);
  154. }
  155. i = hash & mask;
  156. entry = &table[i];
  157. if (entry->key == NULL || entry->key == key)
  158. return entry;
  159. if (entry->key == dummy)
  160. freeslot = entry;
  161. else {
  162. if (entry->hash == hash && _PyString_Eq(entry->key, key))
  163. return entry;
  164. freeslot = NULL;
  165. }
  166. /* In the loop, key == dummy is by far (factor of 100s) the
  167. least likely outcome, so test for that last. */
  168. for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
  169. i = (i << 2) + i + perturb + 1;
  170. entry = &table[i & mask];
  171. if (entry->key == NULL)
  172. return freeslot == NULL ? entry : freeslot;
  173. if (entry->key == key
  174. || (entry->hash == hash
  175. && entry->key != dummy
  176. && _PyString_Eq(entry->key, key)))
  177. return entry;
  178. if (entry->key == dummy && freeslot == NULL)
  179. freeslot = entry;
  180. }
  181. assert(0); /* NOT REACHED */
  182. return 0;
  183. }
  184. /*
  185. Internal routine to insert a new key into the table.
  186. Used by the public insert routine.
  187. Eats a reference to key.
  188. */
  189. static int
  190. set_insert_key(register PySetObject *so, PyObject *key, long hash)
  191. {
  192. register setentry *entry;
  193. typedef setentry *(*lookupfunc)(PySetObject *, PyObject *, long);
  194. assert(so->lookup != NULL);
  195. entry = so->lookup(so, key, hash);
  196. if (entry == NULL)
  197. return -1;
  198. if (entry->key == NULL) {
  199. /* UNUSED */
  200. so->fill++;
  201. entry->key = key;
  202. entry->hash = hash;
  203. so->used++;
  204. } else if (entry->key == dummy) {
  205. /* DUMMY */
  206. entry->key = key;
  207. entry->hash = hash;
  208. so->used++;
  209. Py_DECREF(dummy);
  210. } else {
  211. /* ACTIVE */
  212. Py_DECREF(key);
  213. }
  214. return 0;
  215. }
  216. /*
  217. Internal routine used by set_table_resize() to insert an item which is
  218. known to be absent from the set. This routine also assumes that
  219. the set contains no deleted entries. Besides the performance benefit,
  220. using set_insert_clean() in set_table_resize() is dangerous (SF bug #1456209).
  221. Note that no refcounts are changed by this routine; if needed, the caller
  222. is responsible for incref'ing `key`.
  223. */
  224. static void
  225. set_insert_clean(register PySetObject *so, PyObject *key, long hash)
  226. {
  227. register size_t i;
  228. register size_t perturb;
  229. register size_t mask = (size_t)so->mask;
  230. setentry *table = so->table;
  231. register setentry *entry;
  232. i = hash & mask;
  233. entry = &table[i];
  234. for (perturb = hash; entry->key != NULL; perturb >>= PERTURB_SHIFT) {
  235. i = (i << 2) + i + perturb + 1;
  236. entry = &table[i & mask];
  237. }
  238. so->fill++;
  239. entry->key = key;
  240. entry->hash = hash;
  241. so->used++;
  242. }
  243. /*
  244. Restructure the table by allocating a new table and reinserting all
  245. keys again. When entries have been deleted, the new table may
  246. actually be smaller than the old one.
  247. */
  248. static int
  249. set_table_resize(PySetObject *so, Py_ssize_t minused)
  250. {
  251. Py_ssize_t newsize;
  252. setentry *oldtable, *newtable, *entry;
  253. Py_ssize_t i;
  254. int is_oldtable_malloced;
  255. setentry small_copy[PySet_MINSIZE];
  256. assert(minused >= 0);
  257. /* Find the smallest table size > minused. */
  258. for (newsize = PySet_MINSIZE;
  259. newsize <= minused && newsize > 0;
  260. newsize <<= 1)
  261. ;
  262. if (newsize <= 0) {
  263. PyErr_NoMemory();
  264. return -1;
  265. }
  266. /* Get space for a new table. */
  267. oldtable = so->table;
  268. assert(oldtable != NULL);
  269. is_oldtable_malloced = oldtable != so->smalltable;
  270. if (newsize == PySet_MINSIZE) {
  271. /* A large table is shrinking, or we can't get any smaller. */
  272. newtable = so->smalltable;
  273. if (newtable == oldtable) {
  274. if (so->fill == so->used) {
  275. /* No dummies, so no point doing anything. */
  276. return 0;
  277. }
  278. /* We're not going to resize it, but rebuild the
  279. table anyway to purge old dummy entries.
  280. Subtle: This is *necessary* if fill==size,
  281. as set_lookkey needs at least one virgin slot to
  282. terminate failing searches. If fill < size, it's
  283. merely desirable, as dummies slow searches. */
  284. assert(so->fill > so->used);
  285. memcpy(small_copy, oldtable, sizeof(small_copy));
  286. oldtable = small_copy;
  287. }
  288. }
  289. else {
  290. newtable = PyMem_NEW(setentry, newsize);
  291. if (newtable == NULL) {
  292. PyErr_NoMemory();
  293. return -1;
  294. }
  295. }
  296. /* Make the set empty, using the new table. */
  297. assert(newtable != oldtable);
  298. so->table = newtable;
  299. so->mask = newsize - 1;
  300. memset(newtable, 0, sizeof(setentry) * newsize);
  301. so->used = 0;
  302. i = so->fill;
  303. so->fill = 0;
  304. /* Copy the data over; this is refcount-neutral for active entries;
  305. dummy entries aren't copied over, of course */
  306. for (entry = oldtable; i > 0; entry++) {
  307. if (entry->key == NULL) {
  308. /* UNUSED */
  309. ;
  310. } else if (entry->key == dummy) {
  311. /* DUMMY */
  312. --i;
  313. assert(entry->key == dummy);
  314. Py_DECREF(entry->key);
  315. } else {
  316. /* ACTIVE */
  317. --i;
  318. set_insert_clean(so, entry->key, entry->hash);
  319. }
  320. }
  321. if (is_oldtable_malloced)
  322. PyMem_DEL(oldtable);
  323. return 0;
  324. }
  325. /* CAUTION: set_add_key/entry() must guarantee it won't resize the table */
  326. static int
  327. set_add_entry(register PySetObject *so, setentry *entry)
  328. {
  329. register Py_ssize_t n_used;
  330. assert(so->fill <= so->mask); /* at least one empty slot */
  331. n_used = so->used;
  332. Py_INCREF(entry->key);
  333. if (set_insert_key(so, entry->key, entry->hash) == -1) {
  334. Py_DECREF(entry->key);
  335. return -1;
  336. }
  337. if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2))
  338. return 0;
  339. return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
  340. }
  341. static int
  342. set_add_key(register PySetObject *so, PyObject *key)
  343. {
  344. register long hash;
  345. register Py_ssize_t n_used;
  346. if (!PyString_CheckExact(key) ||
  347. (hash = ((PyStringObject *) key)->ob_shash) == -1) {
  348. hash = PyObject_Hash(key);
  349. if (hash == -1)
  350. return -1;
  351. }
  352. assert(so->fill <= so->mask); /* at least one empty slot */
  353. n_used = so->used;
  354. Py_INCREF(key);
  355. if (set_insert_key(so, key, hash) == -1) {
  356. Py_DECREF(key);
  357. return -1;
  358. }
  359. if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2))
  360. return 0;
  361. return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
  362. }
  363. #define DISCARD_NOTFOUND 0
  364. #define DISCARD_FOUND 1
  365. static int
  366. set_discard_entry(PySetObject *so, setentry *oldentry)
  367. { register setentry *entry;
  368. PyObject *old_key;
  369. entry = (so->lookup)(so, oldentry->key, oldentry->hash);
  370. if (entry == NULL)
  371. return -1;
  372. if (entry->key == NULL || entry->key == dummy)
  373. return DISCARD_NOTFOUND;
  374. old_key = entry->key;
  375. Py_INCREF(dummy);
  376. entry->key = dummy;
  377. so->used--;
  378. Py_DECREF(old_key);
  379. return DISCARD_FOUND;
  380. }
  381. static int
  382. set_discard_key(PySetObject *so, PyObject *key)
  383. {
  384. register long hash;
  385. register setentry *entry;
  386. PyObject *old_key;
  387. assert (PyAnySet_Check(so));
  388. if (!PyString_CheckExact(key) ||
  389. (hash = ((PyStringObject *) key)->ob_shash) == -1) {
  390. hash = PyObject_Hash(key);
  391. if (hash == -1)
  392. return -1;
  393. }
  394. entry = (so->lookup)(so, key, hash);
  395. if (entry == NULL)
  396. return -1;
  397. if (entry->key == NULL || entry->key == dummy)
  398. return DISCARD_NOTFOUND;
  399. old_key = entry->key;
  400. Py_INCREF(dummy);
  401. entry->key = dummy;
  402. so->used--;
  403. Py_DECREF(old_key);
  404. return DISCARD_FOUND;
  405. }
  406. static int
  407. set_clear_internal(PySetObject *so)
  408. {
  409. setentry *entry, *table;
  410. int table_is_malloced;
  411. Py_ssize_t fill;
  412. setentry small_copy[PySet_MINSIZE];
  413. #ifdef Py_DEBUG
  414. Py_ssize_t i, n;
  415. assert (PyAnySet_Check(so));
  416. n = so->mask + 1;
  417. i = 0;
  418. #endif
  419. table = so->table;
  420. assert(table != NULL);
  421. table_is_malloced = table != so->smalltable;
  422. /* This is delicate. During the process of clearing the set,
  423. * decrefs can cause the set to mutate. To avoid fatal confusion
  424. * (voice of experience), we have to make the set empty before
  425. * clearing the slots, and never refer to anything via so->ref while
  426. * clearing.
  427. */
  428. fill = so->fill;
  429. if (table_is_malloced)
  430. EMPTY_TO_MINSIZE(so);
  431. else if (fill > 0) {
  432. /* It's a small table with something that needs to be cleared.
  433. * Afraid the only safe way is to copy the set entries into
  434. * another small table first.
  435. */
  436. memcpy(small_copy, table, sizeof(small_copy));
  437. table = small_copy;
  438. EMPTY_TO_MINSIZE(so);
  439. }
  440. /* 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.
  444. */
  445. for (entry = table; fill > 0; ++entry) {
  446. #ifdef Py_DEBUG
  447. assert(i < n);
  448. ++i;
  449. #endif
  450. if (entry->key) {
  451. --fill;
  452. Py_DECREF(entry->key);
  453. }
  454. #ifdef Py_DEBUG
  455. else
  456. assert(entry->key == NULL);
  457. #endif
  458. }
  459. if (table_is_malloced)
  460. PyMem_DEL(table);
  461. return 0;
  462. }
  463. /*
  464. * Iterate over a set table. Use like so:
  465. *
  466. * Py_ssize_t pos;
  467. * setentry *entry;
  468. * pos = 0; # important! pos should not otherwise be changed by you
  469. * while (set_next(yourset, &pos, &entry)) {
  470. * Refer to borrowed reference in entry->key.
  471. * }
  472. *
  473. * CAUTION: In general, it isn't safe to use set_next in a loop that
  474. * mutates the table.
  475. */
  476. static int
  477. set_next(PySetObject *so, Py_ssize_t *pos_ptr, setentry **entry_ptr)
  478. {
  479. Py_ssize_t i;
  480. Py_ssize_t mask;
  481. register setentry *table;
  482. assert (PyAnySet_Check(so));
  483. i = *pos_ptr;
  484. assert(i >= 0);
  485. table = so->table;
  486. mask = so->mask;
  487. while (i <= mask && (table[i].key == NULL || table[i].key == dummy))
  488. i++;
  489. *pos_ptr = i+1;
  490. if (i > mask)
  491. return 0;
  492. assert(table[i].key != NULL);
  493. *entry_ptr = &table[i];
  494. return 1;
  495. }
  496. static void
  497. set_dealloc(PySetObject *so)
  498. {
  499. register setentry *entry;
  500. Py_ssize_t fill = so->fill;
  501. PyObject_GC_UnTrack(so);
  502. Py_TRASHCAN_SAFE_BEGIN(so)
  503. if (so->weakreflist != NULL)
  504. PyObject_ClearWeakRefs((PyObject *) so);
  505. for (entry = so->table; fill > 0; entry++) {
  506. if (entry->key) {
  507. --fill;
  508. Py_DECREF(entry->key);
  509. }
  510. }
  511. if (so->table != so->smalltable)
  512. PyMem_DEL(so->table);
  513. if (numfree < PySet_MAXFREELIST && PyAnySet_CheckExact(so))
  514. free_list[numfree++] = so;
  515. else
  516. Py_TYPE(so)->tp_free(so);
  517. Py_TRASHCAN_SAFE_END(so)
  518. }
  519. static int
  520. set_tp_print(PySetObject *so, FILE *fp, int flags)
  521. {
  522. setentry *entry;
  523. Py_ssize_t pos=0;
  524. char *emit = ""; /* No separator emitted on first pass */
  525. char *separator = ", ";
  526. int status = Py_ReprEnter((PyObject*)so);
  527. if (status != 0) {
  528. if (status < 0)
  529. return status;
  530. Py_BEGIN_ALLOW_THREADS
  531. fprintf(fp, "%s(...)", so->ob_type->tp_name);
  532. Py_END_ALLOW_THREADS
  533. return 0;
  534. }
  535. Py_BEGIN_ALLOW_THREADS
  536. fprintf(fp, "%s([", so->ob_type->tp_name);
  537. Py_END_ALLOW_THREADS
  538. while (set_next(so, &pos, &entry)) {
  539. Py_BEGIN_ALLOW_THREADS
  540. fputs(emit, fp);
  541. Py_END_ALLOW_THREADS
  542. emit = separator;
  543. if (PyObject_Print(entry->key, fp, 0) != 0) {
  544. Py_ReprLeave((PyObject*)so);
  545. return -1;
  546. }
  547. }
  548. Py_BEGIN_ALLOW_THREADS
  549. fputs("])", fp);
  550. Py_END_ALLOW_THREADS
  551. Py_ReprLeave((PyObject*)so);
  552. return 0;
  553. }
  554. static PyObject *
  555. set_repr(PySetObject *so)
  556. {
  557. PyObject *keys, *result=NULL, *listrepr;
  558. int status = Py_ReprEnter((PyObject*)so);
  559. if (status != 0) {
  560. if (status < 0)
  561. return NULL;
  562. return PyString_FromFormat("%s(...)", so->ob_type->tp_name);
  563. }
  564. keys = PySequence_List((PyObject *)so);
  565. if (keys == NULL)
  566. goto done;
  567. listrepr = PyObject_Repr(keys);
  568. Py_DECREF(keys);
  569. if (listrepr == NULL)
  570. goto done;
  571. result = PyString_FromFormat("%s(%s)", so->ob_type->tp_name,
  572. PyString_AS_STRING(listrepr));
  573. Py_DECREF(listrepr);
  574. done:
  575. Py_ReprLeave((PyObject*)so);
  576. return result;
  577. }
  578. static Py_ssize_t
  579. set_len(PyObject *so)
  580. {
  581. return ((PySetObject *)so)->used;
  582. }
  583. static int
  584. set_merge(PySetObject *so, PyObject *otherset)
  585. {
  586. PySetObject *other;
  587. register Py_ssize_t i;
  588. register setentry *entry;
  589. assert (PyAnySet_Check(so));
  590. assert (PyAnySet_Check(otherset));
  591. other = (PySetObject*)otherset;
  592. if (other == so || other->used == 0)
  593. /* a.update(a) or a.update({}); nothing to do */
  594. return 0;
  595. /* Do one big resize at the start, rather than
  596. * incrementally resizing as we insert new keys. Expect
  597. * that there will be no (or few) overlapping keys.
  598. */
  599. if ((so->fill + other->used)*3 >= (so->mask+1)*2) {
  600. if (set_table_resize(so, (so->used + other->used)*2) != 0)
  601. return -1;
  602. }
  603. for (i = 0; i <= other->mask; i++) {
  604. entry = &other->table[i];
  605. if (entry->key != NULL &&
  606. entry->key != dummy) {
  607. Py_INCREF(entry->key);
  608. if (set_insert_key(so, entry->key, entry->hash) == -1) {
  609. Py_DECREF(entry->key);
  610. return -1;
  611. }
  612. }
  613. }
  614. return 0;
  615. }
  616. static int
  617. set_contains_key(PySetObject *so, PyObject *key)
  618. {
  619. long hash;
  620. setentry *entry;
  621. if (!PyString_CheckExact(key) ||
  622. (hash = ((PyStringObject *) key)->ob_shash) == -1) {
  623. hash = PyObject_Hash(key);
  624. if (hash == -1)
  625. return -1;
  626. }
  627. entry = (so->lookup)(so, key, hash);
  628. if (entry == NULL)
  629. return -1;
  630. key = entry->key;
  631. return key != NULL && key != dummy;
  632. }
  633. static int
  634. set_contains_entry(PySetObject *so, setentry *entry)
  635. {
  636. PyObject *key;
  637. setentry *lu_entry;
  638. lu_entry = (so->lookup)(so, entry->key, entry->hash);
  639. if (lu_entry == NULL)
  640. return -1;
  641. key = lu_entry->key;
  642. return key != NULL && key != dummy;
  643. }
  644. static PyObject *
  645. set_pop(PySetObject *so)
  646. {
  647. register Py_ssize_t i = 0;
  648. register setentry *entry;
  649. PyObject *key;
  650. assert (PyAnySet_Check(so));
  651. if (so->used == 0) {
  652. PyErr_SetString(PyExc_KeyError, "pop from an empty set");
  653. return NULL;
  654. }
  655. /* Set entry to "the first" unused or dummy set entry. We abuse
  656. * the hash field of slot 0 to hold a search finger:
  657. * If slot 0 has a value, use slot 0.
  658. * Else slot 0 is being used to hold a search finger,
  659. * and we use its hash value as the first index to look.
  660. */
  661. entry = &so->table[0];
  662. if (entry->key == NULL || entry->key == dummy) {
  663. i = entry->hash;
  664. /* The hash field may be a real hash value, or it may be a
  665. * legit search finger, or it may be a once-legit search
  666. * finger that's out of bounds now because it wrapped around
  667. * or the table shrunk -- simply make sure it's in bounds now.
  668. */
  669. if (i > so->mask || i < 1)
  670. i = 1; /* skip slot 0 */
  671. while ((entry = &so->table[i])->key == NULL || entry->key==dummy) {
  672. i++;
  673. if (i > so->mask)
  674. i = 1;
  675. }
  676. }
  677. key = entry->key;
  678. Py_INCREF(dummy);
  679. entry->key = dummy;
  680. so->used--;
  681. so->table[0].hash = i + 1; /* next place to start */
  682. return key;
  683. }
  684. PyDoc_STRVAR(pop_doc, "Remove and return an arbitrary set element.\n\
  685. Raises KeyError if the set is empty.");
  686. static int
  687. set_traverse(PySetObject *so, visitproc visit, void *arg)
  688. {
  689. Py_ssize_t pos = 0;
  690. setentry *entry;
  691. while (set_next(so, &pos, &entry))
  692. Py_VISIT(entry->key);
  693. return 0;
  694. }
  695. static long
  696. frozenset_hash(PyObject *self)
  697. {
  698. PySetObject *so = (PySetObject *)self;
  699. long h, hash = 1927868237L;
  700. setentry *entry;
  701. Py_ssize_t pos = 0;
  702. if (so->hash != -1)
  703. return so->hash;
  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. */
  711. h = entry->hash;
  712. hash ^= (h ^ (h << 16) ^ 89869747L) * 3644798167u;
  713. }
  714. hash = hash * 69069L + 907133923L;
  715. if (hash == -1)
  716. hash = 590923713L;
  717. so->hash = hash;
  718. return hash;
  719. }
  720. /***** Set iterator type ***********************************************/
  721. typedef struct {
  722. PyObject_HEAD
  723. PySetObject *si_set; /* Set to NULL when iterator is exhausted */
  724. Py_ssize_t si_used;
  725. Py_ssize_t si_pos;
  726. Py_ssize_t len;
  727. } setiterobject;
  728. static void
  729. setiter_dealloc(setiterobject *si)
  730. {
  731. Py_XDECREF(si->si_set);
  732. PyObject_GC_Del(si);
  733. }
  734. static int
  735. setiter_traverse(setiterobject *si, visitproc visit, void *arg)
  736. {
  737. Py_VISIT(si->si_set);
  738. return 0;
  739. }
  740. static PyObject *
  741. setiter_len(setiterobject *si)
  742. {
  743. Py_ssize_t len = 0;
  744. if (si->si_set != NULL && si->si_used == si->si_set->used)
  745. len = si->len;
  746. return PyInt_FromLong(len);
  747. }
  748. PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
  749. static PyMethodDef setiter_methods[] = {
  750. {"__length_hint__", (PyCFunction)setiter_len, METH_NOARGS, length_hint_doc},
  751. {NULL, NULL} /* sentinel */
  752. };
  753. static PyObject *setiter_iternext(setiterobject *si)
  754. {
  755. PyObject *key;
  756. register Py_ssize_t i, mask;
  757. register setentry *entry;
  758. PySetObject *so = si->si_set;
  759. if (so == NULL)
  760. return NULL;
  761. assert (PyAnySet_Check(so));
  762. if (si->si_used != so->used) {
  763. PyErr_SetString(PyExc_RuntimeError,
  764. "Set changed size during iteration");
  765. si->si_used = -1; /* Make this state sticky */
  766. return NULL;
  767. }
  768. i = si->si_pos;
  769. assert(i>=0);
  770. entry = so->table;
  771. mask = so->mask;
  772. while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy))
  773. i++;
  774. si->si_pos = i+1;
  775. if (i > mask)
  776. goto fail;
  777. si->len--;
  778. key = entry[i].key;
  779. Py_INCREF(key);
  780. return key;
  781. fail:
  782. Py_DECREF(so);
  783. si->si_set = NULL;
  784. return NULL;
  785. }
  786. static PyTypeObject PySetIter_Type = {
  787. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  788. "setiterator", /* tp_name */
  789. sizeof(setiterobject), /* tp_basicsize */
  790. 0, /* tp_itemsize */
  791. /* methods */
  792. (destructor)setiter_dealloc, /* tp_dealloc */
  793. 0, /* tp_print */
  794. 0, /* tp_getattr */
  795. 0, /* tp_setattr */
  796. 0, /* tp_compare */
  797. 0, /* tp_repr */
  798. 0, /* tp_as_number */
  799. 0, /* tp_as_sequence */
  800. 0, /* tp_as_mapping */
  801. 0, /* tp_hash */
  802. 0, /* tp_call */
  803. 0, /* tp_str */
  804. PyObject_GenericGetAttr, /* tp_getattro */
  805. 0, /* tp_setattro */
  806. 0, /* tp_as_buffer */
  807. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  808. 0, /* tp_doc */
  809. (traverseproc)setiter_traverse, /* tp_traverse */
  810. 0, /* tp_clear */
  811. 0, /* tp_richcompare */
  812. 0, /* tp_weaklistoffset */
  813. PyObject_SelfIter, /* tp_iter */
  814. (iternextfunc)setiter_iternext, /* tp_iternext */
  815. setiter_methods, /* tp_methods */
  816. 0,
  817. };
  818. static PyObject *
  819. set_iter(PySetObject *so)
  820. {
  821. setiterobject *si = PyObject_GC_New(setiterobject, &PySetIter_Type);
  822. if (si == NULL)
  823. return NULL;
  824. Py_INCREF(so);
  825. si->si_set = so;
  826. si->si_used = so->used;
  827. si->si_pos = 0;
  828. si->len = so->used;
  829. _PyObject_GC_TRACK(si);
  830. return (PyObject *)si;
  831. }
  832. static int
  833. set_update_internal(PySetObject *so, PyObject *other)
  834. {
  835. PyObject *key, *it;
  836. if (PyAnySet_Check(other))
  837. return set_merge(so, other);
  838. if (PyDict_CheckExact(other)) {
  839. PyObject *value;
  840. Py_ssize_t pos = 0;
  841. long hash;
  842. Py_ssize_t dictsize = PyDict_Size(other);
  843. /* Do one big resize at the start, rather than
  844. * incrementally resizing as we insert new keys. Expect
  845. * that there will be no (or few) overlapping keys.
  846. */
  847. if (dictsize == -1)
  848. return -1;
  849. if ((so->fill + dictsize)*3 >= (so->mask+1)*2) {
  850. if (set_table_resize(so, (so->used + dictsize)*2) != 0)
  851. return -1;
  852. }
  853. while (_PyDict_Next(other, &pos, &key, &value, &hash)) {
  854. setentry an_entry;
  855. an_entry.hash = hash;
  856. an_entry.key = key;
  857. if (set_add_entry(so, &an_entry) == -1)
  858. return -1;
  859. }
  860. return 0;
  861. }
  862. it = PyObject_GetIter(other);
  863. if (it == NULL)
  864. return -1;
  865. while ((key = PyIter_Next(it)) != NULL) {
  866. if (set_add_key(so, key) == -1) {
  867. Py_DECREF(it);
  868. Py_DECREF(key);
  869. return -1;
  870. }
  871. Py_DECREF(key);
  872. }
  873. Py_DECREF(it);
  874. if (PyErr_Occurred())
  875. return -1;
  876. return 0;
  877. }
  878. static PyObject *
  879. set_update(PySetObject *so, PyObject *args)
  880. {
  881. Py_ssize_t i;
  882. for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
  883. PyObject *other = PyTuple_GET_ITEM(args, i);
  884. if (set_update_internal(so, other) == -1)
  885. return NULL;
  886. }
  887. Py_RETURN_NONE;
  888. }
  889. PyDoc_STRVAR(update_doc,
  890. "Update a set with the union of itself and others.");
  891. static PyObject *
  892. make_new_set(PyTypeObject *type, PyObject *iterable)
  893. {
  894. register PySetObject *so = NULL;
  895. if (dummy == NULL) { /* Auto-initialize dummy */
  896. dummy = PyString_FromString("<dummy key>");
  897. if (dummy == NULL)
  898. return NULL;
  899. }
  900. /* create PySetObject structure */
  901. if (numfree &&
  902. (type == &PySet_Type || type == &PyFrozenSet_Type)) {
  903. so = free_list[--numfree];
  904. assert (so != NULL && PyAnySet_CheckExact(so));
  905. Py_TYPE(so) = type;
  906. _Py_NewReference((PyObject *)so);
  907. EMPTY_TO_MINSIZE(so);
  908. PyObject_GC_Track(so);
  909. } else {
  910. so = (PySetObject *)type->tp_alloc(type, 0);
  911. if (so == NULL)
  912. return NULL;
  913. /* tp_alloc has already zeroed the structure */
  914. assert(so->table == NULL && so->fill == 0 && so->used == 0);
  915. INIT_NONZERO_SET_SLOTS(so);
  916. }
  917. so->lookup = set_lookkey_string;
  918. so->weakreflist = NULL;
  919. if (iterable != NULL) {
  920. if (set_update_internal(so, iterable) == -1) {
  921. Py_DECREF(so);
  922. return NULL;
  923. }
  924. }
  925. return (PyObject *)so;
  926. }
  927. /* The empty frozenset is a singleton */
  928. static PyObject *emptyfrozenset = NULL;
  929. static PyObject *
  930. frozenset_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  931. {
  932. PyObject *iterable = NULL, *result;
  933. if (type == &PyFrozenSet_Type && !_PyArg_NoKeywords("frozenset()", kwds))
  934. return NULL;
  935. if (!PyArg_UnpackTuple(args, type->tp_name, 0, 1, &iterable))
  936. return NULL;
  937. if (type != &PyFrozenSet_Type)
  938. return make_new_set(type, iterable);
  939. if (iterable != NULL) {
  940. /* frozenset(f) is idempotent */
  941. if (PyFrozenSet_CheckExact(iterable)) {
  942. Py_INCREF(iterable);
  943. return iterable;
  944. }
  945. result = make_new_set(type, iterable);
  946. if (result == NULL || PySet_GET_SIZE(result))
  947. return result;
  948. Py_DECREF(result);
  949. }
  950. /* The empty frozenset is a singleton */
  951. if (emptyfrozenset == NULL)
  952. emptyfrozenset = make_new_set(type, NULL);
  953. Py_XINCREF(emptyfrozenset);
  954. return emptyfrozenset;
  955. }
  956. void
  957. PySet_Fini(void)
  958. {
  959. PySetObject *so;
  960. while (numfree) {
  961. numfree--;
  962. so = free_list[numfree];
  963. PyObject_GC_Del(so);
  964. }
  965. Py_CLEAR(dummy);
  966. Py_CLEAR(emptyfrozenset);
  967. }
  968. static PyObject *
  969. set_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  970. {
  971. if (type == &PySet_Type && !_PyArg_NoKeywords("set()", kwds))
  972. return NULL;
  973. return make_new_set(type, NULL);
  974. }
  975. /* set_swap_bodies() switches the contents of any two sets by moving their
  976. internal data pointers and, if needed, copying the internal smalltables.
  977. Semantically equivalent to:
  978. t=set(a); a.clear(); a.update(b); b.clear(); b.update(t); del t
  979. The function always succeeds and it leaves both objects in a stable state.
  980. Useful for creating temporary frozensets from sets for membership testing
  981. in __contains__(), discard(), and remove(). Also useful for operations
  982. that update in-place (by allowing an intermediate result to be swapped
  983. into one of the original inputs).
  984. */
  985. static void
  986. set_swap_bodies(PySetObject *a, PySetObject *b)
  987. {
  988. Py_ssize_t t;
  989. setentry *u;
  990. setentry *(*f)(PySetObject *so, PyObject *key, long hash);
  991. setentry tab[PySet_MINSIZE];
  992. long h;
  993. t = a->fill; a->fill = b->fill; b->fill = t;
  994. t = a->used; a->used = b->used; b->used = t;
  995. t = a->mask; a->mask = b->mask; b->mask = t;
  996. u = a->table;
  997. if (a->table == a->smalltable)
  998. u = b->smalltable;
  999. a->table = b->table;
  1000. if (b->table == b->smalltable)
  1001. a->table = a->smalltable;
  1002. b->table = u;
  1003. f = a->lookup; a->lookup = b->lookup; b->lookup = f;
  1004. if (a->table == a->smalltable || b->table == b->smalltable) {
  1005. memcpy(tab, a->smalltable, sizeof(tab));
  1006. memcpy(a->smalltable, b->smalltable, sizeof(tab));
  1007. memcpy(b->smalltable, tab, sizeof(tab));
  1008. }
  1009. if (PyType_IsSubtype(Py_TYPE(a), &PyFrozenSet_Type) &&
  1010. PyType_IsSubtype(Py_TYPE(b), &PyFrozenSet_Type)) {
  1011. h = a->hash; a->hash = b->hash; b->hash = h;
  1012. } else {
  1013. a->hash = -1;
  1014. b->hash = -1;
  1015. }
  1016. }
  1017. static PyObject *
  1018. set_copy(PySetObject *so)
  1019. {
  1020. return make_new_set(Py_TYPE(so), (PyObject *)so);
  1021. }
  1022. static PyObject *
  1023. frozenset_copy(PySetObject *so)
  1024. {
  1025. if (PyFrozenSet_CheckExact(so)) {
  1026. Py_INCREF(so);
  1027. return (PyObject *)so;
  1028. }
  1029. return set_copy(so);
  1030. }
  1031. PyDoc_STRVAR(copy_doc, "Return a shallow copy of a set.");
  1032. static PyObject *
  1033. set_clear(PySetObject *so)
  1034. {
  1035. set_clear_internal(so);
  1036. Py_RETURN_NONE;
  1037. }
  1038. PyDoc_STRVAR(clear_doc, "Remove all elements from this set.");
  1039. static PyObject *
  1040. set_union(PySetObject *so, PyObject *args)
  1041. {
  1042. PySetObject *result;
  1043. PyObject *other;
  1044. Py_ssize_t i;
  1045. result = (PySetObject *)set_copy(so);
  1046. if (result == NULL)
  1047. return NULL;
  1048. for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
  1049. other = PyTuple_GET_ITEM(args, i);
  1050. if ((PyObject *)so == other)
  1051. continue;
  1052. if (set_update_internal(result, other) == -1) {
  1053. Py_DECREF(result);
  1054. return NULL;
  1055. }
  1056. }
  1057. return (PyObject *)result;
  1058. }
  1059. PyDoc_STRVAR(union_doc,
  1060. "Return the union of sets as a new set.\n\
  1061. \n\
  1062. (i.e. all elements that are in either set.)");
  1063. static PyObject *
  1064. set_or(PySetObject *so, PyObject *other)
  1065. {
  1066. PySetObject *result;
  1067. if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
  1068. Py_INCREF(Py_NotImplemented);
  1069. return Py_NotImplemented;
  1070. }
  1071. result = (PySetObject *)set_copy(so);
  1072. if (result == NULL)
  1073. return NULL;
  1074. if ((PyObject *)so == other)
  1075. return (PyObject *)result;
  1076. if (set_update_internal(result, other) == -1) {
  1077. Py_DECREF(result);
  1078. return NULL;
  1079. }
  1080. return (PyObject *)result;
  1081. }
  1082. static PyObject *
  1083. set_ior(PySetObject *so, PyObject *other)
  1084. {
  1085. if (!PyAnySet_Check(other)) {
  1086. Py_INCREF(Py_NotImplemented);
  1087. return Py_NotImplemented;
  1088. }
  1089. if (set_update_internal(so, other) == -1)
  1090. return NULL;
  1091. Py_INCREF(so);
  1092. return (PyObject *)so;
  1093. }
  1094. static PyObject *
  1095. set_intersection(PySetObject *so, PyObject *other)
  1096. {
  1097. PySetObject *result;
  1098. PyObject *key, *it, *tmp;
  1099. if ((PyObject *)so == other)
  1100. return set_copy(so);
  1101. result = (PySetObject *)make_new_set(Py_TYPE(so), NULL);
  1102. if (result == NULL)
  1103. return NULL;
  1104. if (PyAnySet_Check(other)) {
  1105. Py_ssize_t pos = 0;
  1106. setentry *entry;
  1107. if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) {
  1108. tmp = (PyObject *)so;
  1109. so = (PySetObject *)other;
  1110. other = tmp;
  1111. }
  1112. while (set_next((PySetObject *)other, &pos, &entry)) {
  1113. int rv = set_contains_entry(so, entry);
  1114. if (rv == -1) {
  1115. Py_DECREF(result);
  1116. return NULL;
  1117. }
  1118. if (rv) {
  1119. if (set_add_entry(result, entry) == -1) {
  1120. Py_DECREF(result);
  1121. return NULL;
  1122. }
  1123. }
  1124. }
  1125. return (PyObject *)result;
  1126. }
  1127. it = PyObject_GetIter(other);
  1128. if (it == NULL) {
  1129. Py_DECREF(result);
  1130. return NULL;
  1131. }
  1132. while ((key = PyIter_Next(it)) != NULL) {
  1133. int rv;
  1134. setentry entry;
  1135. long hash = PyObject_Hash(key);
  1136. if (hash == -1) {
  1137. Py_DECREF(it);
  1138. Py_DECREF(result);
  1139. Py_DECREF(key);
  1140. return NULL;
  1141. }
  1142. entry.hash = hash;
  1143. entry.key = key;
  1144. rv = set_contains_entry(so, &entry);
  1145. if (rv == -1) {
  1146. Py_DECREF(it);
  1147. Py_DECREF(result);
  1148. Py_DECREF(key);
  1149. return NULL;
  1150. }
  1151. if (rv) {
  1152. if (set_add_entry(result, &entry) == -1) {
  1153. Py_DECREF(it);
  1154. Py_DECREF(result);
  1155. Py_DECREF(key);
  1156. return NULL;
  1157. }
  1158. }
  1159. Py_DECREF(key);
  1160. }
  1161. Py_DECREF(it);
  1162. if (PyErr_Occurred()) {
  1163. Py_DECREF(result);
  1164. return NULL;
  1165. }
  1166. return (PyObject *)result;
  1167. }
  1168. static PyObject *
  1169. set_intersection_multi(PySetObject *so, PyObject *args)
  1170. {
  1171. Py_ssize_t i;
  1172. PyObject *result = (PyObject *)so;
  1173. if (PyTuple_GET_SIZE(args) == 0)
  1174. return set_copy(so);
  1175. Py_INCREF(so);
  1176. for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
  1177. PyObject *other = PyTuple_GET_ITEM(args, i);
  1178. PyObject *newresult = set_intersection((PySetObject *)result, other);
  1179. if (newresult == NULL) {
  1180. Py_DECREF(result);
  1181. return NULL;
  1182. }
  1183. Py_DECREF(result);
  1184. result = newresult;
  1185. }
  1186. return result;
  1187. }
  1188. PyDoc_STRVAR(intersection_doc,
  1189. "Return the intersection of two sets as a new set.\n\
  1190. \n\
  1191. (i.e. all elements that are in both sets.)");
  1192. static PyObject *
  1193. set_intersection_update(PySetObject *so, PyObject *other)
  1194. {
  1195. PyObject *tmp;
  1196. tmp = set_intersection(so, other);
  1197. if (tmp == NULL)
  1198. return NULL;
  1199. set_swap_bodies(so, (PySetObject *)tmp);
  1200. Py_DECREF(tmp);
  1201. Py_RETURN_NONE;
  1202. }
  1203. static PyObject *
  1204. set_intersection_update_multi(PySetObject *so, PyObject *args)
  1205. {
  1206. PyObject *tmp;
  1207. tmp = set_intersection_multi(so, args);
  1208. if (tmp == NULL)
  1209. return NULL;
  1210. set_swap_bodies(so, (PySetObject *)tmp);
  1211. Py_DECREF(tmp);
  1212. Py_RETURN_NONE;
  1213. }
  1214. PyDoc_STRVAR(intersection_update_doc,
  1215. "Update a set with the intersection of itself and another.");
  1216. static PyObject *
  1217. set_and(PySetObject *so, PyObject *other)
  1218. {
  1219. if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
  1220. Py_INCREF(Py_NotImplemented);
  1221. return Py_NotImplemented;
  1222. }
  1223. return set_intersection(so, other);
  1224. }
  1225. static PyObject *
  1226. set_iand(PySetObject *so, PyObject *other)
  1227. {
  1228. PyObject *result;
  1229. if (!PyAnySet_Check(other)) {
  1230. Py_INCREF(Py_NotImplemented);
  1231. return Py_NotImplemented;
  1232. }
  1233. result = set_intersection_update(so, other);
  1234. if (result == NULL)
  1235. return NULL;
  1236. Py_DECREF(result);
  1237. Py_INCREF(so);
  1238. return (PyObject *)so;
  1239. }
  1240. static PyObject *
  1241. set_isdisjoint(PySetObject *so, PyObject *other)
  1242. {
  1243. PyObject *key, *it, *tmp;
  1244. if ((PyObject *)so == other) {
  1245. if (PySet_GET_SIZE(so) == 0)
  1246. Py_RETURN_TRUE;
  1247. else
  1248. Py_RETURN_FALSE;
  1249. }
  1250. if (PyAnySet_CheckExact(other)) {
  1251. Py_ssize_t pos = 0;
  1252. setentry *entry;
  1253. if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) {
  1254. tmp = (PyObject *)so;
  1255. so = (PySetObject *)other;
  1256. other = tmp;
  1257. }
  1258. while (set_next((PySetObject *)other, &pos, &entry)) {
  1259. int rv = set_contains_entry(so, entry);
  1260. if (rv == -1)
  1261. return NULL;
  1262. if (rv)
  1263. Py_RETURN_FALSE;
  1264. }
  1265. Py_RETURN_TRUE;
  1266. }
  1267. it = PyObject_GetIter(other);
  1268. if (it == NULL)
  1269. return NULL;
  1270. while ((key = PyIter_Next(it)) != NULL) {
  1271. int rv;
  1272. setentry entry;
  1273. long hash = PyObject_Hash(key);
  1274. if (hash == -1) {
  1275. Py_DECREF(key);
  1276. Py_DECREF(it);
  1277. return NULL;
  1278. }
  1279. entry.hash = hash;
  1280. entry.key = key;
  1281. rv = set_contains_entry(so, &entry);
  1282. Py_DECREF(key);
  1283. if (rv == -1) {
  1284. Py_DECREF(it);
  1285. return NULL;
  1286. }
  1287. if (rv) {
  1288. Py_DECREF(it);
  1289. Py_RETURN_FALSE;
  1290. }
  1291. }
  1292. Py_DECREF(it);
  1293. if (PyErr_Occurred())
  1294. return NULL;
  1295. Py_RETURN_TRUE;
  1296. }
  1297. PyDoc_STRVAR(isdisjoint_doc,
  1298. "Return True if two sets have a null intersection.");
  1299. static int
  1300. set_difference_update_internal(PySetObject *so, PyObject *other)
  1301. {
  1302. if ((PyObject *)so == other)
  1303. return set_clear_internal(so);
  1304. if (PyAnySet_Check(other)) {
  1305. setentry *entry;
  1306. Py_ssize_t pos = 0;
  1307. while (set_next((PySetObject *)other, &pos, &entry))
  1308. if (set_discard_entry(so, entry) == -1)
  1309. return -1;
  1310. } else {
  1311. PyObject *key, *it;
  1312. it = PyObject_GetIter(other);
  1313. if (it == NULL)
  1314. return -1;
  1315. while ((key = PyIter_Next(it)) != NULL) {
  1316. if (set_discard_key(so, key) == -1) {
  1317. Py_DECREF(it);
  1318. Py_DECREF(key);
  1319. return -1;
  1320. }
  1321. Py_DECREF(key);
  1322. }
  1323. Py_DECREF(it);
  1324. if (PyErr_Occurred())
  1325. return -1;
  1326. }
  1327. /* If more than 1/5 are dummies, then resize them away. */
  1328. if ((so->fill - so->used) * 5 < so->mask)
  1329. return 0;
  1330. return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
  1331. }
  1332. static PyObject *
  1333. set_difference_update(PySetObject *so, PyObject *args)
  1334. {
  1335. Py_ssize_t i;
  1336. for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
  1337. PyObject *other = PyTuple_GET_ITEM(args, i);
  1338. if (set_difference_update_internal(so, other) == -1)
  1339. return NULL;
  1340. }
  1341. Py_RETURN_NONE;
  1342. }
  1343. PyDoc_STRVAR(difference_update_doc,
  1344. "Remove all elements of another set from this set.");
  1345. static PyObject *
  1346. set_difference(PySetObject *so, PyObject *other)
  1347. {
  1348. PyObject *result;
  1349. setentry *entry;
  1350. Py_ssize_t pos = 0;
  1351. if (!PyAnySet_Check(other) && !PyDict_CheckExact(other)) {
  1352. result = set_copy(so);
  1353. if (result == NULL)
  1354. return NULL;
  1355. if (set_difference_update_internal((PySetObject *)result, other) != -1)
  1356. return result;
  1357. Py_DECREF(result);
  1358. return NULL;
  1359. }
  1360. result = make_new_set(Py_TYPE(so), NULL);
  1361. if (result == NULL)
  1362. return NULL;
  1363. if (PyDict_CheckExact(other)) {
  1364. while (set_next(so, &pos, &entry)) {
  1365. setentry entrycopy;
  1366. entrycopy.hash = entry->hash;
  1367. entrycopy.key = entry->key;
  1368. if (!_PyDict_Contains(other, entry->key, entry->hash)) {
  1369. if (set_add_entry((PySetObject *)result, &entrycopy) == -1) {
  1370. Py_DECREF(result);
  1371. return NULL;
  1372. }
  1373. }
  1374. }
  1375. return result;
  1376. }
  1377. while (set_next(so, &pos, &entry)) {
  1378. int rv = set_contains_entry((PySetObject *)other, entry);
  1379. if (rv == -1) {
  1380. Py_DECREF(result);
  1381. return NULL;
  1382. }
  1383. if (!rv) {
  1384. if (set_add_entry((PySetObject *)result, entry) == -1) {
  1385. Py_DECREF(result);
  1386. return NULL;
  1387. }
  1388. }
  1389. }
  1390. return result;
  1391. }
  1392. static PyObject *
  1393. set_difference_multi(PySetObject *so, PyObject *args)
  1394. {
  1395. Py_ssize_t i;
  1396. PyObject *result, *other;
  1397. if (PyTuple_GET_SIZE(args) == 0)
  1398. return set_copy(so);
  1399. other = PyTuple_GET_ITEM(args, 0);
  1400. result = set_difference(so, other);
  1401. if (result == NULL)
  1402. return NULL;
  1403. for (i=1 ; i<PyTuple_GET_SIZE(args) ; i++) {
  1404. other = PyTuple_GET_ITEM(args, i);
  1405. if (set_difference_update_internal((PySetObject *)result, other) == -1) {
  1406. Py_DECREF(result);
  1407. return NULL;
  1408. }
  1409. }
  1410. return result;
  1411. }
  1412. PyDoc_STRVAR(difference_doc,
  1413. "Return the difference of two or more sets as a new set.\n\
  1414. \n\
  1415. (i.e. all elements that are in this set but not the others.)");
  1416. static PyObject *
  1417. set_sub(PySetObject *so, PyObject *other)
  1418. {
  1419. if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
  1420. Py_INCREF(Py_NotImplemented);
  1421. return Py_NotImplemented;
  1422. }
  1423. return set_difference(so, other);
  1424. }
  1425. static PyObject *
  1426. set_isub(PySetObject *so, PyObject *other)
  1427. {
  1428. if (!PyAnySet_Check(other)) {
  1429. Py_INCREF(Py_NotImplemented);
  1430. return Py_NotImplemented;
  1431. }
  1432. if (set_difference_update_internal(so, other) == -1)
  1433. return NULL;
  1434. Py_INCREF(so);
  1435. return (PyObject *)so;
  1436. }
  1437. static PyObject *
  1438. set_symmetric_difference_update(PySetObject *so, PyObject *other)
  1439. {
  1440. PySetObject *otherset;
  1441. PyObject *key;
  1442. Py_ssize_t pos = 0;
  1443. setentry *entry;
  1444. if ((PyObject *)so == other)
  1445. return set_clear(so);
  1446. if (PyDict_CheckExact(other)) {
  1447. PyObject *value;
  1448. int rv;
  1449. long hash;
  1450. while (_PyDict_Next(other, &pos, &key, &value, &hash)) {
  1451. setentry an_entry;
  1452. an_entry.hash = hash;
  1453. an_entry.key = key;
  1454. rv = set_discard_entry(so, &an_entry);
  1455. if (rv == -1)
  1456. return NULL;
  1457. if (rv == DISCARD_NOTFOUND) {
  1458. if (set_add_entry(so, &an_entry) == -1)
  1459. return NULL;
  1460. }
  1461. }
  1462. Py_RETURN_NONE;
  1463. }
  1464. if (PyAnySet_Check(other)) {
  1465. Py_INCREF(other);
  1466. otherset = (PySetObject *)other;
  1467. } else {
  1468. otherset = (PySetObject *)make_new_set(Py_TYPE(so), other);
  1469. if (otherset == NULL)
  1470. return NULL;
  1471. }
  1472. while (set_next(otherset, &pos, &entry)) {
  1473. int rv = set_discard_entry(so, entry);
  1474. if (rv == -1) {
  1475. Py_DECREF(otherset);
  1476. return NULL;
  1477. }
  1478. if (rv == DISCARD_NOTFOUND) {
  1479. if (set_add_entry(so, entry) == -1) {
  1480. Py_DECREF(otherset);
  1481. return NULL;
  1482. }
  1483. }
  1484. }
  1485. Py_DECREF(otherset);
  1486. Py_RETURN_NONE;
  1487. }
  1488. PyDoc_STRVAR(symmetric_difference_update_doc,
  1489. "Update a set with the symmetric difference of itself and another.");
  1490. static PyObject *
  1491. set_symmetric_difference(PySetObject *so, PyObject *other)
  1492. {
  1493. PyObject *rv;
  1494. PySetObject *otherset;
  1495. otherset = (PySetObject *)make_new_set(Py_TYPE(so), other);
  1496. if (otherset == NULL)
  1497. return NULL;
  1498. rv = set_symmetric_difference_update(otherset, (PyObject *)so);
  1499. if (rv == NULL)
  1500. return NULL;
  1501. Py_DECREF(rv);
  1502. return (PyObject *)otherset;
  1503. }
  1504. PyDoc_STRVAR(symmetric_difference_doc,
  1505. "Return the symmetric difference of two sets as a new set.\n\
  1506. \n\
  1507. (i.e. all elements that are in exactly one of the sets.)");
  1508. static PyObject *
  1509. set_xor(PySetObject *so, PyObject *other)
  1510. {
  1511. if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
  1512. Py_INCREF(Py_NotImplemented);
  1513. return Py_NotImplemented;
  1514. }
  1515. return set_symmetric_difference(so, other);
  1516. }
  1517. static PyObject *
  1518. set_ixor(PySetObject *so, PyObject *other)
  1519. {
  1520. PyObject *result;
  1521. if (!PyAnySet_Check(other)) {
  1522. Py_INCREF(Py_NotImplemented);
  1523. return Py_NotImplemented;
  1524. }
  1525. result = set_symmetric_difference_update(so, other);
  1526. if (result == NULL)
  1527. return NULL;
  1528. Py_DECREF(result);
  1529. Py_INCREF(so);
  1530. return (PyObject *)so;
  1531. }
  1532. static PyObject *
  1533. set_issubset(PySetObject *so, PyObject *other)
  1534. {
  1535. setentry *entry;
  1536. Py_ssize_t pos = 0;
  1537. if (!PyAnySet_Check(other)) {
  1538. PyObject *tmp, *result;
  1539. tmp = make_new_set(&PySet_Type, other);
  1540. if (tmp == NULL)
  1541. return NULL;
  1542. result = set_issubset(so, tmp);
  1543. Py_DECREF(tmp);
  1544. return result;
  1545. }
  1546. if (PySet_GET_SIZE(so) > PySet_GET_SIZE(other))
  1547. Py_RETURN_FALSE;
  1548. while (set_next(so, &pos, &entry)) {
  1549. int rv = set_contains_entry((PySetObject *)other, entry);
  1550. if (rv == -1)
  1551. return NULL;
  1552. if (!rv)
  1553. Py_RETURN_FALSE;
  1554. }
  1555. Py_RETURN_TRUE;
  1556. }
  1557. PyDoc_STRVAR(issubset_doc, "Report whether another set contains this set.");
  1558. static PyObject *
  1559. set_issuperset(PySetObject *so, PyObject *other)
  1560. {
  1561. PyObject *tmp, *result;
  1562. if (!PyAnySet_Check(other)) {
  1563. tmp = make_new_set(&PySet_Type, other);
  1564. if (tmp == NULL)
  1565. return NULL;
  1566. result = set_issuperset(so, tmp);
  1567. Py_DECREF(tmp);
  1568. return result;
  1569. }
  1570. return set_issubset((PySetObject *)other, (PyObject *)so);
  1571. }
  1572. PyDoc_STRVAR(issuperset_doc, "Report whether this set contains another set.");
  1573. static PyObject *
  1574. set_richcompare(PySetObject *v, PyObject *w, int op)
  1575. {
  1576. PyObject *r1, *r2;
  1577. if(!PyAnySet_Check(w)) {
  1578. if (op == Py_EQ)
  1579. Py_RETURN_FALSE;
  1580. if (op == Py_NE)
  1581. Py_RETURN_TRUE;
  1582. PyErr_SetString(PyExc_TypeError, "can only compare to a set");
  1583. return NULL;
  1584. }
  1585. switch (op) {
  1586. case Py_EQ:
  1587. if (PySet_GET_SIZE(v) != PySet_GET_SIZE(w))
  1588. Py_RETURN_FALSE;
  1589. if (v->hash != -1 &&
  1590. ((PySetObject *)w)->hash != -1 &&
  1591. v->hash != ((PySetObject *)w)->hash)
  1592. Py_RETURN_FALSE;
  1593. return set_issubset(v, w);
  1594. case Py_NE:
  1595. r1 = set_richcompare(v, w, Py_EQ);
  1596. if (r1 == NULL)
  1597. return NULL;
  1598. r2 = PyBool_FromLong(PyObject_Not(r1));
  1599. Py_DECREF(r1);
  1600. return r2;
  1601. case Py_LE:
  1602. return set_issubset(v, w);
  1603. case Py_GE:
  1604. return set_issuperset(v, w);
  1605. case Py_LT:
  1606. if (PySet_GET_SIZE(v) >= PySet_GET_SIZE(w))
  1607. Py_RETURN_FALSE;
  1608. return set_issubset(v, w);
  1609. case Py_GT:
  1610. if (PySet_GET_SIZE(v) <= PySet_GET_SIZE(w))
  1611. Py_RETURN_FALSE;
  1612. return set_issuperset(v, w);
  1613. }
  1614. Py_INCREF(Py_NotImplemented);
  1615. return Py_NotImplemented;
  1616. }
  1617. static int
  1618. set_nocmp(PyObject *self, PyObject *other)
  1619. {
  1620. PyErr_SetString(PyExc_TypeError, "cannot compare sets using cmp()");
  1621. return -1;
  1622. }
  1623. static PyObject *
  1624. set_add(PySetObject *so, PyObject *key)
  1625. {
  1626. if (set_add_key(so, key) == -1)
  1627. return NULL;
  1628. Py_RETURN_NONE;
  1629. }
  1630. PyDoc_STRVAR(add_doc,
  1631. "Add an element to a set.\n\
  1632. \n\
  1633. This has no effect if the element is already present.");
  1634. static int
  1635. set_contains(PySetObject *so, PyObject *key)
  1636. {
  1637. PyObject *tmpkey;
  1638. int rv;
  1639. rv = set_contains_key(so, key);
  1640. if (rv == -1) {
  1641. if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
  1642. return -1;
  1643. PyErr_Clear();
  1644. tmpkey = make_new_set(&PyFrozenSet_Type, NULL);
  1645. if (tmpkey == NULL)
  1646. return -1;
  1647. set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
  1648. rv = set_contains(so, tmpkey);
  1649. set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
  1650. Py_DECREF(tmpkey);
  1651. }
  1652. return rv;
  1653. }
  1654. static PyObject *
  1655. set_direct_contains(PySetObject *so, PyObject *key)
  1656. {
  1657. long result;
  1658. result = set_contains(so, key);
  1659. if (result == -1)
  1660. return NULL;
  1661. return PyBool_FromLong(result);
  1662. }
  1663. PyDoc_STRVAR(contains_doc, "x.__contains__(y) <==> y in x.");
  1664. static PyObject *
  1665. set_remove(PySetObject *so, PyObject *key)
  1666. {
  1667. PyObject *tmpkey;
  1668. int rv;
  1669. rv = set_discard_key(so, key);
  1670. if (rv == -1) {
  1671. if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
  1672. return NULL;
  1673. PyErr_Clear();
  1674. tmpkey = make_new_set(&PyFrozenSet_Type, NULL);
  1675. if (tmpkey == NULL)
  1676. return NULL;
  1677. set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
  1678. rv = set_discard_key(so, tmpkey);
  1679. set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
  1680. Py_DECREF(tmpkey);
  1681. if (rv == -1)
  1682. return NULL;
  1683. }
  1684. if (rv == DISCARD_NOTFOUND) {
  1685. set_key_error(key);
  1686. return NULL;
  1687. }
  1688. Py_RETURN_NONE;
  1689. }
  1690. PyDoc_STRVAR(remove_doc,
  1691. "Remove an element from a set; it must be a member.\n\
  1692. \n\
  1693. If the element is not a member, raise a KeyError.");
  1694. static PyObject *
  1695. set_discard(PySetObject *so, PyObject *key)
  1696. {
  1697. PyObject *tmpkey, *result;
  1698. int rv;
  1699. rv = set_discard_key(so, key);
  1700. if (rv == -1) {
  1701. if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
  1702. return NULL;
  1703. PyErr_Clear();
  1704. tmpkey = make_new_set(&PyFrozenSet_Type, NULL);
  1705. if (tmpkey == NULL)
  1706. return NULL;
  1707. set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
  1708. result = set_discard(so, tmpkey);
  1709. set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
  1710. Py_DECREF(tmpkey);
  1711. return result;
  1712. }
  1713. Py_RETURN_NONE;
  1714. }
  1715. PyDoc_STRVAR(discard_doc,
  1716. "Remove an element from a set if it is a member.\n\
  1717. \n\
  1718. If the element is not a member, do nothing.");
  1719. static PyObject *
  1720. set_reduce(PySetObject *so)
  1721. {
  1722. PyObject *keys=NULL, *args=NULL, *result=NULL, *dict=NULL;
  1723. keys = PySequence_List((PyObject *)so);
  1724. if (keys == NULL)
  1725. goto done;
  1726. args = PyTuple_Pack(1, keys);
  1727. if (args == NULL)
  1728. goto done;
  1729. dict = PyObject_GetAttrString((PyObject *)so, "__dict__");
  1730. if (dict == NULL) {
  1731. PyErr_Clear();
  1732. dict = Py_None;
  1733. Py_INCREF(dict);
  1734. }
  1735. result = PyTuple_Pack(3, Py_TYPE(so), args, dict);
  1736. done:
  1737. Py_XDECREF(args);
  1738. Py_XDECREF(keys);
  1739. Py_XDECREF(dict);
  1740. return result;
  1741. }
  1742. PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
  1743. static PyObject *
  1744. set_sizeof(PySetObject *so)
  1745. {
  1746. Py_ssize_t res;
  1747. res = sizeof(PySetObject);
  1748. if (so->table != so->smalltable)
  1749. res = res + (so->mask + 1) * sizeof(setentry);
  1750. return PyInt_FromSsize_t(res);
  1751. }
  1752. PyDoc_STRVAR(sizeof_doc, "S.__sizeof__() -> size of S in memory, in bytes");
  1753. static int
  1754. set_init(PySetObject *self, PyObject *args, PyObject *kwds)
  1755. {
  1756. PyObject *iterable = NULL;
  1757. if (!PyAnySet_Check(self))
  1758. return -1;
  1759. if (!PyArg_UnpackTuple(args, Py_TYPE(self)->tp_name, 0, 1, &iterable))
  1760. return -1;
  1761. set_clear_internal(self);
  1762. self->hash = -1;
  1763. if (iterable == NULL)
  1764. return 0;
  1765. return set_update_internal(self, iterable);
  1766. }
  1767. static PySequenceMethods set_as_sequence = {
  1768. set_len, /* sq_length */
  1769. 0, /* sq_concat */
  1770. 0, /* sq_repeat */
  1771. 0, /* sq_item */
  1772. 0, /* sq_slice */
  1773. 0, /* sq_ass_item */
  1774. 0, /* sq_ass_slice */
  1775. (objobjproc)set_contains, /* sq_contains */
  1776. };
  1777. /* set object ********************************************************/
  1778. #ifdef Py_DEBUG
  1779. static PyObject *test_c_api(PySetObject *so);
  1780. PyDoc_STRVAR(test_c_api_doc, "Exercises C API. Returns True.\n\
  1781. All is well if assertions don't fail.");
  1782. #endif
  1783. static PyMethodDef set_methods[] = {
  1784. {"add", (PyCFunction)set_add, METH_O,
  1785. add_doc},
  1786. {"clear", (PyCFunction)set_clear, METH_NOARGS,
  1787. clear_doc},
  1788. {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST,
  1789. contains_doc},
  1790. {"copy", (PyCFunction)set_copy, METH_NOARGS,
  1791. copy_doc},
  1792. {"discard", (PyCFunction)set_discard, METH_O,
  1793. discard_doc},
  1794. {"difference", (PyCFunction)set_difference_multi, METH_VARARGS,
  1795. difference_doc},
  1796. {"difference_update", (PyCFunction)set_difference_update, METH_VARARGS,
  1797. difference_update_doc},
  1798. {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS,
  1799. intersection_doc},
  1800. {"intersection_update",(PyCFunction)set_intersection_update_multi, METH_VARARGS,
  1801. intersection_update_doc},
  1802. {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O,
  1803. isdisjoint_doc},
  1804. {"issubset", (PyCFunction)set_issubset, METH_O,
  1805. issubset_doc},
  1806. {"issuperset", (PyCFunction)set_issuperset, METH_O,
  1807. issuperset_doc},
  1808. {"pop", (PyCFunction)set_pop, METH_NOARGS,
  1809. pop_doc},
  1810. {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS,
  1811. reduce_doc},
  1812. {"remove", (PyCFunction)set_remove, METH_O,
  1813. remove_doc},
  1814. {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS,
  1815. sizeof_doc},
  1816. {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O,
  1817. symmetric_difference_doc},
  1818. {"symmetric_difference_update",(PyCFunction)set_symmetric_difference_update, METH_O,
  1819. symmetric_difference_update_doc},
  1820. #ifdef Py_DEBUG
  1821. {"test_c_api", (PyCFunction)test_c_api, METH_NOARGS,
  1822. test_c_api_doc},
  1823. #endif
  1824. {"union", (PyCFunction)set_union, METH_VARARGS,
  1825. union_doc},
  1826. {"update", (PyCFunction)set_update, METH_VARARGS,
  1827. update_doc},
  1828. {NULL, NULL} /* sentinel */
  1829. };
  1830. static PyNumberMethods set_as_number = {
  1831. 0, /*nb_add*/
  1832. (binaryfunc)set_sub, /*nb_subtract*/
  1833. 0, /*nb_multiply*/
  1834. 0, /*nb_divide*/
  1835. 0, /*nb_remainder*/
  1836. 0, /*nb_divmod*/
  1837. 0, /*nb_power*/
  1838. 0, /*nb_negative*/
  1839. 0, /*nb_positive*/
  1840. 0, /*nb_absolute*/
  1841. 0, /*nb_nonzero*/
  1842. 0, /*nb_invert*/
  1843. 0, /*nb_lshift*/
  1844. 0, /*nb_rshift*/
  1845. (binaryfunc)set_and, /*nb_and*/
  1846. (binaryfunc)set_xor, /*nb_xor*/
  1847. (binaryfunc)set_or, /*nb_or*/
  1848. 0, /*nb_coerce*/
  1849. 0, /*nb_int*/
  1850. 0, /*nb_long*/
  1851. 0, /*nb_float*/
  1852. 0, /*nb_oct*/
  1853. 0, /*nb_hex*/
  1854. 0, /*nb_inplace_add*/
  1855. (binaryfunc)set_isub, /*nb_inplace_subtract*/
  1856. 0, /*nb_inplace_multiply*/
  1857. 0, /*nb_inplace_divide*/
  1858. 0, /*nb_inplace_remainder*/
  1859. 0, /*nb_inplace_power*/
  1860. 0, /*nb_inplace_lshift*/
  1861. 0, /*nb_inplace_rshift*/
  1862. (binaryfunc)set_iand, /*nb_inplace_and*/
  1863. (binaryfunc)set_ixor, /*nb_inplace_xor*/
  1864. (binaryfunc)set_ior, /*nb_inplace_or*/
  1865. };
  1866. PyDoc_STRVAR(set_doc,
  1867. "set(iterable) --> set object\n\
  1868. \n\
  1869. Build an unordered collection of unique elements.");
  1870. PyTypeObject PySet_Type = {
  1871. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1872. "set", /* tp_name */
  1873. sizeof(PySetObject), /* tp_basicsize */
  1874. 0, /* tp_itemsize */
  1875. /* methods */
  1876. (destructor)set_dealloc, /* tp_dealloc */
  1877. (printfunc)set_tp_print, /* tp_print */
  1878. 0, /* tp_getattr */
  1879. 0, /* tp_setattr */
  1880. set_nocmp, /* tp_compare */
  1881. (reprfunc)set_repr, /* tp_repr */
  1882. &set_as_number, /* tp_as_number */
  1883. &set_as_sequence, /* tp_as_sequence */
  1884. 0, /* tp_as_mapping */
  1885. (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
  1886. 0, /* tp_call */
  1887. 0, /* tp_str */
  1888. PyObject_GenericGetAttr, /* tp_getattro */
  1889. 0, /* tp_setattro */
  1890. 0, /* tp_as_buffer */
  1891. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES |
  1892. Py_TPFLAGS_BASETYPE, /* tp_flags */
  1893. set_doc, /* tp_doc */
  1894. (traverseproc)set_traverse, /* tp_traverse */
  1895. (inquiry)set_clear_internal, /* tp_clear */
  1896. (richcmpfunc)set_richcompare, /* tp_richcompare */
  1897. offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */
  1898. (getiterfunc)set_iter, /* tp_iter */
  1899. 0, /* tp_iternext */
  1900. set_methods, /* tp_methods */
  1901. 0, /* tp_members */
  1902. 0, /* tp_getset */
  1903. 0, /* tp_base */
  1904. 0, /* tp_dict */
  1905. 0, /* tp_descr_get */
  1906. 0, /* tp_descr_set */
  1907. 0, /* tp_dictoffset */
  1908. (initproc)set_init, /* tp_init */
  1909. PyType_GenericAlloc, /* tp_alloc */
  1910. set_new, /* tp_new */
  1911. PyObject_GC_Del, /* tp_free */
  1912. };
  1913. /* frozenset object ********************************************************/
  1914. static PyMethodDef frozenset_methods[] = {
  1915. {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST,
  1916. contains_doc},
  1917. {"copy", (PyCFunction)frozenset_copy, METH_NOARGS,
  1918. copy_doc},
  1919. {"difference", (PyCFunction)set_difference_multi, METH_VARARGS,
  1920. difference_doc},
  1921. {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS,
  1922. intersection_doc},
  1923. {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O,
  1924. isdisjoint_doc},
  1925. {"issubset", (PyCFunction)set_issubset, METH_O,
  1926. issubset_doc},
  1927. {"issuperset", (PyCFunction)set_issuperset, METH_O,
  1928. issuperset_doc},
  1929. {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS,
  1930. reduce_doc},
  1931. {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS,
  1932. sizeof_doc},
  1933. {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O,
  1934. symmetric_difference_doc},
  1935. {"union", (PyCFunction)set_union, METH_VARARGS,
  1936. union_doc},
  1937. {NULL, NULL} /* sentinel */
  1938. };
  1939. static PyNumberMethods frozenset_as_number = {
  1940. 0, /*nb_add*/
  1941. (binaryfunc)set_sub, /*nb_subtract*/
  1942. 0, /*nb_multiply*/
  1943. 0, /*nb_divide*/
  1944. 0, /*nb_remainder*/
  1945. 0, /*nb_divmod*/
  1946. 0, /*nb_power*/
  1947. 0, /*nb_negative*/
  1948. 0, /*nb_positive*/
  1949. 0, /*nb_absolute*/
  1950. 0, /*nb_nonzero*/
  1951. 0, /*nb_invert*/
  1952. 0, /*nb_lshift*/
  1953. 0, /*nb_rshift*/
  1954. (binaryfunc)set_and, /*nb_and*/
  1955. (binaryfunc)set_xor, /*nb_xor*/
  1956. (binaryfunc)set_or, /*nb_or*/
  1957. };
  1958. PyDoc_STRVAR(frozenset_doc,
  1959. "frozenset(iterable) --> frozenset object\n\
  1960. \n\
  1961. Build an immutable unordered collection of unique elements.");
  1962. PyTypeObject PyFrozenSet_Type = {
  1963. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1964. "frozenset", /* tp_name */
  1965. sizeof(PySetObject), /* tp_basicsize */
  1966. 0, /* tp_itemsize */
  1967. /* methods */
  1968. (destructor)set_dealloc, /* tp_dealloc */
  1969. (printfunc)set_tp_print, /* tp_print */
  1970. 0, /* tp_getattr */
  1971. 0, /* tp_setattr */
  1972. set_nocmp, /* tp_compare */
  1973. (reprfunc)set_repr, /* tp_repr */
  1974. &frozenset_as_number, /* tp_as_number */
  1975. &set_as_sequence, /* tp_as_sequence */
  1976. 0, /* tp_as_mapping */
  1977. frozenset_hash, /* tp_hash */
  1978. 0, /* tp_call */
  1979. 0, /* tp_str */
  1980. PyObject_GenericGetAttr, /* tp_getattro */
  1981. 0, /* tp_setattro */
  1982. 0, /* tp_as_buffer */
  1983. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES |
  1984. Py_TPFLAGS_BASETYPE, /* tp_flags */
  1985. frozenset_doc, /* tp_doc */
  1986. (traverseproc)set_traverse, /* tp_traverse */
  1987. (inquiry)set_clear_internal, /* tp_clear */
  1988. (richcmpfunc)set_richcompare, /* tp_richcompare */
  1989. offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */
  1990. (getiterfunc)set_iter, /* tp_iter */
  1991. 0, /* tp_iternext */
  1992. frozenset_methods, /* tp_methods */
  1993. 0, /* tp_members */
  1994. 0, /* tp_getset */
  1995. 0, /* tp_base */
  1996. 0, /* tp_dict */
  1997. 0, /* tp_descr_get */
  1998. 0, /* tp_descr_set */
  1999. 0, /* tp_dictoffset */
  2000. 0, /* tp_init */
  2001. PyType_GenericAlloc, /* tp_alloc */
  2002. frozenset_new, /* tp_new */
  2003. PyObject_GC_Del, /* tp_free */
  2004. };
  2005. /***** C API functions *************************************************/
  2006. PyObject *
  2007. PySet_New(PyObject *iterable)
  2008. {
  2009. return make_new_set(&PySet_Type, iterable);
  2010. }
  2011. PyObject *
  2012. PyFrozenSet_New(PyObject *iterable)
  2013. {
  2014. return make_new_set(&PyFrozenSet_Type, iterable);
  2015. }
  2016. Py_ssize_t
  2017. PySet_Size(PyObject *anyset)
  2018. {
  2019. if (!PyAnySet_Check(anyset)) {
  2020. PyErr_BadInternalCall();
  2021. return -1;
  2022. }
  2023. return PySet_GET_SIZE(anyset);
  2024. }
  2025. int
  2026. PySet_Clear(PyObject *set)
  2027. {
  2028. if (!PySet_Check(set)) {
  2029. PyErr_BadInternalCall();
  2030. return -1;
  2031. }
  2032. return set_clear_internal((PySetObject *)set);
  2033. }
  2034. int
  2035. PySet_Contains(PyObject *anyset, PyObject *key)
  2036. {
  2037. if (!PyAnySet_Check(anyset)) {
  2038. PyErr_BadInternalCall();
  2039. return -1;
  2040. }
  2041. return set_contains_key((PySetObject *)anyset, key);
  2042. }
  2043. int
  2044. PySet_Discard(PyObject *set, PyObject *key)
  2045. {
  2046. if (!PySet_Check(set)) {
  2047. PyErr_BadInternalCall();
  2048. return -1;
  2049. }
  2050. return set_discard_key((PySetObject *)set, key);
  2051. }
  2052. int
  2053. PySet_Add(PyObject *anyset, PyObject *key)
  2054. {
  2055. if (!PySet_Check(anyset) &&
  2056. (!PyFrozenSet_Check(anyset) || Py_REFCNT(anyset) != 1)) {
  2057. PyErr_BadInternalCall();
  2058. return -1;
  2059. }
  2060. return set_add_key((PySetObject *)anyset, key);
  2061. }
  2062. int
  2063. _PySet_Next(PyObject *set, Py_ssize_t *pos, PyObject **key)
  2064. {
  2065. setentry *entry_ptr;
  2066. if (!PyAnySet_Check(set)) {
  2067. PyErr_BadInternalCall();
  2068. return -1;
  2069. }
  2070. if (set_next((PySetObject *)set, pos, &entry_ptr) == 0)
  2071. return 0;
  2072. *key = entry_ptr->key;
  2073. return 1;
  2074. }
  2075. int
  2076. _PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, long *hash)
  2077. {
  2078. setentry *entry;
  2079. if (!PyAnySet_Check(set)) {
  2080. PyErr_BadInternalCall();
  2081. return -1;
  2082. }
  2083. if (set_next((PySetObject *)set, pos, &entry) == 0)
  2084. return 0;
  2085. *key = entry->key;
  2086. *hash = entry->hash;
  2087. return 1;
  2088. }
  2089. PyObject *
  2090. PySet_Pop(PyObject *set)
  2091. {
  2092. if (!PySet_Check(set)) {
  2093. PyErr_BadInternalCall();
  2094. return NULL;
  2095. }
  2096. return set_pop((PySetObject *)set);
  2097. }
  2098. int
  2099. _PySet_Update(PyObject *set, PyObject *iterable)
  2100. {
  2101. if (!PySet_Check(set)) {
  2102. PyErr_BadInternalCall();
  2103. return -1;
  2104. }
  2105. return set_update_internal((PySetObject *)set, iterable);
  2106. }
  2107. #ifdef Py_DEBUG
  2108. /* Test code to be called with any three element set.
  2109. Returns True and original set is restored. */
  2110. #define assertRaises(call_return_value, exception) \
  2111. do { \
  2112. assert(call_return_value); \
  2113. assert(PyErr_ExceptionMatches(exception)); \
  2114. PyErr_Clear(); \
  2115. } while(0)
  2116. static PyObject *
  2117. test_c_api(PySetObject *so)
  2118. {
  2119. Py_ssize_t count;
  2120. char *s;
  2121. Py_ssize_t i;
  2122. PyObject *elem=NULL, *dup=NULL, *t, *f, *dup2, *x;
  2123. PyObject *ob = (PyObject *)so;
  2124. /* Verify preconditions and exercise type/size checks */
  2125. assert(PyAnySet_Check(ob));
  2126. assert(PyAnySet_CheckExact(ob));
  2127. assert(!PyFrozenSet_CheckExact(ob));
  2128. assert(PySet_Size(ob) == 3);
  2129. assert(PySet_GET_SIZE(ob) == 3);
  2130. /* Raise TypeError for non-iterable constructor arguments */
  2131. assertRaises(PySet_New(Py_None) == NULL, PyExc_TypeError);
  2132. assertRaises(PyFrozenSet_New(Py_None) == NULL, PyExc_TypeError);
  2133. /* Raise TypeError for unhashable key */
  2134. dup = PySet_New(ob);
  2135. assertRaises(PySet_Discard(ob, dup) == -1, PyExc_TypeError);
  2136. assertRaises(PySet_Contains(ob, dup) == -1, PyExc_TypeError);
  2137. assertRaises(PySet_Add(ob, dup) == -1, PyExc_TypeError);
  2138. /* Exercise successful pop, contains, add, and discard */
  2139. elem = PySet_Pop(ob);
  2140. assert(PySet_Contains(ob, elem) == 0);
  2141. assert(PySet_GET_SIZE(ob) == 2);
  2142. assert(PySet_Add(ob, elem) == 0);
  2143. assert(PySet_Contains(ob, elem) == 1);
  2144. assert(PySet_GET_SIZE(ob) == 3);
  2145. assert(PySet_Discard(ob, elem) == 1);
  2146. assert(PySet_GET_SIZE(ob) == 2);
  2147. assert(PySet_Discard(ob, elem) == 0);
  2148. assert(PySet_GET_SIZE(ob) == 2);
  2149. /* Exercise clear */
  2150. dup2 = PySet_New(dup);
  2151. assert(PySet_Clear(dup2) == 0);
  2152. assert(PySet_Size(dup2) == 0);
  2153. Py_DECREF(dup2);
  2154. /* Raise SystemError on clear or update of frozen set */
  2155. f = PyFrozenSet_New(dup);
  2156. assertRaises(PySet_Clear(f) == -1, PyExc_SystemError);
  2157. assertRaises(_PySet_Update(f, dup) == -1, PyExc_SystemError);
  2158. assert(PySet_Add(f, elem) == 0);
  2159. Py_INCREF(f);
  2160. assertRaises(PySet_Add(f, elem) == -1, PyExc_SystemError);
  2161. Py_DECREF(f);
  2162. Py_DECREF(f);
  2163. /* Exercise direct iteration */
  2164. i = 0, count = 0;
  2165. while (_PySet_Next((PyObject *)dup, &i, &x)) {
  2166. s = PyString_AsString(x);
  2167. assert(s && (s[0] == 'a' || s[0] == 'b' || s[0] == 'c'));
  2168. count++;
  2169. }
  2170. assert(count == 3);
  2171. /* Exercise updates */
  2172. dup2 = PySet_New(NULL);
  2173. assert(_PySet_Update(dup2, dup) == 0);
  2174. assert(PySet_Size(dup2) == 3);
  2175. assert(_PySet_Update(dup2, dup) == 0);
  2176. assert(PySet_Size(dup2) == 3);
  2177. Py_DECREF(dup2);
  2178. /* Raise SystemError when self argument is not a set or frozenset. */
  2179. t = PyTuple_New(0);
  2180. assertRaises(PySet_Size(t) == -1, PyExc_SystemError);
  2181. assertRaises(PySet_Contains(t, elem) == -1, PyExc_SystemError);
  2182. Py_DECREF(t);
  2183. /* Raise SystemError when self argument is not a set. */
  2184. f = PyFrozenSet_New(dup);
  2185. assert(PySet_Size(f) == 3);
  2186. assert(PyFrozenSet_CheckExact(f));
  2187. assertRaises(PySet_Discard(f, elem) == -1, PyExc_SystemError);
  2188. assertRaises(PySet_Pop(f) == NULL, PyExc_SystemError);
  2189. Py_DECREF(f);
  2190. /* Raise KeyError when popping from an empty set */
  2191. assert(PyNumber_InPlaceSubtract(ob, ob) == ob);
  2192. Py_DECREF(ob);
  2193. assert(PySet_GET_SIZE(ob) == 0);
  2194. assertRaises(PySet_Pop(ob) == NULL, PyExc_KeyError);
  2195. /* Restore the set from the copy using the PyNumber API */
  2196. assert(PyNumber_InPlaceOr(ob, dup) == ob);
  2197. Py_DECREF(ob);
  2198. /* Verify constructors accept NULL arguments */
  2199. f = PySet_New(NULL);
  2200. assert(f != NULL);
  2201. assert(PySet_GET_SIZE(f) == 0);
  2202. Py_DECREF(f);
  2203. f = PyFrozenSet_New(NULL);
  2204. assert(f != NULL);
  2205. assert(PyFrozenSet_CheckExact(f));
  2206. assert(PySet_GET_SIZE(f) == 0);
  2207. Py_DECREF(f);
  2208. Py_DECREF(elem);
  2209. Py_DECREF(dup);
  2210. Py_RETURN_TRUE;
  2211. }
  2212. #undef assertRaises
  2213. #endif