GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — cpython/Objects/setobject.c at 3.13 · python/cpython Expand file tree/ Copy pathsetobject.cMore file actions 2822 lines (2479 loc) · 78.2 KB / Copy pathsetobject.cFile metadata and controls2822 lines (2479 loc) · 78.2 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 /* set object implementation Written and maintained by Raymond D. Hettinger <[email protected]> Derived from Objects/dictobject.c. The basic lookup function used by all operations. This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4. The initial probe index is computed as hash mod the table size. Subsequent probe indices are computed as explained in Objects/dictobject.c. To improve cache locality, each probe inspects a series of consecutive nearby entries before moving on to probes elsewhere in memory. This leaves us with a hybrid of linear probing and randomized probing. The linear probing reduces the cost of hash collisions because consecutive memory accesses tend to be much cheaper than scattered probes. After LINEAR_PROBES steps, we then use more of the upper bits from the hash value and apply a simple linear congruential random number generator. This helps break-up long chains of collisions. All arithmetic on hash should ignore overflow. Unlike the dictionary implementation, the lookkey function can return NULL if the rich comparison returns an error. Use cases for sets differ considerably from dictionaries where looked-up keys are more likely to be present. In contrast, sets are primarily about membership testing where the presence of an element is not known in advance. Accordingly, the set implementation needs to optimize for both the found and not-found case. */ #include "Python.h" #include "pycore_ceval.h" // _PyEval_GetBuiltin() #include "pycore_critical_section.h" // Py_BEGIN_CRITICAL_SECTION, Py_END_CRITICAL_SECTION #include "pycore_dict.h" // _PyDict_Contains_KnownHash() #include "pycore_modsupport.h" // _PyArg_NoKwnames() #include "pycore_object.h" // _PyObject_GC_UNTRACK() #include "pycore_pyatomic_ft_wrappers.h" // FT_ATOMIC_LOAD_SSIZE_RELAXED() #include "pycore_pyerrors.h" // _PyErr_SetKeyError() #include "pycore_setobject.h" // _PySet_NextEntry() definition #include "pycore_weakref.h" // FT_CLEAR_WEAKREFS() #include <stddef.h> // offsetof() #include "clinic/setobject.c.h" /*[clinic input] class set "PySetObject *" "&PySet_Type" class frozenset "PySetObject *" "&PyFrozenSet_Type" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=97ad1d3e9f117079]*/ /*[python input] class setobject_converter(self_converter): type = "PySetObject *" [python start generated code]*/ /*[python end generated code: output=da39a3ee5e6b4b0d input=33a44506d4d57793]*/ /* Object used as dummy key to fill deleted entries */ static PyObject _dummy_struct; #define dummy (&_dummy_struct) /* ======================================================================== */ /* ======= Begin logic for probing the hash table ========================= */ /* Set this to zero to turn-off linear probing */ #ifndef LINEAR_PROBES #define LINEAR_PROBES 9 #endif /* This must be >= 1 */ #define PERTURB_SHIFT 5 static setentry * set_lookkey(PySetObject *so, PyObject *key, Py_hash_t hash) { setentry *table; setentry *entry; size_t perturb = hash; size_t mask = so->mask; size_t i = (size_t)hash & mask; /* Unsigned for defined overflow behavior */ int probes; int cmp; while (1) { entry = &so->table[i]; probes = (i + LINEAR_PROBES <= mask) ? LINEAR_PROBES: 0; do { if (entry->hash == 0 && entry->key == NULL) return entry; if (entry->hash == hash) { PyObject *startkey = entry->key; assert(startkey != dummy); if (startkey == key) return entry; if (PyUnicode_CheckExact(startkey) && PyUnicode_CheckExact(key) && _PyUnicode_EQ(startkey, key)) return entry; table = so->table; Py_INCREF(startkey); cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); Py_DECREF(startkey); if (cmp < 0) return NULL; if (table != so->table || entry->key != startkey) return set_lookkey(so, key, hash); if (cmp > 0) return entry; mask = so->mask; } entry++; } while (probes--); perturb >>= PERTURB_SHIFT; i = (i * 5 + 1 + perturb) & mask; } } static int set_table_resize(PySetObject *, Py_ssize_t); static int set_add_entry(PySetObject *so, PyObject *key, Py_hash_t hash) { setentry *table; setentry *freeslot; setentry *entry; size_t perturb; size_t mask; size_t i; /* Unsigned for defined overflow behavior */ int probes; int cmp; _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so); /* Pre-increment is necessary to prevent arbitrary code in the rich comparison from deallocating the key just before the insertion. */ Py_INCREF(key); restart: mask = so->mask; i = (size_t)hash & mask; freeslot = NULL; perturb = hash; while (1) { entry = &so->table[i]; probes = (i + LINEAR_PROBES <= mask) ? LINEAR_PROBES: 0; do { if (entry->hash == 0 && entry->key == NULL) goto found_unused_or_dummy; if (entry->hash == hash) { PyObject *startkey = entry->key; assert(startkey != dummy); if (startkey == key) goto found_active; if (PyUnicode_CheckExact(startkey) && PyUnicode_CheckExact(key) && _PyUnicode_EQ(startkey, key)) goto found_active; table = so->table; Py_INCREF(startkey); cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); Py_DECREF(startkey); if (cmp > 0) goto found_active; if (cmp < 0) goto comparison_error; if (table != so->table || entry->key != startkey) goto restart; mask = so->mask; } else if (entry->hash == -1) { assert (entry->key == dummy); freeslot = entry; } entry++; } while (probes--); perturb >>= PERTURB_SHIFT; i = (i * 5 + 1 + perturb) & mask; } found_unused_or_dummy: if (freeslot == NULL) goto found_unused; if (freeslot->hash != -1) { goto restart; } FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, so->used + 1); freeslot->key = key; freeslot->hash = hash; return 0; found_unused: so->fill++; FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, so->used + 1); entry->key = key; entry->hash = hash; if ((size_t)so->fill*5 < mask*3) return 0; return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); found_active: Py_DECREF(key); return 0; comparison_error: Py_DECREF(key); return -1; } /* Internal routine used by set_table_resize() to insert an item which is known to be absent from the set. Besides the performance benefit, there is also safety benefit since using set_add_entry() risks making a callback in the middle of a set_table_resize(), see issue 1456209. The caller is responsible for updating the key's reference count and the setobject's fill and used fields. */ static void set_insert_clean(setentry *table, size_t mask, PyObject *key, Py_hash_t hash) { setentry *entry; size_t perturb = hash; size_t i = (size_t)hash & mask; size_t j; while (1) { entry = &table[i]; if (entry->key == NULL) goto found_null; if (i + LINEAR_PROBES <= mask) { for (j = 0; j < LINEAR_PROBES; j++) { entry++; if (entry->key == NULL) goto found_null; } } perturb >>= PERTURB_SHIFT; i = (i * 5 + 1 + perturb) & mask; } found_null: entry->key = key; entry->hash = hash; } /* ======== End logic for probing the hash table ========================== */ /* ======================================================================== */ /* Restructure the table by allocating a new table and reinserting all keys again. When entries have been deleted, the new table may actually be smaller than the old one. */ static int set_table_resize(PySetObject *so, Py_ssize_t minused) { setentry *oldtable, *newtable, *entry; Py_ssize_t oldmask = so->mask; size_t newmask; int is_oldtable_malloced; setentry small_copy[PySet_MINSIZE]; assert(minused >= 0); /* Find the smallest table size > minused. */ /* XXX speed-up with intrinsics */ size_t newsize = PySet_MINSIZE; while (newsize <= (size_t)minused) { newsize <<= 1; // The largest possible value is PY_SSIZE_T_MAX + 1. } /* Get space for a new table. */ oldtable = so->table; assert(oldtable != NULL); is_oldtable_malloced = oldtable != so->smalltable; if (newsize == PySet_MINSIZE) { /* A large table is shrinking, or we can't get any smaller. */ newtable = so->smalltable; if (newtable == oldtable) { if (so->fill == so->used) { /* No dummies, so no point doing anything. */ return 0; } /* We're not going to resize it, but rebuild the table anyway to purge old dummy entries. Subtle: This is *necessary* if fill==size, as set_lookkey needs at least one virgin slot to terminate failing searches. If fill < size, it's merely desirable, as dummies slow searches. */ assert(so->fill > so->used); memcpy(small_copy, oldtable, sizeof(small_copy)); oldtable = small_copy; } } else { newtable = PyMem_NEW(setentry, newsize); if (newtable == NULL) { PyErr_NoMemory(); return -1; } } /* Make the set empty, using the new table. */ assert(newtable != oldtable); memset(newtable, 0, sizeof(setentry) * newsize); so->mask = newsize - 1; so->table = newtable; /* Copy the data over; this is refcount-neutral for active entries; dummy entries aren't copied over, of course */ newmask = (size_t)so->mask; if (so->fill == so->used) { for (entry = oldtable; entry <= oldtable + oldmask; entry++) { if (entry->key != NULL) { set_insert_clean(newtable, newmask, entry->key, entry->hash); } } } else { so->fill = so->used; for (entry = oldtable; entry <= oldtable + oldmask; entry++) { if (entry->key != NULL && entry->key != dummy) { set_insert_clean(newtable, newmask, entry->key, entry->hash); } } } if (is_oldtable_malloced) PyMem_Free(oldtable); return 0; } static int set_contains_entry(PySetObject *so, PyObject *key, Py_hash_t hash) { setentry *entry; entry = set_lookkey(so, key, hash); if (entry != NULL) return entry->key != NULL; return -1; } #define DISCARD_NOTFOUND 0 #define DISCARD_FOUND 1 static int set_discard_entry(PySetObject *so, PyObject *key, Py_hash_t hash) { setentry *entry; PyObject *old_key; entry = set_lookkey(so, key, hash); if (entry == NULL) return -1; if (entry->key == NULL) return DISCARD_NOTFOUND; old_key = entry->key; entry->key = dummy; entry->hash = -1; FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, so->used - 1); Py_DECREF(old_key); return DISCARD_FOUND; } static int set_add_key(PySetObject *so, PyObject *key) { Py_hash_t hash = _PyObject_HashFast(key); if (hash == -1) { return -1; } return set_add_entry(so, key, hash); } static int set_contains_key(PySetObject *so, PyObject *key) { Py_hash_t hash = _PyObject_HashFast(key); if (hash == -1) { return -1; } return set_contains_entry(so, key, hash); } static int set_discard_key(PySetObject *so, PyObject *key) { Py_hash_t hash = _PyObject_HashFast(key); if (hash == -1) { return -1; } return set_discard_entry(so, key, hash); } static void set_empty_to_minsize(PySetObject *so) { memset(so->smalltable, 0, sizeof(so->smalltable)); so->fill = 0; FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, 0); so->mask = PySet_MINSIZE - 1; so->table = so->smalltable; FT_ATOMIC_STORE_SSIZE_RELAXED(so->hash, -1); } static int set_clear_internal(PySetObject *so) { setentry *entry; setentry *table = so->table; Py_ssize_t fill = so->fill; Py_ssize_t used = so->used; int table_is_malloced = table != so->smalltable; setentry small_copy[PySet_MINSIZE]; assert (PyAnySet_Check(so)); assert(table != NULL); /* This is delicate. During the process of clearing the set, * decrefs can cause the set to mutate. To avoid fatal confusion * (voice of experience), we have to make the set empty before * clearing the slots, and never refer to anything via so->ref while * clearing. */ if (table_is_malloced) set_empty_to_minsize(so); else if (fill > 0) { /* It's a small table with something that needs to be cleared. * Afraid the only safe way is to copy the set entries into * another small table first. */ memcpy(small_copy, table, sizeof(small_copy)); table = small_copy; set_empty_to_minsize(so); } /* else it's a small table that's already empty */ /* Now we can finally clear things. If C had refcounts, we could * assert that the refcount on table is 1 now, i.e. that this function * has unique access to it, so decref side-effects can't alter it. */ for (entry = table; used > 0; entry++) { if (entry->key && entry->key != dummy) { used--; Py_DECREF(entry->key); } } if (table_is_malloced) PyMem_Free(table); return 0; } /* * Iterate over a set table. Use like so: * * Py_ssize_t pos; * setentry *entry; * pos = 0; # important! pos should not otherwise be changed by you * while (set_next(yourset, &pos, &entry)) { * Refer to borrowed reference in entry->key. * } * * CAUTION: In general, it isn't safe to use set_next in a loop that * mutates the table. */ static int set_next(PySetObject *so, Py_ssize_t *pos_ptr, setentry **entry_ptr) { Py_ssize_t i; Py_ssize_t mask; setentry *entry; assert (PyAnySet_Check(so)); i = *pos_ptr; assert(i >= 0); mask = so->mask; entry = &so->table[i]; while (i <= mask && (entry->key == NULL || entry->key == dummy)) { i++; entry++; } *pos_ptr = i+1; if (i > mask) return 0; assert(entry != NULL); *entry_ptr = entry; return 1; } static void set_dealloc(PySetObject *so) { setentry *entry; Py_ssize_t used = so->used; /* bpo-31095: UnTrack is needed before calling any callbacks */ PyObject_GC_UnTrack(so); Py_TRASHCAN_BEGIN(so, set_dealloc) FT_CLEAR_WEAKREFS((PyObject *) so, so->weakreflist); for (entry = so->table; used > 0; entry++) { if (entry->key && entry->key != dummy) { used--; Py_DECREF(entry->key); } } if (so->table != so->smalltable) PyMem_Free(so->table); Py_TYPE(so)->tp_free(so); Py_TRASHCAN_END } static PyObject * set_repr_lock_held(PySetObject *so) { PyObject *result=NULL, *keys, *listrepr, *tmp; int status = Py_ReprEnter((PyObject*)so); if (status != 0) { if (status < 0) return NULL; return PyUnicode_FromFormat("%s(...)", Py_TYPE(so)->tp_name); } /* shortcut for the empty set */ if (!so->used) { Py_ReprLeave((PyObject*)so); return PyUnicode_FromFormat("%s()", Py_TYPE(so)->tp_name); } // gh-129967: avoid PySequence_List because it might re-lock the object // lock or the GIL and allow something to clear the set from underneath us. keys = PyList_New(so->used); if (keys == NULL) { goto done; } Py_ssize_t pos = 0, idx = 0; setentry *entry; while (set_next(so, &pos, &entry)) { PyList_SET_ITEM(keys, idx++, Py_NewRef(entry->key)); } /* repr(keys)[1:-1] */ listrepr = PyObject_Repr(keys); Py_DECREF(keys); if (listrepr == NULL) goto done; tmp = PyUnicode_Substring(listrepr, 1, PyUnicode_GET_LENGTH(listrepr)-1); Py_DECREF(listrepr); if (tmp == NULL) goto done; listrepr = tmp; if (!PySet_CheckExact(so)) result = PyUnicode_FromFormat("%s({%U})", Py_TYPE(so)->tp_name, listrepr); else result = PyUnicode_FromFormat("{%U}", listrepr); Py_DECREF(listrepr); done: Py_ReprLeave((PyObject*)so); return result; } static PyObject * set_repr(PySetObject *so) { PyObject *result; Py_BEGIN_CRITICAL_SECTION(so); result = set_repr_lock_held(so); Py_END_CRITICAL_SECTION(); return result; } static Py_ssize_t set_len(PySetObject *so) { return FT_ATOMIC_LOAD_SSIZE_RELAXED(so->used); } static int set_merge_lock_held(PySetObject *so, PyObject *otherset) { PySetObject *other; PyObject *key; Py_ssize_t i; setentry *so_entry; setentry *other_entry; assert (PyAnySet_Check(so)); assert (PyAnySet_Check(otherset)); _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so); _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(otherset); other = (PySetObject*)otherset; if (other == so || other->used == 0) /* a.update(a) or a.update(set()); nothing to do */ return 0; /* Do one big resize at the start, rather than * incrementally resizing as we insert new keys. Expect * that there will be no (or few) overlapping keys. */ if ((so->fill + other->used)*5 >= so->mask*3) { if (set_table_resize(so, (so->used + other->used)*2) != 0) return -1; } so_entry = so->table; other_entry = other->table; /* If our table is empty, and both tables have the same size, and there are no dummies to eliminate, then just copy the pointers. */ if (so->fill == 0 && so->mask == other->mask && other->fill == other->used) { for (i = 0; i <= other->mask; i++, so_entry++, other_entry++) { key = other_entry->key; if (key != NULL) { assert(so_entry->key == NULL); so_entry->key = Py_NewRef(key); so_entry->hash = other_entry->hash; } } so->fill = other->fill; FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, other->used); return 0; } /* If our table is empty, we can use set_insert_clean() */ if (so->fill == 0) { setentry *newtable = so->table; size_t newmask = (size_t)so->mask; so->fill = other->used; FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, other->used); for (i = other->mask + 1; i > 0 ; i--, other_entry++) { key = other_entry->key; if (key != NULL && key != dummy) { set_insert_clean(newtable, newmask, Py_NewRef(key), other_entry->hash); } } return 0; } /* We can't assure there are no duplicates, so do normal insertions */ for (i = 0; i <= other->mask; i++) { other_entry = &other->table[i]; key = other_entry->key; if (key != NULL && key != dummy) { if (set_add_entry(so, key, other_entry->hash)) return -1; } } return 0; } /*[clinic input] @critical_section set.pop so: setobject Remove and return an arbitrary set element. Raises KeyError if the set is empty. [clinic start generated code]*/ static PyObject * set_pop_impl(PySetObject *so) /*[clinic end generated code: output=4d65180f1271871b input=9296c84921125060]*/ { /* Make sure the search finger is in bounds */ setentry *entry = so->table + (so->finger & so->mask); setentry *limit = so->table + so->mask; PyObject *key; if (so->used == 0) { PyErr_SetString(PyExc_KeyError, "pop from an empty set"); return NULL; } while (entry->key == NULL || entry->key==dummy) { entry++; if (entry > limit) entry = so->table; } key = entry->key; entry->key = dummy; entry->hash = -1; FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, so->used - 1); so->finger = entry - so->table + 1; /* next place to start */ return key; } static int set_traverse(PySetObject *so, visitproc visit, void *arg) { Py_ssize_t pos = 0; setentry *entry; while (set_next(so, &pos, &entry)) Py_VISIT(entry->key); return 0; } /* Work to increase the bit dispersion for closely spaced hash values. This is important because some use cases have many combinations of a small number of elements with nearby hashes so that many distinct combinations collapse to only a handful of distinct hash values. */ static Py_uhash_t _shuffle_bits(Py_uhash_t h) { return ((h ^ 89869747UL) ^ (h << 16)) * 3644798167UL; } /* Most of the constants in this hash algorithm are randomly chosen large primes with "interesting bit patterns" and that passed tests for good collision statistics on a variety of problematic datasets including powersets and graph structures (such as David Eppstein's graph recipes in Lib/test/test_set.py). */ static Py_hash_t frozenset_hash_impl(PyObject *self) { PySetObject *so = _PySet_CAST(self); Py_uhash_t hash = 0; setentry *entry; /* Xor-in shuffled bits from every entry's hash field because xor is commutative and a frozenset hash should be independent of order. For speed, include null entries and dummy entries and then subtract out their effect afterwards so that the final hash depends only on active entries. This allows the code to be vectorized by the compiler and it saves the unpredictable branches that would arise when trying to exclude null and dummy entries on every iteration. */ for (entry = so->table; entry <= &so->table[so->mask]; entry++) hash ^= _shuffle_bits(entry->hash); /* Remove the effect of an odd number of NULL entries */ if ((so->mask + 1 - so->fill) & 1) hash ^= _shuffle_bits(0); /* Remove the effect of an odd number of dummy entries */ if ((so->fill - so->used) & 1) hash ^= _shuffle_bits(-1); /* Factor in the number of active entries */ hash ^= ((Py_uhash_t)PySet_GET_SIZE(self) + 1) * 1927868237UL; /* Disperse patterns arising in nested frozensets */ hash ^= (hash >> 11) ^ (hash >> 25); hash = hash * 69069U + 907133923UL; /* -1 is reserved as an error code */ if (hash == (Py_uhash_t)-1) hash = 590923713UL; return (Py_hash_t)hash; } static Py_hash_t frozenset_hash(PyObject *self) { PySetObject *so = _PySet_CAST(self); Py_uhash_t hash; if (FT_ATOMIC_LOAD_SSIZE_RELAXED(so->hash) != -1) { return FT_ATOMIC_LOAD_SSIZE_RELAXED(so->hash); } hash = frozenset_hash_impl(self); FT_ATOMIC_STORE_SSIZE_RELAXED(so->hash, hash); return hash; } /***** Set iterator type ***********************************************/ typedef struct { PyObject_HEAD PySetObject *si_set; /* Set to NULL when iterator is exhausted */ Py_ssize_t si_used; Py_ssize_t si_pos; Py_ssize_t len; } setiterobject; static void setiter_dealloc(setiterobject *si) { /* bpo-31095: UnTrack is needed before calling any callbacks */ _PyObject_GC_UNTRACK(si); Py_XDECREF(si->si_set); PyObject_GC_Del(si); } static int setiter_traverse(setiterobject *si, visitproc visit, void *arg) { Py_VISIT(si->si_set); return 0; } static PyObject * setiter_len(setiterobject *si, PyObject *Py_UNUSED(ignored)) { Py_ssize_t len = 0; if (si->si_set != NULL && si->si_used == si->si_set->used) len = si->len; return PyLong_FromSsize_t(len); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyObject *setiter_iternext(setiterobject *si); static PyObject * setiter_reduce(setiterobject *si, PyObject *Py_UNUSED(ignored)) { /* copy the iterator state */ setiterobject tmp = *si; Py_XINCREF(tmp.si_set); /* iterate the temporary into a list */ PyObject *list = PySequence_List((PyObject*)&tmp); Py_XDECREF(tmp.si_set); if (list == NULL) { return NULL; } return Py_BuildValue("N(N)", _PyEval_GetBuiltin(&_Py_ID(iter)), list); } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); static PyMethodDef setiter_methods[] = { {"__length_hint__", (PyCFunction)setiter_len, METH_NOARGS, length_hint_doc}, {"__reduce__", (PyCFunction)setiter_reduce, METH_NOARGS, reduce_doc}, {NULL, NULL} /* sentinel */ }; static PyObject *setiter_iternext(setiterobject *si) { PyObject *key = NULL; Py_ssize_t i, mask; setentry *entry; PySetObject *so = si->si_set; if (so == NULL) return NULL; assert (PyAnySet_Check(so)); Py_ssize_t so_used = FT_ATOMIC_LOAD_SSIZE(so->used); Py_ssize_t si_used = FT_ATOMIC_LOAD_SSIZE(si->si_used); if (si_used != so_used) { PyErr_SetString(PyExc_RuntimeError, "Set changed size during iteration"); si->si_used = -1; /* Make this state sticky */ return NULL; } Py_BEGIN_CRITICAL_SECTION(so); i = si->si_pos; assert(i>=0); entry = so->table; mask = so->mask; while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy)) { i++; } if (i <= mask) { key = Py_NewRef(entry[i].key); } Py_END_CRITICAL_SECTION(); si->si_pos = i+1; if (key == NULL) { si->si_set = NULL; Py_DECREF(so); return NULL; } si->len--; return key; } PyTypeObject PySetIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "set_iterator", /* tp_name */ sizeof(setiterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)setiter_dealloc, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)setiter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)setiter_iternext, /* tp_iternext */ setiter_methods, /* tp_methods */ 0, }; static PyObject * set_iter(PySetObject *so) { Py_ssize_t size = set_len(so); setiterobject *si = PyObject_GC_New(setiterobject, &PySetIter_Type); if (si == NULL) return NULL; si->si_set = (PySetObject*)Py_NewRef(so); si->si_used = size; si->si_pos = 0; si->len = size; _PyObject_GC_TRACK(si); return (PyObject *)si; } static int set_update_dict_lock_held(PySetObject *so, PyObject *other) { assert(PyDict_CheckExact(other)); _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so); _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(other); /* Do one big resize at the start, rather than * incrementally resizing as we insert new keys. Expect * that there will be no (or few) overlapping keys. */ Py_ssize_t dictsize = PyDict_GET_SIZE(other); if ((so->fill + dictsize)*5 >= so->mask*3) { if (set_table_resize(so, (so->used + dictsize)*2) != 0) { return -1; } } Py_ssize_t pos = 0; PyObject *key; PyObject *value; Py_hash_t hash; while (_PyDict_Next(other, &pos, &key, &value, &hash)) { if (set_add_entry(so, key, hash)) { return -1; } } return 0; } static int set_update_iterable_lock_held(PySetObject *so, PyObject *other) { _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so); PyObject *it = PyObject_GetIter(other); if (it == NULL) { return -1; } PyObject *key; while ((key = PyIter_Next(it)) != NULL) { if (set_add_key(so, key)) { Py_DECREF(it); Py_DECREF(key); return -1; } Py_DECREF(key); } Py_DECREF(it); if (PyErr_Occurred()) return -1; return 0; } static int set_update_lock_held(PySetObject *so, PyObject *other) { if (PyAnySet_Check(other)) { return set_merge_lock_held(so, other); } else if (PyDict_CheckExact(other)) { return set_update_dict_lock_held(so, other); } |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |