Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/setobject.c
Line
Count
Source
1
2
/* set object implementation
3
4
   Written and maintained by Raymond D. Hettinger <python@rcn.com>
5
   Derived from Objects/dictobject.c.
6
7
   The basic lookup function used by all operations.
8
   This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
9
10
   The initial probe index is computed as hash mod the table size.
11
   Subsequent probe indices are computed as explained in Objects/dictobject.c.
12
13
   To improve cache locality, each probe inspects a series of consecutive
14
   nearby entries before moving on to probes elsewhere in memory.  This leaves
15
   us with a hybrid of linear probing and randomized probing.  The linear probing
16
   reduces the cost of hash collisions because consecutive memory accesses
17
   tend to be much cheaper than scattered probes.  After LINEAR_PROBES steps,
18
   we then use more of the upper bits from the hash value and apply a simple
19
   linear congruential random number generator.  This helps break-up long
20
   chains of collisions.
21
22
   All arithmetic on hash should ignore overflow.
23
24
   Unlike the dictionary implementation, the lookkey function can return
25
   NULL if the rich comparison returns an error.
26
27
   Use cases for sets differ considerably from dictionaries where looked-up
28
   keys are more likely to be present.  In contrast, sets are primarily
29
   about membership testing where the presence of an element is not known in
30
   advance.  Accordingly, the set implementation needs to optimize for both
31
   the found and not-found case.
32
*/
33
34
#include "Python.h"
35
#include "pycore_ceval.h"               // _PyEval_GetBuiltin()
36
#include "pycore_critical_section.h"    // Py_BEGIN_CRITICAL_SECTION, Py_END_CRITICAL_SECTION
37
#include "pycore_dict.h"                // _PyDict_Contains_KnownHash()
38
#include "pycore_modsupport.h"          // _PyArg_NoKwnames()
39
#include "pycore_object.h"              // _PyObject_GC_UNTRACK()
40
#include "pycore_pyatomic_ft_wrappers.h"  // FT_ATOMIC_LOAD_SSIZE_RELAXED()
41
#include "pycore_pyerrors.h"            // _PyErr_SetKeyError()
42
#include "pycore_setobject.h"           // _PySet_NextEntry() definition
43
#include "pycore_weakref.h"             // FT_CLEAR_WEAKREFS()
44
45
#include "stringlib/eq.h"               // unicode_eq()
46
#include <stddef.h>                     // offsetof()
47
#include "clinic/setobject.c.h"
48
49
/*[clinic input]
50
class set "PySetObject *" "&PySet_Type"
51
class frozenset "PySetObject *" "&PyFrozenSet_Type"
52
[clinic start generated code]*/
53
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=97ad1d3e9f117079]*/
54
55
/*[python input]
56
class setobject_converter(self_converter):
57
    type = "PySetObject *"
58
[python start generated code]*/
59
/*[python end generated code: output=da39a3ee5e6b4b0d input=33a44506d4d57793]*/
60
61
/* Object used as dummy key to fill deleted entries */
62
static PyObject _dummy_struct;
63
64
29.5M
#define dummy (&_dummy_struct)
65
66
92.3M
#define SET_LOOKKEY_FOUND 1
67
988M
#define SET_LOOKKEY_NO_MATCH 0
68
0
#define SET_LOOKKEY_ERROR (-1)
69
103M
#define SET_LOOKKEY_CHANGED (-2)
70
534M
#define SET_LOOKKEY_EMPTY (-3)
71
72
typedef int (*compare_func)(PySetObject *so, setentry *table, setentry *ep,
73
                            PyObject *key, Py_hash_t hash);
74
75
#ifdef Py_GIL_DISABLED
76
77
#define SET_IS_SHARED(so) _PyObject_GC_IS_SHARED(so)
78
#define SET_MARK_SHARED(so) _PyObject_GC_SET_SHARED(so)
79
80
static void
81
ensure_shared_on_read(PySetObject *so)
82
{
83
    if (!_Py_IsOwnedByCurrentThread((PyObject *)so) && !SET_IS_SHARED(so)) {
84
        // The first time we access a set from a non-owning thread we mark it
85
        // as shared. This ensures that a concurrent resize operation will
86
        // delay freeing the old entries using QSBR, which is necessary
87
        // to safely allow concurrent reads without locking...
88
        Py_BEGIN_CRITICAL_SECTION(so);
89
        if (!SET_IS_SHARED(so)) {
90
            SET_MARK_SHARED(so);
91
        }
92
        Py_END_CRITICAL_SECTION();
93
    }
94
}
95
96
static inline Py_ALWAYS_INLINE int
97
set_compare_threadsafe(PySetObject *so, setentry *table, setentry *ep,
98
                       PyObject *key, Py_hash_t hash)
99
{
100
    PyObject *startkey = FT_ATOMIC_LOAD_PTR_ACQUIRE(ep->key);
101
    if (startkey == NULL) {
102
        return SET_LOOKKEY_EMPTY;
103
    }
104
    if (startkey == key) {
105
        return SET_LOOKKEY_FOUND;
106
    }
107
    Py_ssize_t ep_hash = FT_ATOMIC_LOAD_SSIZE_ACQUIRE(ep->hash);
108
    if (ep_hash == hash) {
109
        if (!_Py_TryIncrefCompare(&ep->key, startkey)) {
110
            return SET_LOOKKEY_CHANGED;
111
        }
112
        int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
113
        Py_DECREF(startkey);
114
        if (cmp < 0) {
115
            return SET_LOOKKEY_ERROR;
116
        }
117
        if (table == FT_ATOMIC_LOAD_PTR_ACQUIRE(so->table) &&
118
            startkey == FT_ATOMIC_LOAD_PTR_ACQUIRE(ep->key)) {
119
            assert(cmp == SET_LOOKKEY_FOUND || cmp == SET_LOOKKEY_NO_MATCH);
120
            return cmp;
121
        }
122
        else {
123
            /* The set was mutated, restart */
124
            return SET_LOOKKEY_CHANGED;
125
        }
126
    }
127
    return SET_LOOKKEY_NO_MATCH;
128
}
129
130
#else
131
132
249k
#define SET_IS_SHARED(so) 0
133
#define SET_MARK_SHARED(so)
134
135
#endif
136
137
static inline Py_ALWAYS_INLINE int
138
set_compare_entry_lock_held(PySetObject *so, setentry *table, setentry *entry,
139
                            PyObject *key, Py_hash_t hash)
140
202M
{
141
202M
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so);
142
202M
    if (entry->hash == 0 && entry->key == NULL)
143
71.2M
        return SET_LOOKKEY_EMPTY;
144
131M
    if (entry->hash == hash) {
145
32.4M
        PyObject *startkey = entry->key;
146
32.4M
        assert(startkey != dummy);
147
32.4M
        if (startkey == key)
148
32.4M
            return SET_LOOKKEY_FOUND;
149
23.8k
        if (PyUnicode_CheckExact(startkey)
150
23.8k
            && PyUnicode_CheckExact(key)
151
2.20k
            && unicode_eq(startkey, key))
152
2.20k
            return SET_LOOKKEY_FOUND;
153
21.6k
        table = so->table;
154
21.6k
        Py_INCREF(startkey);
155
21.6k
        int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
156
21.6k
        Py_DECREF(startkey);
157
21.6k
        if (cmp < 0)
158
0
            return SET_LOOKKEY_ERROR;
159
21.6k
        if (table != so->table || entry->key != startkey)
160
0
            return SET_LOOKKEY_CHANGED;
161
21.6k
        if (cmp > 0)
162
21.6k
            return SET_LOOKKEY_FOUND;
163
21.6k
    }
164
98.6M
    return SET_LOOKKEY_NO_MATCH;
165
131M
}
166
167
// This is similar to set_compare_entry_lock_held() but we don't need to
168
// incref startkey before comparing and we don't need to check if the set has
169
// changed.  This also omits the PyUnicode_CheckExact() special case since it
170
// doesn't help much for frozensets.
171
static inline Py_ALWAYS_INLINE int
172
set_compare_frozenset(PySetObject *so, setentry *table, setentry *ep,
173
                                 PyObject *key, Py_hash_t hash)
174
337M
{
175
337M
    assert(PyFrozenSet_Check(so));
176
337M
    PyObject *startkey = ep->key;
177
337M
    if (startkey == NULL) {
178
149M
        return SET_LOOKKEY_EMPTY;
179
149M
    }
180
188M
    if (startkey == key) {
181
59.8M
        return SET_LOOKKEY_FOUND;
182
59.8M
    }
183
128M
    Py_ssize_t ep_hash = ep->hash;
184
128M
    if (ep_hash == hash) {
185
69.0k
        int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
186
69.0k
        if (cmp < 0) {
187
0
            return SET_LOOKKEY_ERROR;
188
0
        }
189
69.0k
        assert(cmp == SET_LOOKKEY_FOUND || cmp == SET_LOOKKEY_NO_MATCH);
190
69.0k
        return cmp;
191
69.0k
    }
192
128M
    return SET_LOOKKEY_NO_MATCH;
193
128M
}
194
195
static void
196
set_zero_table(setentry *table, size_t size)
197
325k
{
198
#ifdef Py_GIL_DISABLED
199
    for (size_t i = 0; i < size; i++) {
200
        setentry *entry = &table[i];
201
        FT_ATOMIC_STORE_SSIZE_RELAXED(entry->hash, 0);
202
        FT_ATOMIC_STORE_PTR_RELEASE(entry->key, NULL);
203
    }
204
#else
205
325k
    memset(table, 0, sizeof(setentry)*size);
206
325k
#endif
207
325k
}
208
209
/* ======================================================================== */
210
/* ======= Begin logic for probing the hash table ========================= */
211
212
/* Set this to zero to turn-off linear probing */
213
#ifndef LINEAR_PROBES
214
589M
#define LINEAR_PROBES 9
215
#endif
216
217
/* This must be >= 1 */
218
43.4M
#define PERTURB_SHIFT 5
219
220
static int
221
set_do_lookup(PySetObject *so, setentry *table, size_t mask, PyObject *key,
222
              Py_hash_t hash, setentry **epp, compare_func compare_entry)
223
313M
{
224
313M
    setentry *entry;
225
313M
    size_t perturb = hash;
226
313M
    size_t i = (size_t)hash & mask; /* Unsigned for defined overflow behavior */
227
313M
    int probes;
228
313M
    int status;
229
230
355M
    while (1) {
231
355M
        entry = &table[i];
232
355M
        probes = (i + LINEAR_PROBES <= mask) ? LINEAR_PROBES: 0;
233
540M
        do {
234
540M
            status = compare_entry(so, table, entry, key, hash);
235
540M
            if (status != SET_LOOKKEY_NO_MATCH) {
236
313M
                if (status == SET_LOOKKEY_EMPTY) {
237
220M
                    return SET_LOOKKEY_NO_MATCH;
238
220M
                }
239
92.3M
                *epp = entry;
240
92.3M
                return status;
241
313M
            }
242
226M
            entry++;
243
226M
        } while (probes--);
244
42.6M
        perturb >>= PERTURB_SHIFT;
245
42.6M
        i = (i * 5 + 1 + perturb) & mask;
246
42.6M
    }
247
313M
    Py_UNREACHABLE();
248
313M
}
249
250
static int set_table_resize(PySetObject *, Py_ssize_t);
251
252
static int
253
set_add_entry_takeref(PySetObject *so, PyObject *key, Py_hash_t hash)
254
23.8M
{
255
23.8M
    setentry *table;
256
23.8M
    setentry *freeslot;
257
23.8M
    setentry *entry;
258
23.8M
    size_t perturb;
259
23.8M
    size_t mask;
260
23.8M
    size_t i;                       /* Unsigned for defined overflow behavior */
261
23.8M
    int probes;
262
23.8M
    int cmp;
263
264
23.8M
  restart:
265
266
23.8M
    mask = so->mask;
267
23.8M
    i = (size_t)hash & mask;
268
23.8M
    freeslot = NULL;
269
23.8M
    perturb = hash;
270
271
24.7M
    while (1) {
272
24.7M
        entry = &so->table[i];
273
24.7M
        probes = (i + LINEAR_PROBES <= mask) ? LINEAR_PROBES: 0;
274
30.6M
        do {
275
30.6M
            if (entry->hash == 0 && entry->key == NULL)
276
15.8M
                goto found_unused_or_dummy;
277
14.7M
            if (entry->hash == hash) {
278
7.97M
                PyObject *startkey = entry->key;
279
7.97M
                assert(startkey != dummy);
280
7.97M
                if (startkey == key)
281
198k
                    goto found_active;
282
7.77M
                if (PyUnicode_CheckExact(startkey)
283
7.77M
                    && PyUnicode_CheckExact(key)
284
429k
                    && unicode_eq(startkey, key))
285
429k
                    goto found_active;
286
7.34M
                table = so->table;
287
7.34M
                Py_INCREF(startkey);
288
7.34M
                cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
289
7.34M
                Py_DECREF(startkey);
290
7.34M
                if (cmp > 0)
291
7.34M
                    goto found_active;
292
474
                if (cmp < 0)
293
0
                    goto comparison_error;
294
474
                if (table != so->table || entry->key != startkey)
295
0
                    goto restart;
296
474
                mask = so->mask;
297
474
            }
298
6.82M
            else if (entry->hash == -1) {
299
13
                assert (entry->key == dummy);
300
13
                freeslot = entry;
301
13
            }
302
6.82M
            entry++;
303
6.82M
        } while (probes--);
304
867k
        perturb >>= PERTURB_SHIFT;
305
867k
        i = (i * 5 + 1 + perturb) & mask;
306
867k
    }
307
308
15.8M
  found_unused_or_dummy:
309
15.8M
    if (freeslot == NULL)
310
15.8M
        goto found_unused;
311
9
    if (freeslot->hash != -1) {
312
0
        goto restart;
313
0
    }
314
9
    FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, so->used + 1);
315
9
    FT_ATOMIC_STORE_SSIZE_RELAXED(freeslot->hash, hash);
316
9
    FT_ATOMIC_STORE_PTR_RELEASE(freeslot->key, key);
317
9
    return 0;
318
319
15.8M
  found_unused:
320
15.8M
    so->fill++;
321
15.8M
    FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, so->used + 1);
322
15.8M
    FT_ATOMIC_STORE_SSIZE_RELAXED(entry->hash, hash);
323
15.8M
    FT_ATOMIC_STORE_PTR_RELEASE(entry->key, key);
324
15.8M
    if ((size_t)so->fill*5 < mask*3)
325
15.6M
        return 0;
326
238k
    return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
327
328
7.97M
  found_active:
329
7.97M
    Py_DECREF(key);
330
7.97M
    return 0;
331
332
0
  comparison_error:
333
0
    Py_DECREF(key);
334
0
    return -1;
335
15.8M
}
336
337
static int
338
set_add_entry(PySetObject *so, PyObject *key, Py_hash_t hash)
339
23.6M
{
340
23.6M
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so);
341
342
23.6M
    return set_add_entry_takeref(so, Py_NewRef(key), hash);
343
23.6M
}
344
345
static void
346
set_unhashable_type(PyObject *key)
347
0
{
348
0
    PyObject *exc = PyErr_GetRaisedException();
349
0
    assert(exc != NULL);
350
0
    if (!Py_IS_TYPE(exc, (PyTypeObject*)PyExc_TypeError)) {
351
0
        PyErr_SetRaisedException(exc);
352
0
        return;
353
0
    }
354
355
0
    PyErr_Format(PyExc_TypeError,
356
0
                 "cannot use '%T' as a set element (%S)",
357
0
                 key, exc);
358
0
    Py_DECREF(exc);
359
0
}
360
361
int
362
_PySet_AddTakeRef(PySetObject *so, PyObject *key)
363
255k
{
364
255k
    Py_hash_t hash = PyObject_Hash(key);
365
255k
    if (hash == -1) {
366
0
        set_unhashable_type(key);
367
0
        Py_DECREF(key);
368
0
        return -1;
369
0
    }
370
    // We don't pre-increment here, the caller holds a strong
371
    // reference to the object which we are stealing.
372
255k
    return set_add_entry_takeref(so, key, hash);
373
255k
}
374
375
/*
376
Internal routine used by set_table_resize() to insert an item which is
377
known to be absent from the set.  Besides the performance benefit,
378
there is also safety benefit since using set_add_entry() risks making
379
a callback in the middle of a set_table_resize(), see issue 1456209.
380
The caller is responsible for updating the key's reference count and
381
the setobject's fill and used fields.
382
*/
383
static void
384
set_insert_clean(setentry *table, size_t mask, PyObject *key, Py_hash_t hash)
385
6.68M
{
386
6.68M
    setentry *entry;
387
6.68M
    size_t perturb = hash;
388
6.68M
    size_t i = (size_t)hash & mask;
389
6.68M
    size_t j;
390
391
6.70M
    while (1) {
392
6.70M
        entry = &table[i];
393
6.70M
        if (entry->key == NULL)
394
6.27M
            goto found_null;
395
432k
        if (i + LINEAR_PROBES <= mask) {
396
574k
            for (j = 0; j < LINEAR_PROBES; j++) {
397
566k
                entry++;
398
566k
                if (entry->key == NULL)
399
411k
                    goto found_null;
400
566k
            }
401
420k
        }
402
21.2k
        perturb >>= PERTURB_SHIFT;
403
21.2k
        i = (i * 5 + 1 + perturb) & mask;
404
21.2k
    }
405
6.68M
  found_null:
406
6.68M
    FT_ATOMIC_STORE_SSIZE_RELAXED(entry->hash, hash);
407
6.68M
    FT_ATOMIC_STORE_PTR_RELEASE(entry->key, key);
408
6.68M
}
409
410
/* ======== End logic for probing the hash table ========================== */
411
/* ======================================================================== */
412
413
static int
414
set_lookkey(PySetObject *so, PyObject *key, Py_hash_t hash, setentry **epp)
415
313M
{
416
313M
    int status;
417
313M
    if (PyFrozenSet_CheckExact(so)) {
418
209M
        status = set_do_lookup(so, so->table, so->mask, key, hash, epp,
419
209M
                               set_compare_frozenset);
420
209M
    }
421
103M
    else {
422
103M
        Py_BEGIN_CRITICAL_SECTION(so);
423
103M
        do {
424
103M
            status = set_do_lookup(so, so->table, so->mask, key, hash, epp,
425
103M
                                   set_compare_entry_lock_held);
426
103M
        } while (status == SET_LOOKKEY_CHANGED);
427
103M
        Py_END_CRITICAL_SECTION();
428
103M
    }
429
313M
    assert(status == SET_LOOKKEY_FOUND ||
430
313M
           status == SET_LOOKKEY_NO_MATCH ||
431
313M
           status == SET_LOOKKEY_ERROR);
432
313M
    return status;
433
313M
}
434
435
#ifdef Py_GIL_DISABLED
436
static int
437
set_lookkey_threadsafe(PySetObject *so, PyObject *key, Py_hash_t hash)
438
{
439
    int status;
440
    setentry *entry;
441
    if (PyFrozenSet_CheckExact(so)) {
442
        status = set_do_lookup(so, so->table, so->mask, key, hash, &entry,
443
                               set_compare_frozenset);
444
        assert(status == SET_LOOKKEY_FOUND ||
445
               status == SET_LOOKKEY_NO_MATCH ||
446
               status == SET_LOOKKEY_ERROR);
447
        return status;
448
    }
449
    ensure_shared_on_read(so);
450
    setentry *table = FT_ATOMIC_LOAD_PTR_ACQUIRE(so->table);
451
    size_t mask = FT_ATOMIC_LOAD_SSIZE_ACQUIRE(so->mask);
452
    if (table == NULL || table != FT_ATOMIC_LOAD_PTR_ACQUIRE(so->table)) {
453
        return set_lookkey(so, key, hash, &entry);
454
    }
455
    status = set_do_lookup(so, table, mask, key, hash, &entry,
456
                           set_compare_threadsafe);
457
    if (status == SET_LOOKKEY_CHANGED) {
458
        return set_lookkey(so, key, hash, &entry);
459
    }
460
    assert(status == SET_LOOKKEY_FOUND ||
461
           status == SET_LOOKKEY_NO_MATCH ||
462
           status == SET_LOOKKEY_ERROR);
463
    return status;
464
}
465
#endif
466
467
static void free_entries(setentry *entries, size_t size, bool use_qsbr)
468
249k
{
469
#ifdef Py_GIL_DISABLED
470
    if (use_qsbr) {
471
        _PyMem_FreeDelayed(entries, size * sizeof(setentry));
472
        return;
473
    }
474
#endif
475
249k
    PyMem_Free(entries);
476
249k
}
477
478
/*
479
Restructure the table by allocating a new table and reinserting all
480
keys again.  When entries have been deleted, the new table may
481
actually be smaller than the old one.
482
*/
483
static int
484
set_table_resize(PySetObject *so, Py_ssize_t minused)
485
251k
{
486
251k
    setentry *oldtable, *newtable, *entry;
487
251k
    Py_ssize_t oldmask = so->mask;
488
251k
    Py_ssize_t oldsize = (size_t)oldmask + 1;
489
251k
    size_t newmask;
490
251k
    int is_oldtable_malloced;
491
251k
    setentry small_copy[PySet_MINSIZE];
492
493
251k
    assert(minused >= 0);
494
495
    /* Find the smallest table size > minused. */
496
    /* XXX speed-up with intrinsics */
497
251k
    size_t newsize = PySet_MINSIZE;
498
915k
    while (newsize <= (size_t)minused) {
499
663k
        newsize <<= 1; // The largest possible value is PY_SSIZE_T_MAX + 1.
500
663k
    }
501
502
    /* Get space for a new table. */
503
251k
    oldtable = so->table;
504
251k
    assert(oldtable != NULL);
505
251k
    is_oldtable_malloced = oldtable != so->smalltable;
506
507
251k
    if (newsize == PySet_MINSIZE) {
508
        /* A large table is shrinking, or we can't get any smaller. */
509
0
        newtable = so->smalltable;
510
0
        if (newtable == oldtable) {
511
0
            if (so->fill == so->used) {
512
                /* No dummies, so no point doing anything. */
513
0
                return 0;
514
0
            }
515
            /* We're not going to resize it, but rebuild the
516
               table anyway to purge old dummy entries.
517
               Subtle:  This is *necessary* if fill==size,
518
               as set_lookkey needs at least one virgin slot to
519
               terminate failing searches.  If fill < size, it's
520
               merely desirable, as dummies slow searches. */
521
0
            assert(so->fill > so->used);
522
0
            memcpy(small_copy, oldtable, sizeof(small_copy));
523
0
            oldtable = small_copy;
524
0
        }
525
0
    }
526
251k
    else {
527
251k
        newtable = PyMem_NEW(setentry, newsize);
528
251k
        if (newtable == NULL) {
529
0
            PyErr_NoMemory();
530
0
            return -1;
531
0
        }
532
251k
    }
533
534
    /* Make the set empty, using the new table. */
535
251k
    assert(newtable != oldtable);
536
251k
    set_zero_table(newtable, newsize);
537
251k
    FT_ATOMIC_STORE_PTR_RELEASE(so->table, NULL);
538
251k
    FT_ATOMIC_STORE_SSIZE_RELEASE(so->mask, newsize - 1);
539
540
    /* Copy the data over; this is refcount-neutral for active entries;
541
       dummy entries aren't copied over, of course */
542
251k
    newmask = (size_t)so->mask;
543
251k
    if (so->fill == so->used) {
544
11.3M
        for (entry = oldtable; entry <= oldtable + oldmask; entry++) {
545
11.1M
            if (entry->key != NULL) {
546
6.67M
                set_insert_clean(newtable, newmask, entry->key, entry->hash);
547
6.67M
            }
548
11.1M
        }
549
251k
    } else {
550
4
        so->fill = so->used;
551
132
        for (entry = oldtable; entry <= oldtable + oldmask; entry++) {
552
128
            if (entry->key != NULL && entry->key != dummy) {
553
55
                set_insert_clean(newtable, newmask, entry->key, entry->hash);
554
55
            }
555
128
        }
556
4
    }
557
558
251k
    FT_ATOMIC_STORE_PTR_RELEASE(so->table, newtable);
559
560
251k
    if (is_oldtable_malloced)
561
54.0k
        free_entries(oldtable, oldsize, SET_IS_SHARED(so));
562
251k
    return 0;
563
251k
}
564
565
static int
566
set_contains_entry(PySetObject *so, PyObject *key, Py_hash_t hash)
567
313M
{
568
#ifdef Py_GIL_DISABLED
569
    return set_lookkey_threadsafe(so, key, hash);
570
#else
571
313M
    setentry *entry; // unused
572
313M
    return set_lookkey(so, key, hash, &entry);
573
313M
#endif
574
313M
}
575
576
34.3k
#define DISCARD_NOTFOUND 0
577
953
#define DISCARD_FOUND 1
578
579
static int
580
set_discard_entry(PySetObject *so, PyObject *key, Py_hash_t hash)
581
35.3k
{
582
35.3k
    setentry *entry;
583
35.3k
    PyObject *old_key;
584
35.3k
    int status = set_lookkey(so, key, hash, &entry);
585
35.3k
    if (status < 0) {
586
0
        return -1;
587
0
    }
588
35.3k
    if (status == SET_LOOKKEY_NO_MATCH) {
589
34.3k
        return DISCARD_NOTFOUND;
590
34.3k
    }
591
35.3k
    assert(status == SET_LOOKKEY_FOUND);
592
953
    old_key = entry->key;
593
953
    FT_ATOMIC_STORE_SSIZE_RELAXED(entry->hash, -1);
594
953
    FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, so->used - 1);
595
953
    FT_ATOMIC_STORE_PTR_RELEASE(entry->key, dummy);
596
953
    Py_DECREF(old_key);
597
953
    return DISCARD_FOUND;
598
35.3k
}
599
600
static int
601
set_add_key(PySetObject *so, PyObject *key)
602
23.3M
{
603
23.3M
    Py_hash_t hash = PyObject_Hash(key);
604
23.3M
    if (hash == -1) {
605
0
        set_unhashable_type(key);
606
0
        return -1;
607
0
    }
608
23.3M
    return set_add_entry(so, key, hash);
609
23.3M
}
610
611
static int
612
set_contains_key(PySetObject *so, PyObject *key)
613
18.8M
{
614
18.8M
    Py_hash_t hash = PyObject_Hash(key);
615
18.8M
    if (hash == -1) {
616
0
        set_unhashable_type(key);
617
0
        return -1;
618
0
    }
619
18.8M
    return set_contains_entry(so, key, hash);
620
18.8M
}
621
622
static int
623
set_discard_key(PySetObject *so, PyObject *key)
624
35.2k
{
625
35.2k
    Py_hash_t hash = PyObject_Hash(key);
626
35.2k
    if (hash == -1) {
627
0
        set_unhashable_type(key);
628
0
        return -1;
629
0
    }
630
35.2k
    return set_discard_entry(so, key, hash);
631
35.2k
}
632
633
static void
634
set_empty_to_minsize(PySetObject *so)
635
74.1k
{
636
74.1k
    FT_ATOMIC_STORE_PTR_RELEASE(so->table, NULL);
637
74.1k
    set_zero_table(so->smalltable, PySet_MINSIZE);
638
74.1k
    so->fill = 0;
639
74.1k
    FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, 0);
640
74.1k
    FT_ATOMIC_STORE_SSIZE_RELEASE(so->mask, PySet_MINSIZE - 1);
641
74.1k
    FT_ATOMIC_STORE_SSIZE_RELAXED(so->hash, -1);
642
74.1k
    FT_ATOMIC_STORE_PTR_RELEASE(so->table, so->smalltable);
643
74.1k
}
644
645
static int
646
set_clear_internal(PyObject *self)
647
319k
{
648
319k
    PySetObject *so = _PySet_CAST(self);
649
319k
    setentry *entry;
650
319k
    setentry *table = so->table;
651
319k
    Py_ssize_t fill = so->fill;
652
319k
    Py_ssize_t used = so->used;
653
319k
    Py_ssize_t oldsize = (size_t)so->mask + 1;
654
319k
    int table_is_malloced = table != so->smalltable;
655
319k
    setentry small_copy[PySet_MINSIZE];
656
657
319k
    assert (PyAnySet_Check(so));
658
319k
    assert(table != NULL);
659
660
    /* This is delicate.  During the process of clearing the set,
661
     * decrefs can cause the set to mutate.  To avoid fatal confusion
662
     * (voice of experience), we have to make the set empty before
663
     * clearing the slots, and never refer to anything via so->ref while
664
     * clearing.
665
     */
666
319k
    if (table_is_malloced)
667
31.3k
        set_empty_to_minsize(so);
668
669
287k
    else if (fill > 0) {
670
        /* It's a small table with something that needs to be cleared.
671
         * Afraid the only safe way is to copy the set entries into
672
         * another small table first.
673
         */
674
42.8k
        memcpy(small_copy, table, sizeof(small_copy));
675
42.8k
        table = small_copy;
676
42.8k
        set_empty_to_minsize(so);
677
42.8k
    }
678
    /* else it's a small table that's already empty */
679
680
    /* Now we can finally clear things.  If C had refcounts, we could
681
     * assert that the refcount on table is 1 now, i.e. that this function
682
     * has unique access to it, so decref side-effects can't alter it.
683
     */
684
21.8M
    for (entry = table; used > 0; entry++) {
685
21.4M
        if (entry->key && entry->key != dummy) {
686
5.01M
            used--;
687
5.01M
            Py_DECREF(entry->key);
688
5.01M
        }
689
21.4M
    }
690
691
319k
    if (table_is_malloced)
692
31.3k
        free_entries(table, oldsize, SET_IS_SHARED(so));
693
319k
    return 0;
694
319k
}
695
696
/*
697
 * Iterate over a set table.  Use like so:
698
 *
699
 *     Py_ssize_t pos;
700
 *     setentry *entry;
701
 *     pos = 0;   # important!  pos should not otherwise be changed by you
702
 *     while (set_next(yourset, &pos, &entry)) {
703
 *              Refer to borrowed reference in entry->key.
704
 *     }
705
 *
706
 * CAUTION:  In general, it isn't safe to use set_next in a loop that
707
 * mutates the table.
708
 */
709
static int
710
set_next(PySetObject *so, Py_ssize_t *pos_ptr, setentry **entry_ptr)
711
21.5M
{
712
21.5M
    Py_ssize_t i;
713
21.5M
    Py_ssize_t mask;
714
21.5M
    setentry *entry;
715
716
21.5M
    assert (PyAnySet_Check(so));
717
21.5M
    i = *pos_ptr;
718
21.5M
    assert(i >= 0);
719
21.5M
    mask = so->mask;
720
21.5M
    entry = &so->table[i];
721
137M
    while (i <= mask && (entry->key == NULL || entry->key == dummy)) {
722
116M
        i++;
723
116M
        entry++;
724
116M
    }
725
21.5M
    *pos_ptr = i+1;
726
21.5M
    if (i > mask)
727
13.3M
        return 0;
728
21.5M
    assert(entry != NULL);
729
8.12M
    *entry_ptr = entry;
730
8.12M
    return 1;
731
21.5M
}
732
733
static void
734
set_dealloc(PyObject *self)
735
12.9M
{
736
12.9M
    PySetObject *so = _PySet_CAST(self);
737
12.9M
    setentry *entry;
738
12.9M
    Py_ssize_t used = so->used;
739
12.9M
    Py_ssize_t oldsize = (size_t)so->mask + 1;
740
741
    /* bpo-31095: UnTrack is needed before calling any callbacks */
742
12.9M
    PyObject_GC_UnTrack(so);
743
12.9M
    FT_CLEAR_WEAKREFS(self, so->weakreflist);
744
745
44.8M
    for (entry = so->table; used > 0; entry++) {
746
31.9M
        if (entry->key && entry->key != dummy) {
747
11.0M
                used--;
748
11.0M
                Py_DECREF(entry->key);
749
11.0M
        }
750
31.9M
    }
751
12.9M
    if (so->table != so->smalltable)
752
164k
        free_entries(so->table, oldsize, SET_IS_SHARED(so));
753
12.9M
    Py_TYPE(so)->tp_free(so);
754
12.9M
}
755
756
/*[clinic input]
757
@critical_section
758
set.__repr__
759
760
    so: setobject
761
[clinic start generated code]*/
762
763
static PyObject *
764
set_repr_impl(PySetObject *so)
765
/*[clinic end generated code: output=5dfbb5e7f7c947ad input=f6743ec76163d7b3]*/
766
0
{
767
0
    PyObject *result=NULL, *keys, *listrepr, *tmp;
768
0
    int status = Py_ReprEnter((PyObject*)so);
769
770
0
    if (status != 0) {
771
0
        if (status < 0)
772
0
            return NULL;
773
0
        return PyUnicode_FromFormat("%s(...)", Py_TYPE(so)->tp_name);
774
0
    }
775
776
    /* shortcut for the empty set */
777
0
    if (!so->used) {
778
0
        Py_ReprLeave((PyObject*)so);
779
0
        return PyUnicode_FromFormat("%s()", Py_TYPE(so)->tp_name);
780
0
    }
781
782
    // gh-129967: avoid PySequence_List because it might re-lock the object
783
    // lock or the GIL and allow something to clear the set from underneath us.
784
0
    keys = PyList_New(so->used);
785
0
    if (keys == NULL) {
786
0
        goto done;
787
0
    }
788
789
0
    Py_ssize_t pos = 0, idx = 0;
790
0
    setentry *entry;
791
0
    while (set_next(so, &pos, &entry)) {
792
0
        PyList_SET_ITEM(keys, idx++, Py_NewRef(entry->key));
793
0
    }
794
795
    /* repr(keys)[1:-1] */
796
0
    listrepr = PyObject_Repr(keys);
797
0
    Py_DECREF(keys);
798
0
    if (listrepr == NULL)
799
0
        goto done;
800
0
    tmp = PyUnicode_Substring(listrepr, 1, PyUnicode_GET_LENGTH(listrepr)-1);
801
0
    Py_DECREF(listrepr);
802
0
    if (tmp == NULL)
803
0
        goto done;
804
0
    listrepr = tmp;
805
806
0
    if (!PySet_CheckExact(so))
807
0
        result = PyUnicode_FromFormat("%s({%U})",
808
0
                                      Py_TYPE(so)->tp_name,
809
0
                                      listrepr);
810
0
    else
811
0
        result = PyUnicode_FromFormat("{%U}", listrepr);
812
0
    Py_DECREF(listrepr);
813
0
done:
814
0
    Py_ReprLeave((PyObject*)so);
815
0
    return result;
816
0
}
817
818
static Py_ssize_t
819
set_len(PyObject *self)
820
388k
{
821
388k
    PySetObject *so = _PySet_CAST(self);
822
388k
    return FT_ATOMIC_LOAD_SSIZE_RELAXED(so->used);
823
388k
}
824
825
static int
826
set_merge_lock_held(PySetObject *so, PyObject *otherset)
827
389k
{
828
389k
    PySetObject *other;
829
389k
    PyObject *key;
830
389k
    Py_ssize_t i;
831
389k
    setentry *so_entry;
832
389k
    setentry *other_entry;
833
834
389k
    assert (PyAnySet_Check(so));
835
389k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so);
836
389k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(otherset);
837
838
389k
    other = _PySet_CAST(otherset);
839
389k
    if (other == so || other->used == 0)
840
        /* a.update(a) or a.update(set()); nothing to do */
841
117k
        return 0;
842
    /* Do one big resize at the start, rather than
843
     * incrementally resizing as we insert new keys.  Expect
844
     * that there will be no (or few) overlapping keys.
845
     */
846
271k
    if ((so->fill + other->used)*5 >= so->mask*3) {
847
12.8k
        if (set_table_resize(so, (so->used + other->used)*2) != 0)
848
0
            return -1;
849
12.8k
    }
850
271k
    so_entry = so->table;
851
271k
    other_entry = other->table;
852
853
    /* If our table is empty, and both tables have the same size, and
854
       there are no dummies to eliminate, then just copy the pointers. */
855
271k
    if (so->fill == 0 && so->mask == other->mask && other->fill == other->used) {
856
835k
        for (i = 0; i <= other->mask; i++, so_entry++, other_entry++) {
857
747k
            key = other_entry->key;
858
747k
            if (key != NULL) {
859
232k
                assert(so_entry->key == NULL);
860
232k
                FT_ATOMIC_STORE_SSIZE_RELAXED(so_entry->hash, other_entry->hash);
861
232k
                FT_ATOMIC_STORE_PTR_RELEASE(so_entry->key, Py_NewRef(key));
862
232k
            }
863
747k
        }
864
88.0k
        so->fill = other->fill;
865
88.0k
        FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, other->used);
866
88.0k
        return 0;
867
88.0k
    }
868
869
    /* If our table is empty, we can use set_insert_clean() */
870
183k
    if (so->fill == 0) {
871
740
        setentry *newtable = so->table;
872
740
        size_t newmask = (size_t)so->mask;
873
740
        so->fill = other->used;
874
740
        FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, other->used);
875
31.5k
        for (i = other->mask + 1; i > 0 ; i--, other_entry++) {
876
30.7k
            key = other_entry->key;
877
30.7k
            if (key != NULL && key != dummy) {
878
6.41k
                set_insert_clean(newtable, newmask, Py_NewRef(key),
879
6.41k
                                 other_entry->hash);
880
6.41k
            }
881
30.7k
        }
882
740
        return 0;
883
740
    }
884
885
    /* We can't assure there are no duplicates, so do normal insertions */
886
1.74M
    for (i = 0; i <= other->mask; i++) {
887
1.55M
        other_entry = &other->table[i];
888
1.55M
        key = other_entry->key;
889
1.55M
        if (key != NULL && key != dummy) {
890
288k
            if (set_add_entry(so, key, other_entry->hash))
891
0
                return -1;
892
288k
        }
893
1.55M
    }
894
182k
    return 0;
895
182k
}
896
897
/*[clinic input]
898
@critical_section
899
set.pop
900
    so: setobject
901
902
Remove and return an arbitrary set element.
903
904
Raises KeyError if the set is empty.
905
[clinic start generated code]*/
906
907
static PyObject *
908
set_pop_impl(PySetObject *so)
909
/*[clinic end generated code: output=4d65180f1271871b input=9296c84921125060]*/
910
332
{
911
    /* Make sure the search finger is in bounds */
912
332
    setentry *entry = so->table + (so->finger & so->mask);
913
332
    setentry *limit = so->table + so->mask;
914
332
    PyObject *key;
915
916
332
    if (so->used == 0) {
917
0
        PyErr_SetString(PyExc_KeyError, "pop from an empty set");
918
0
        return NULL;
919
0
    }
920
1.95k
    while (entry->key == NULL || entry->key==dummy) {
921
1.62k
        entry++;
922
1.62k
        if (entry > limit)
923
0
            entry = so->table;
924
1.62k
    }
925
332
    FT_ATOMIC_STORE_SSIZE_RELAXED(entry->hash, -1);
926
332
    FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, so->used - 1);
927
332
    key = entry->key;
928
332
    FT_ATOMIC_STORE_PTR_RELEASE(entry->key, dummy);
929
332
    so->finger = entry - so->table + 1;   /* next place to start */
930
332
    return key;
931
332
}
932
933
static int
934
set_traverse(PyObject *self, visitproc visit, void *arg)
935
11.8M
{
936
11.8M
    PySetObject *so = _PySet_CAST(self);
937
11.8M
    Py_ssize_t pos = 0;
938
11.8M
    setentry *entry;
939
940
16.5M
    while (set_next(so, &pos, &entry))
941
4.70M
        Py_VISIT(entry->key);
942
11.8M
    return 0;
943
11.8M
}
944
945
/* Work to increase the bit dispersion for closely spaced hash values.
946
   This is important because some use cases have many combinations of a
947
   small number of elements with nearby hashes so that many distinct
948
   combinations collapse to only a handful of distinct hash values. */
949
950
static Py_uhash_t
951
_shuffle_bits(Py_uhash_t h)
952
964k
{
953
964k
    return ((h ^ 89869747UL) ^ (h << 16)) * 3644798167UL;
954
964k
}
955
956
/* Most of the constants in this hash algorithm are randomly chosen
957
   large primes with "interesting bit patterns" and that passed tests
958
   for good collision statistics on a variety of problematic datasets
959
   including powersets and graph structures (such as David Eppstein's
960
   graph recipes in Lib/test/test_set.py).
961
962
   This hash algorithm can be used on either a frozenset or a set.
963
   When it is used on a set, it computes the hash value of the equivalent
964
   frozenset without creating a new frozenset object.
965
966
   If you update this code, update also frozendict_hash() which copied this
967
   code. */
968
969
static Py_hash_t
970
frozenset_hash_impl(PyObject *self)
971
118k
{
972
118k
    PySetObject *so = _PySet_CAST(self);
973
118k
    Py_uhash_t hash = 0;
974
118k
    setentry *entry;
975
976
    /* Xor-in shuffled bits from every entry's hash field because xor is
977
       commutative and a frozenset hash should be independent of order.
978
979
       For speed, include null entries and dummy entries and then
980
       subtract out their effect afterwards so that the final hash
981
       depends only on active entries.  This allows the code to be
982
       vectorized by the compiler and it saves the unpredictable
983
       branches that would arise when trying to exclude null and dummy
984
       entries on every iteration. */
985
986
1.08M
    for (entry = so->table; entry <= &so->table[so->mask]; entry++)
987
964k
        hash ^= _shuffle_bits(entry->hash);
988
989
    /* Remove the effect of an odd number of NULL entries */
990
118k
    if ((so->mask + 1 - so->fill) & 1)
991
473
        hash ^= _shuffle_bits(0);
992
993
    /* Remove the effect of an odd number of dummy entries */
994
118k
    if ((so->fill - so->used) & 1)
995
0
        hash ^= _shuffle_bits(-1);
996
997
    /* Factor in the number of active entries */
998
118k
    hash ^= ((Py_uhash_t)PySet_GET_SIZE(self) + 1) * 1927868237UL;
999
1000
    /* Disperse patterns arising in nested frozensets */
1001
118k
    hash ^= (hash >> 11) ^ (hash >> 25);
1002
118k
    hash = hash * 69069U + 907133923UL;
1003
1004
    /* -1 is reserved as an error code */
1005
118k
    if (hash == (Py_uhash_t)-1)
1006
0
        hash = 590923713UL;
1007
1008
118k
    return (Py_hash_t)hash;
1009
118k
}
1010
1011
static Py_hash_t
1012
frozenset_hash(PyObject *self)
1013
118k
{
1014
118k
    PySetObject *so = _PySet_CAST(self);
1015
118k
    Py_uhash_t hash;
1016
1017
118k
    if (FT_ATOMIC_LOAD_SSIZE_RELAXED(so->hash) != -1) {
1018
442
        return FT_ATOMIC_LOAD_SSIZE_ACQUIRE(so->hash);
1019
442
    }
1020
1021
118k
    hash = frozenset_hash_impl(self);
1022
118k
    FT_ATOMIC_STORE_SSIZE_RELEASE(so->hash, hash);
1023
118k
    return hash;
1024
118k
}
1025
1026
/***** Set iterator type ***********************************************/
1027
1028
typedef struct {
1029
    PyObject_HEAD
1030
    /* Set to NULL when the iterator is exhausted, except in the free-threaded
1031
       build, where the reference is kept until the iterator is deallocated
1032
       (see setiter_set_exhausted()). */
1033
    PySetObject *si_set;
1034
    Py_ssize_t si_used;
1035
    Py_ssize_t si_pos;
1036
    Py_ssize_t len;
1037
} setiterobject;
1038
1039
static void
1040
setiter_dealloc(PyObject *self)
1041
377k
{
1042
377k
    setiterobject *si = (setiterobject*)self;
1043
    /* bpo-31095: UnTrack is needed before calling any callbacks */
1044
377k
    _PyObject_GC_UNTRACK(si);
1045
377k
    Py_XDECREF(si->si_set);
1046
377k
    PyObject_GC_Del(si);
1047
377k
}
1048
1049
static int
1050
setiter_traverse(PyObject *self, visitproc visit, void *arg)
1051
14.6k
{
1052
14.6k
    setiterobject *si = (setiterobject*)self;
1053
14.6k
    Py_VISIT(si->si_set);
1054
14.6k
    return 0;
1055
14.6k
}
1056
1057
static PyObject *
1058
setiter_len(PyObject *op, PyObject *Py_UNUSED(ignored))
1059
10
{
1060
10
    setiterobject *si = (setiterobject*)op;
1061
10
    Py_ssize_t len = 0;
1062
10
    PySetObject *so = si->si_set;
1063
10
    if (so != NULL) {
1064
10
        Py_ssize_t so_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(so->used);
1065
10
        Py_ssize_t si_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(si->si_used);
1066
10
        if (si_used == so_used) {
1067
10
            len = FT_ATOMIC_LOAD_SSIZE_RELAXED(si->len);
1068
10
        }
1069
10
    }
1070
10
    return PyLong_FromSsize_t(len);
1071
10
}
1072
1073
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
1074
1075
static PyObject *
1076
setiter_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
1077
0
{
1078
0
    setiterobject *si = (setiterobject*)op;
1079
1080
    /* copy the iterator state */
1081
0
    setiterobject tmp = *si;
1082
0
    Py_XINCREF(tmp.si_set);
1083
1084
    /* iterate the temporary into a list */
1085
0
    PyObject *list = PySequence_List((PyObject*)&tmp);
1086
0
    Py_XDECREF(tmp.si_set);
1087
0
    if (list == NULL) {
1088
0
        return NULL;
1089
0
    }
1090
0
    return Py_BuildValue("N(N)", _PyEval_GetBuiltin(&_Py_ID(iter)), list);
1091
0
}
1092
1093
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1094
1095
static PyMethodDef setiter_methods[] = {
1096
    {"__length_hint__", setiter_len, METH_NOARGS, length_hint_doc},
1097
    {"__reduce__", setiter_reduce, METH_NOARGS, reduce_doc},
1098
    {NULL,              NULL}           /* sentinel */
1099
};
1100
1101
/* Mark the iterator as exhausted.  In the free-threaded build an iterator
1102
   may be advanced by several threads at once, each holding a borrowed
1103
   pointer to si_set, so the iterator keeps its reference to the set until
1104
   it is deallocated (as list and tuple iterators do) and records exhaustion
1105
   by setting si_pos to SETITER_EXHAUSTED. */
1106
5.40M
#define SETITER_EXHAUSTED (-1)
1107
1108
static void
1109
setiter_set_exhausted(setiterobject *si, PySetObject *so)
1110
376k
{
1111
#ifdef Py_GIL_DISABLED
1112
    FT_ATOMIC_STORE_SSIZE_RELAXED(si->si_pos, SETITER_EXHAUSTED);
1113
    FT_ATOMIC_STORE_SSIZE_RELAXED(si->len, 0);
1114
#else
1115
376k
    si->si_set = NULL;
1116
376k
    Py_DECREF(so);
1117
376k
#endif
1118
376k
}
1119
1120
static PyObject *setiter_iternext(PyObject *self)
1121
5.40M
{
1122
5.40M
    setiterobject *si = (setiterobject*)self;
1123
5.40M
    PyObject *key = NULL;
1124
5.40M
    Py_ssize_t i, mask;
1125
5.40M
    setentry *entry;
1126
5.40M
    PySetObject *so = si->si_set;
1127
1128
5.40M
    if (so == NULL)
1129
0
        return NULL;
1130
5.40M
    assert (PyAnySet_Check(so));
1131
1132
#ifdef Py_GIL_DISABLED
1133
    if (FT_ATOMIC_LOAD_SSIZE_RELAXED(si->si_pos) == SETITER_EXHAUSTED) {
1134
        return NULL;
1135
    }
1136
#endif
1137
1138
5.40M
    Py_ssize_t so_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(so->used);
1139
5.40M
    Py_ssize_t si_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(si->si_used);
1140
5.40M
    if (si_used != so_used) {
1141
0
        PyErr_SetString(PyExc_RuntimeError,
1142
0
                        "Set changed size during iteration");
1143
        /* Make this state sticky */
1144
0
        FT_ATOMIC_STORE_SSIZE_RELAXED(si->si_used, -1);
1145
0
        return NULL;
1146
0
    }
1147
1148
    /* si_pos and len are only written with the set locked, so that an
1149
       iterator marked as exhausted by another thread stays exhausted. */
1150
5.40M
    Py_BEGIN_CRITICAL_SECTION(so);
1151
5.40M
    i = si->si_pos;
1152
5.40M
    if (i != SETITER_EXHAUSTED) {
1153
5.40M
        assert(i >= 0);
1154
5.40M
        entry = so->table;
1155
5.40M
        mask = so->mask;
1156
24.4M
        while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy)) {
1157
19.0M
            i++;
1158
19.0M
        }
1159
5.40M
        if (i <= mask) {
1160
5.02M
            key = Py_NewRef(entry[i].key);
1161
5.02M
            FT_ATOMIC_STORE_SSIZE_RELAXED(si->si_pos, i + 1);
1162
5.02M
            FT_ATOMIC_STORE_SSIZE_RELAXED(si->len, si->len - 1);
1163
5.02M
        }
1164
376k
        else {
1165
376k
            setiter_set_exhausted(si, so);
1166
376k
        }
1167
5.40M
    }
1168
5.40M
    Py_END_CRITICAL_SECTION();
1169
5.40M
    return key;
1170
5.40M
}
1171
1172
PyTypeObject PySetIter_Type = {
1173
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1174
    "set_iterator",                             /* tp_name */
1175
    sizeof(setiterobject),                      /* tp_basicsize */
1176
    0,                                          /* tp_itemsize */
1177
    /* methods */
1178
    setiter_dealloc,                            /* tp_dealloc */
1179
    0,                                          /* tp_vectorcall_offset */
1180
    0,                                          /* tp_getattr */
1181
    0,                                          /* tp_setattr */
1182
    0,                                          /* tp_as_async */
1183
    0,                                          /* tp_repr */
1184
    0,                                          /* tp_as_number */
1185
    0,                                          /* tp_as_sequence */
1186
    0,                                          /* tp_as_mapping */
1187
    0,                                          /* tp_hash */
1188
    0,                                          /* tp_call */
1189
    0,                                          /* tp_str */
1190
    PyObject_GenericGetAttr,                    /* tp_getattro */
1191
    0,                                          /* tp_setattro */
1192
    0,                                          /* tp_as_buffer */
1193
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
1194
    0,                                          /* tp_doc */
1195
    setiter_traverse,                           /* tp_traverse */
1196
    0,                                          /* tp_clear */
1197
    0,                                          /* tp_richcompare */
1198
    0,                                          /* tp_weaklistoffset */
1199
    PyObject_SelfIter,                          /* tp_iter */
1200
    setiter_iternext,                           /* tp_iternext */
1201
    setiter_methods,                            /* tp_methods */
1202
    0,
1203
};
1204
1205
static PyObject *
1206
set_iter(PyObject *so)
1207
377k
{
1208
377k
    Py_ssize_t size = set_len(so);
1209
377k
    setiterobject *si = PyObject_GC_New(setiterobject, &PySetIter_Type);
1210
377k
    if (si == NULL)
1211
0
        return NULL;
1212
377k
    si->si_set = (PySetObject*)Py_NewRef(so);
1213
377k
    si->si_used = size;
1214
377k
    si->si_pos = 0;
1215
377k
    si->len = size;
1216
377k
    _PyObject_GC_TRACK(si);
1217
377k
    return (PyObject *)si;
1218
377k
}
1219
1220
static int
1221
set_update_dict_lock_held(PySetObject *so, PyObject *other)
1222
272
{
1223
272
    assert(PyAnyDict_CheckExact(other));
1224
1225
272
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so);
1226
#ifdef Py_DEBUG
1227
    if (!PyFrozenDict_CheckExact(other)) {
1228
        _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(other);
1229
    }
1230
#endif
1231
1232
    /* Do one big resize at the start, rather than
1233
    * incrementally resizing as we insert new keys.  Expect
1234
    * that there will be no (or few) overlapping keys.
1235
    */
1236
272
    Py_ssize_t dictsize = PyDict_GET_SIZE(other);
1237
272
    if ((so->fill + dictsize)*5 >= so->mask*3) {
1238
38
        if (set_table_resize(so, (so->used + dictsize)*2) != 0) {
1239
0
            return -1;
1240
0
        }
1241
38
    }
1242
1243
272
    Py_ssize_t pos = 0;
1244
272
    PyObject *key;
1245
272
    PyObject *value;
1246
272
    Py_hash_t hash;
1247
923
    while (_PyDict_Next(other, &pos, &key, &value, &hash)) {
1248
651
        if (set_add_entry(so, key, hash)) {
1249
0
            return -1;
1250
0
        }
1251
651
    }
1252
272
    return 0;
1253
272
}
1254
1255
static int
1256
set_update_iterable_lock_held(PySetObject *so, PyObject *other)
1257
22.8k
{
1258
22.8k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so);
1259
1260
22.8k
    PyObject *it = PyObject_GetIter(other);
1261
22.8k
    if (it == NULL) {
1262
0
        return -1;
1263
0
    }
1264
1265
22.8k
    PyObject *key;
1266
146k
    while ((key = PyIter_Next(it)) != NULL) {
1267
123k
        if (set_add_key(so, key)) {
1268
0
            Py_DECREF(it);
1269
0
            Py_DECREF(key);
1270
0
            return -1;
1271
0
        }
1272
123k
        Py_DECREF(key);
1273
123k
    }
1274
22.8k
    Py_DECREF(it);
1275
22.8k
    if (PyErr_Occurred())
1276
0
        return -1;
1277
22.8k
    return 0;
1278
22.8k
}
1279
1280
static int
1281
set_update_lock_held(PySetObject *so, PyObject *other)
1282
0
{
1283
0
    if (PyAnySet_Check(other)) {
1284
0
        return set_merge_lock_held(so, other);
1285
0
    }
1286
0
    else if (PyAnyDict_CheckExact(other)) {
1287
0
        return set_update_dict_lock_held(so, other);
1288
0
    }
1289
0
    return set_update_iterable_lock_held(so, other);
1290
0
}
1291
1292
// set_update for a `so` that is only visible to the current thread
1293
static int
1294
set_update_local(PySetObject *so, PyObject *other)
1295
160k
{
1296
160k
    assert(Py_REFCNT(so) == 1);
1297
160k
    if (PyAnySet_Check(other)) {
1298
140k
        int rv;
1299
140k
        Py_BEGIN_CRITICAL_SECTION(other);
1300
140k
        rv = set_merge_lock_held(so, other);
1301
140k
        Py_END_CRITICAL_SECTION();
1302
140k
        return rv;
1303
140k
    }
1304
19.4k
    else if (PyDict_CheckExact(other)) {
1305
272
        int rv;
1306
272
        Py_BEGIN_CRITICAL_SECTION(other);
1307
272
        rv = set_update_dict_lock_held(so, other);
1308
272
        Py_END_CRITICAL_SECTION();
1309
272
        return rv;
1310
272
    }
1311
19.2k
    else if (PyFrozenDict_CheckExact(other)) {
1312
0
        return set_update_dict_lock_held(so, other);
1313
0
    }
1314
19.2k
    return set_update_iterable_lock_held(so, other);
1315
160k
}
1316
1317
static int
1318
set_update_internal(PySetObject *so, PyObject *other)
1319
251k
{
1320
251k
    if (PyAnySet_Check(other)) {
1321
247k
        if (Py_Is((PyObject *)so, other)) {
1322
0
            return 0;
1323
0
        }
1324
247k
        int rv;
1325
247k
        Py_BEGIN_CRITICAL_SECTION2(so, other);
1326
247k
        rv = set_merge_lock_held(so, other);
1327
247k
        Py_END_CRITICAL_SECTION2();
1328
247k
        return rv;
1329
247k
    }
1330
3.60k
    else if (PyDict_CheckExact(other)) {
1331
0
        int rv;
1332
0
        Py_BEGIN_CRITICAL_SECTION2(so, other);
1333
0
        rv = set_update_dict_lock_held(so, other);
1334
0
        Py_END_CRITICAL_SECTION2();
1335
0
        return rv;
1336
0
    }
1337
3.60k
    else if (PyFrozenDict_CheckExact(other)) {
1338
0
        int rv;
1339
0
        Py_BEGIN_CRITICAL_SECTION(so);
1340
0
        rv = set_update_dict_lock_held(so, other);
1341
0
        Py_END_CRITICAL_SECTION();
1342
0
        return rv;
1343
0
    }
1344
3.60k
    else {
1345
3.60k
        int rv;
1346
3.60k
        Py_BEGIN_CRITICAL_SECTION(so);
1347
3.60k
        rv = set_update_iterable_lock_held(so, other);
1348
3.60k
        Py_END_CRITICAL_SECTION();
1349
3.60k
        return rv;
1350
3.60k
    }
1351
251k
}
1352
1353
/*[clinic input]
1354
set.update
1355
    so: setobject
1356
    *others: array
1357
1358
Update the set, adding elements from all others.
1359
[clinic start generated code]*/
1360
1361
static PyObject *
1362
set_update_impl(PySetObject *so, PyObject * const *others,
1363
                Py_ssize_t others_length)
1364
/*[clinic end generated code: output=017c781c992d5c23 input=ed5d78885b076636]*/
1365
180k
{
1366
180k
    Py_ssize_t i;
1367
1368
360k
    for (i = 0; i < others_length; i++) {
1369
180k
        PyObject *other = others[i];
1370
180k
        if (set_update_internal(so, other))
1371
0
            return NULL;
1372
180k
    }
1373
180k
    Py_RETURN_NONE;
1374
180k
}
1375
1376
/* XXX Todo:
1377
   If aligned memory allocations become available, make the
1378
   set object 64 byte aligned so that most of the fields
1379
   can be retrieved or updated in a single cache line.
1380
*/
1381
1382
// Build a set/frozenset left GC-untracked; the caller must _PyObject_GC_TRACK()
1383
// it once fully built, so a half-built set is never exposed during filling.
1384
static PyObject *
1385
make_new_set_untracked(PyTypeObject *type, PyObject *iterable)
1386
12.9M
{
1387
12.9M
    assert(PyType_Check(type));
1388
1389
    // fields are zero-initialized by _PyType_AllocNoTrack
1390
12.9M
    PySetObject *so = (PySetObject *)_PyType_AllocNoTrack(type, 0);
1391
12.9M
    if (so == NULL) {
1392
0
        return NULL;
1393
0
    }
1394
1395
12.9M
    assert(so->fill == 0);
1396
12.9M
    assert(so->used == 0);
1397
12.9M
    so->mask = PySet_MINSIZE - 1;
1398
12.9M
    so->table = so->smalltable;
1399
12.9M
    so->hash = -1;
1400
12.9M
    assert(so->finger == 0);
1401
12.9M
    assert(so->weakreflist == NULL);
1402
1403
12.9M
    if (iterable != NULL) {
1404
160k
        if (set_update_local(so, iterable)) {
1405
0
            Py_DECREF(so);
1406
0
            return NULL;
1407
0
        }
1408
160k
    }
1409
1410
12.9M
    return (PyObject *)so;
1411
12.9M
}
1412
1413
static PyObject *
1414
make_new_set(PyTypeObject *type, PyObject *iterable)
1415
12.9M
{
1416
12.9M
    PyObject *so = make_new_set_untracked(type, iterable);
1417
12.9M
    if (so != NULL) {
1418
12.9M
        _PyObject_GC_TRACK(so);
1419
12.9M
    }
1420
12.9M
    return so;
1421
12.9M
}
1422
1423
static PyObject *
1424
make_new_set_basetype_untracked(PyTypeObject *type, PyObject *iterable)
1425
1.25k
{
1426
1.25k
    if (type != &PySet_Type && type != &PyFrozenSet_Type) {
1427
0
        if (PyType_IsSubtype(type, &PySet_Type))
1428
0
            type = &PySet_Type;
1429
0
        else
1430
0
            type = &PyFrozenSet_Type;
1431
0
    }
1432
1.25k
    return make_new_set_untracked(type, iterable);
1433
1.25k
}
1434
1435
static PyObject *
1436
make_new_set_basetype(PyTypeObject *type, PyObject *iterable)
1437
0
{
1438
0
    PyObject *so = make_new_set_basetype_untracked(type, iterable);
1439
0
    if (so != NULL) {
1440
0
        _PyObject_GC_TRACK(so);
1441
0
    }
1442
0
    return so;
1443
0
}
1444
1445
// gh-140232: check whether a frozenset can be untracked from the GC
1446
static void
1447
_PyFrozenSet_MaybeUntrack(PyObject *op)
1448
122k
{
1449
122k
    assert(op != NULL);
1450
    // subclasses of a frozenset can generate reference cycles, so do not untrack
1451
122k
    if (!PyFrozenSet_CheckExact(op)) {
1452
0
        return;
1453
0
    }
1454
    // if no elements of a frozenset are tracked by the GC, we untrack the object
1455
122k
    Py_ssize_t pos = 0;
1456
122k
    setentry *entry;
1457
147k
    while (set_next((PySetObject *)op, &pos, &entry)) {
1458
58.8k
        if (_PyObject_GC_MAY_BE_TRACKED(entry->key)) {
1459
34.5k
            return;
1460
34.5k
        }
1461
58.8k
    }
1462
88.2k
    _PyObject_GC_UNTRACK(op);
1463
88.2k
}
1464
1465
static PyObject *
1466
make_new_frozenset(PyTypeObject *type, PyObject *iterable)
1467
118k
{
1468
118k
    if (type != &PyFrozenSet_Type) {
1469
0
        return make_new_set(type, iterable);
1470
0
    }
1471
1472
118k
    if (iterable != NULL && PyFrozenSet_CheckExact(iterable)) {
1473
        /* frozenset(f) is idempotent */
1474
0
        return Py_NewRef(iterable);
1475
0
    }
1476
118k
    PyObject *obj = make_new_set(type, iterable);
1477
118k
    if (obj != NULL) {
1478
118k
        _PyFrozenSet_MaybeUntrack(obj);
1479
118k
    }
1480
118k
    return obj;
1481
118k
}
1482
1483
static PyObject *
1484
frozenset_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1485
0
{
1486
0
    PyObject *iterable = NULL;
1487
1488
0
    if ((type == &PyFrozenSet_Type ||
1489
0
         type->tp_init == PyFrozenSet_Type.tp_init) &&
1490
0
        !_PyArg_NoKeywords("frozenset", kwds)) {
1491
0
        return NULL;
1492
0
    }
1493
1494
0
    if (!PyArg_UnpackTuple(args, type->tp_name, 0, 1, &iterable)) {
1495
0
        return NULL;
1496
0
    }
1497
1498
0
    return make_new_frozenset(type, iterable);
1499
0
}
1500
1501
static PyObject *
1502
frozenset_vectorcall(PyObject *type, PyObject * const*args,
1503
                     size_t nargsf, PyObject *kwnames)
1504
118k
{
1505
118k
    if (!_PyArg_NoKwnames("frozenset", kwnames)) {
1506
0
        return NULL;
1507
0
    }
1508
1509
118k
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
1510
118k
    if (!_PyArg_CheckPositional("frozenset", nargs, 0, 1)) {
1511
0
        return NULL;
1512
0
    }
1513
1514
118k
    PyObject *iterable = (nargs ? args[0] : NULL);
1515
118k
    return make_new_frozenset(_PyType_CAST(type), iterable);
1516
118k
}
1517
1518
static PyObject *
1519
set_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1520
0
{
1521
0
    return make_new_set(type, NULL);
1522
0
}
1523
1524
#ifdef Py_GIL_DISABLED
1525
static void
1526
copy_small_table(setentry *dest, setentry *src)
1527
{
1528
    for (Py_ssize_t i = 0; i < PySet_MINSIZE; i++) {
1529
        _Py_atomic_store_ptr_release(&dest[i].key, src[i].key);
1530
        _Py_atomic_store_ssize_relaxed(&dest[i].hash, src[i].hash);
1531
    }
1532
}
1533
#endif
1534
1535
/* set_swap_bodies() switches the contents of any two sets by moving their
1536
   internal data pointers and, if needed, copying the internal smalltables.
1537
   Semantically equivalent to:
1538
1539
     t=set(a); a.clear(); a.update(b); b.clear(); b.update(t); del t
1540
1541
   The function always succeeds and it leaves both objects in a stable state.
1542
   Useful for operations that update in-place (by allowing an intermediate
1543
   result to be swapped into one of the original inputs).
1544
*/
1545
1546
static void
1547
set_swap_bodies(PySetObject *a, PySetObject *b)
1548
{
1549
    Py_ssize_t t;
1550
    setentry *u;
1551
    setentry tab[PySet_MINSIZE];
1552
    Py_hash_t h;
1553
1554
    setentry *a_table = a->table;
1555
    setentry *b_table = b->table;
1556
    FT_ATOMIC_STORE_PTR_RELEASE(a->table, NULL);
1557
    FT_ATOMIC_STORE_PTR_RELEASE(b->table, NULL);
1558
1559
    t = a->fill;     a->fill   = b->fill;        b->fill  = t;
1560
    t = a->used;
1561
    FT_ATOMIC_STORE_SSIZE_RELAXED(a->used, b->used);
1562
    FT_ATOMIC_STORE_SSIZE_RELAXED(b->used, t);
1563
    t = a->mask;
1564
    FT_ATOMIC_STORE_SSIZE_RELEASE(a->mask, b->mask);
1565
    FT_ATOMIC_STORE_SSIZE_RELEASE(b->mask, t);
1566
1567
    u = a_table;
1568
    if (a_table == a->smalltable)
1569
        u = b->smalltable;
1570
    a_table  = b_table;
1571
    if (b_table == b->smalltable)
1572
        a_table = a->smalltable;
1573
    b_table = u;
1574
1575
    if (a_table == a->smalltable || b_table == b->smalltable) {
1576
        memcpy(tab, a->smalltable, sizeof(tab));
1577
#ifndef Py_GIL_DISABLED
1578
        memcpy(a->smalltable, b->smalltable, sizeof(tab));
1579
        memcpy(b->smalltable, tab, sizeof(tab));
1580
#else
1581
        copy_small_table(a->smalltable, b->smalltable);
1582
        copy_small_table(b->smalltable, tab);
1583
#endif
1584
    }
1585
1586
    if (PyType_IsSubtype(Py_TYPE(a), &PyFrozenSet_Type)  &&
1587
        PyType_IsSubtype(Py_TYPE(b), &PyFrozenSet_Type)) {
1588
        h = FT_ATOMIC_LOAD_SSIZE_RELAXED(a->hash);
1589
        FT_ATOMIC_STORE_SSIZE_RELAXED(a->hash, FT_ATOMIC_LOAD_SSIZE_RELAXED(b->hash));
1590
        FT_ATOMIC_STORE_SSIZE_RELAXED(b->hash, h);
1591
    } else {
1592
        FT_ATOMIC_STORE_SSIZE_RELAXED(a->hash, -1);
1593
        FT_ATOMIC_STORE_SSIZE_RELAXED(b->hash, -1);
1594
    }
1595
    if (!SET_IS_SHARED(b) && SET_IS_SHARED(a)) {
1596
        SET_MARK_SHARED(b);
1597
    }
1598
    if (!SET_IS_SHARED(a) && SET_IS_SHARED(b)) {
1599
        SET_MARK_SHARED(a);
1600
    }
1601
    FT_ATOMIC_STORE_PTR_RELEASE(a->table, a_table);
1602
    FT_ATOMIC_STORE_PTR_RELEASE(b->table, b_table);
1603
}
1604
1605
PyObject *
1606
_PySet_Freeze(PyObject *set)
1607
157
{
1608
157
    assert(set != NULL);
1609
157
    assert(PySet_CheckExact(set));
1610
157
    assert(_PyObject_IsUniquelyReferenced(set));
1611
157
    set->ob_type = &PyFrozenSet_Type;
1612
157
    _PyFrozenSet_MaybeUntrack(set);
1613
157
    return Py_NewRef(set);
1614
157
}
1615
1616
static PyObject *
1617
set_copy_untracked_lock_held(PySetObject *so)
1618
965
{
1619
965
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so);
1620
965
    PyObject *copy = make_new_set_basetype_untracked(Py_TYPE(so), NULL);
1621
965
    if (copy == NULL) {
1622
0
        return NULL;
1623
0
    }
1624
965
    if (set_merge_lock_held((PySetObject *)copy, (PyObject *)so) < 0) {
1625
0
        Py_DECREF(copy);
1626
0
        return NULL;
1627
0
    }
1628
965
    return copy;
1629
965
}
1630
1631
/*[clinic input]
1632
@critical_section
1633
set.copy
1634
    so: setobject
1635
1636
Return a shallow copy of a set.
1637
[clinic start generated code]*/
1638
1639
static PyObject *
1640
set_copy_impl(PySetObject *so)
1641
/*[clinic end generated code: output=c9223a1e1cc6b041 input=c169a4fbb8209257]*/
1642
943
{
1643
943
    PyObject *copy = set_copy_untracked_lock_held(so);
1644
943
    if (copy != NULL) {
1645
943
        _PyObject_GC_TRACK(copy);
1646
943
    }
1647
943
    return copy;
1648
943
}
1649
1650
/*[clinic input]
1651
@critical_section
1652
frozenset.copy
1653
    so: setobject
1654
1655
Return a shallow copy of a set.
1656
[clinic start generated code]*/
1657
1658
static PyObject *
1659
frozenset_copy_impl(PySetObject *so)
1660
/*[clinic end generated code: output=b356263526af9e70 input=fbf5bef131268dd7]*/
1661
0
{
1662
0
    if (PyFrozenSet_CheckExact(so)) {
1663
0
        return Py_NewRef(so);
1664
0
    }
1665
0
    return set_copy_impl(so);
1666
0
}
1667
1668
/*[clinic input]
1669
@critical_section
1670
set.clear
1671
    so: setobject
1672
1673
Remove all elements from this set.
1674
[clinic start generated code]*/
1675
1676
static PyObject *
1677
set_clear_impl(PySetObject *so)
1678
/*[clinic end generated code: output=4e71d5a83904161a input=c6f831b366111950]*/
1679
319k
{
1680
319k
    set_clear_internal((PyObject*)so);
1681
319k
    Py_RETURN_NONE;
1682
319k
}
1683
1684
/*[clinic input]
1685
set.union
1686
    so: setobject
1687
    *others: array
1688
1689
Return a new set with elements from the set and all others.
1690
[clinic start generated code]*/
1691
1692
static PyObject *
1693
set_union_impl(PySetObject *so, PyObject * const *others,
1694
               Py_ssize_t others_length)
1695
/*[clinic end generated code: output=b1bfa3d74065f27e input=55a2e81db6347a4f]*/
1696
4
{
1697
4
    PySetObject *result;
1698
4
    PyObject *other;
1699
4
    Py_ssize_t i;
1700
1701
4
    result = (PySetObject *)make_new_set_basetype_untracked(Py_TYPE(so),
1702
4
                                                            (PyObject *)so);
1703
4
    if (result == NULL)
1704
0
        return NULL;
1705
1706
8
    for (i = 0; i < others_length; i++) {
1707
4
        other = others[i];
1708
4
        if ((PyObject *)so == other)
1709
0
            continue;
1710
4
        if (set_update_local(result, other)) {
1711
0
            Py_DECREF(result);
1712
0
            return NULL;
1713
0
        }
1714
4
    }
1715
4
    _PyObject_GC_TRACK(result);
1716
4
    return (PyObject *)result;
1717
4
}
1718
1719
static PyObject *
1720
set_or(PyObject *self, PyObject *other)
1721
60
{
1722
60
    PySetObject *result;
1723
1724
60
    if (!PyAnySet_Check(self) || !PyAnySet_Check(other))
1725
0
        Py_RETURN_NOTIMPLEMENTED;
1726
1727
60
    result = (PySetObject *)set_copy(self, NULL);
1728
60
    if (result == NULL) {
1729
0
        return NULL;
1730
0
    }
1731
60
    if (Py_Is(self, other)) {
1732
0
        return (PyObject *)result;
1733
0
    }
1734
60
    if (set_update_local(result, other)) {
1735
0
        Py_DECREF(result);
1736
0
        return NULL;
1737
0
    }
1738
60
    return (PyObject *)result;
1739
60
}
1740
1741
static PyObject *
1742
set_ior(PyObject *self, PyObject *other)
1743
27.9k
{
1744
27.9k
    if (!PyAnySet_Check(other))
1745
0
        Py_RETURN_NOTIMPLEMENTED;
1746
27.9k
    PySetObject *so = _PySet_CAST(self);
1747
1748
27.9k
    if (set_update_internal(so, other)) {
1749
0
        return NULL;
1750
0
    }
1751
27.9k
    return Py_NewRef(so);
1752
27.9k
}
1753
1754
static PyObject *
1755
set_intersection(PySetObject *so, PyObject *other)
1756
284
{
1757
284
    PySetObject *result;
1758
284
    PyObject *key, *it, *tmp;
1759
284
    Py_hash_t hash;
1760
284
    int rv;
1761
1762
284
    if ((PyObject *)so == other)
1763
0
        return set_copy_impl(so);
1764
1765
284
    result = (PySetObject *)make_new_set_basetype_untracked(Py_TYPE(so), NULL);
1766
284
    if (result == NULL)
1767
0
        return NULL;
1768
1769
284
    if (PyAnySet_Check(other)) {
1770
272
        Py_ssize_t pos = 0;
1771
272
        setentry *entry;
1772
1773
272
        if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) {
1774
175
            tmp = (PyObject *)so;
1775
175
            so = (PySetObject *)other;
1776
175
            other = tmp;
1777
175
        }
1778
1779
473
        while (set_next((PySetObject *)other, &pos, &entry)) {
1780
201
            key = entry->key;
1781
201
            hash = entry->hash;
1782
201
            Py_INCREF(key);
1783
201
            rv = set_contains_entry(so, key, hash);
1784
201
            if (rv < 0) {
1785
0
                Py_DECREF(result);
1786
0
                Py_DECREF(key);
1787
0
                return NULL;
1788
0
            }
1789
201
            if (rv) {
1790
0
                if (set_add_entry(result, key, hash)) {
1791
0
                    Py_DECREF(result);
1792
0
                    Py_DECREF(key);
1793
0
                    return NULL;
1794
0
                }
1795
0
            }
1796
201
            Py_DECREF(key);
1797
201
        }
1798
272
        _PyObject_GC_TRACK(result);
1799
272
        return (PyObject *)result;
1800
272
    }
1801
1802
12
    it = PyObject_GetIter(other);
1803
12
    if (it == NULL) {
1804
0
        Py_DECREF(result);
1805
0
        return NULL;
1806
0
    }
1807
1808
124
    while ((key = PyIter_Next(it)) != NULL) {
1809
116
        hash = PyObject_Hash(key);
1810
116
        if (hash == -1)
1811
0
            goto error;
1812
116
        rv = set_contains_entry(so, key, hash);
1813
116
        if (rv < 0)
1814
0
            goto error;
1815
116
        if (rv) {
1816
116
            if (set_add_entry(result, key, hash))
1817
0
                goto error;
1818
116
            if (PySet_GET_SIZE(result) >= PySet_GET_SIZE(so)) {
1819
4
                Py_DECREF(key);
1820
4
                break;
1821
4
            }
1822
116
        }
1823
112
        Py_DECREF(key);
1824
112
    }
1825
12
    Py_DECREF(it);
1826
12
    if (PyErr_Occurred()) {
1827
0
        Py_DECREF(result);
1828
0
        return NULL;
1829
0
    }
1830
12
    _PyObject_GC_TRACK(result);
1831
12
    return (PyObject *)result;
1832
0
  error:
1833
0
    Py_DECREF(it);
1834
0
    Py_DECREF(result);
1835
0
    Py_DECREF(key);
1836
0
    return NULL;
1837
12
}
1838
1839
/*[clinic input]
1840
set.intersection as set_intersection_multi
1841
    so: setobject
1842
    *others: array
1843
1844
Return a new set with elements common to the set and all others.
1845
[clinic start generated code]*/
1846
1847
static PyObject *
1848
set_intersection_multi_impl(PySetObject *so, PyObject * const *others,
1849
                            Py_ssize_t others_length)
1850
/*[clinic end generated code: output=db9ff9f875132b6b input=36c7b615694cadae]*/
1851
8
{
1852
8
    Py_ssize_t i;
1853
1854
8
    if (others_length == 0) {
1855
0
        return set_copy((PyObject *)so, NULL);
1856
0
    }
1857
1858
8
    PyObject *result = Py_NewRef(so);
1859
16
    for (i = 0; i < others_length; i++) {
1860
8
        PyObject *other = others[i];
1861
8
        PyObject *newresult;
1862
8
        Py_BEGIN_CRITICAL_SECTION2(result, other);
1863
8
        newresult = set_intersection((PySetObject *)result, other);
1864
8
        Py_END_CRITICAL_SECTION2();
1865
8
        if (newresult == NULL) {
1866
0
            Py_DECREF(result);
1867
0
            return NULL;
1868
0
        }
1869
8
        Py_SETREF(result, newresult);
1870
8
    }
1871
8
    return result;
1872
8
}
1873
1874
static PyObject *
1875
set_intersection_update(PySetObject *so, PyObject *other)
1876
0
{
1877
0
    PyObject *tmp;
1878
1879
0
    tmp = set_intersection(so, other);
1880
0
    if (tmp == NULL)
1881
0
        return NULL;
1882
0
    set_swap_bodies(so, (PySetObject *)tmp);
1883
0
    Py_DECREF(tmp);
1884
0
    Py_RETURN_NONE;
1885
0
}
1886
1887
/*[clinic input]
1888
set.intersection_update as set_intersection_update_multi
1889
    so: setobject
1890
    *others: array
1891
1892
Update the set, keeping only elements found in it and all others.
1893
[clinic start generated code]*/
1894
1895
static PyObject *
1896
set_intersection_update_multi_impl(PySetObject *so, PyObject * const *others,
1897
                                   Py_ssize_t others_length)
1898
/*[clinic end generated code: output=d768b5584675b48d input=782e422fc370e4fc]*/
1899
0
{
1900
0
    PyObject *tmp;
1901
1902
0
    tmp = set_intersection_multi_impl(so, others, others_length);
1903
0
    if (tmp == NULL)
1904
0
        return NULL;
1905
0
    Py_BEGIN_CRITICAL_SECTION(so);
1906
0
    set_swap_bodies(so, (PySetObject *)tmp);
1907
0
    Py_END_CRITICAL_SECTION();
1908
0
    Py_DECREF(tmp);
1909
0
    Py_RETURN_NONE;
1910
0
}
1911
1912
static PyObject *
1913
set_and(PyObject *self, PyObject *other)
1914
272
{
1915
272
    if (!PyAnySet_Check(self) || !PyAnySet_Check(other))
1916
0
        Py_RETURN_NOTIMPLEMENTED;
1917
272
    PySetObject *so = _PySet_CAST(self);
1918
1919
272
    PyObject *rv;
1920
272
    Py_BEGIN_CRITICAL_SECTION2(so, other);
1921
272
    rv = set_intersection(so, other);
1922
272
    Py_END_CRITICAL_SECTION2();
1923
1924
272
    return rv;
1925
272
}
1926
1927
static PyObject *
1928
set_iand(PyObject *self, PyObject *other)
1929
0
{
1930
0
    PyObject *result;
1931
1932
0
    if (!PyAnySet_Check(other))
1933
0
        Py_RETURN_NOTIMPLEMENTED;
1934
0
    PySetObject *so = _PySet_CAST(self);
1935
1936
0
    Py_BEGIN_CRITICAL_SECTION2(so, other);
1937
0
    result = set_intersection_update(so, other);
1938
0
    Py_END_CRITICAL_SECTION2();
1939
1940
0
    if (result == NULL)
1941
0
        return NULL;
1942
0
    Py_DECREF(result);
1943
0
    return Py_NewRef(so);
1944
0
}
1945
1946
/*[clinic input]
1947
@critical_section so other
1948
set.isdisjoint
1949
    so: setobject
1950
    other: object
1951
    /
1952
1953
Return True if two sets have a null intersection.
1954
[clinic start generated code]*/
1955
1956
static PyObject *
1957
set_isdisjoint_impl(PySetObject *so, PyObject *other)
1958
/*[clinic end generated code: output=273493f2d57c565e input=32f8dcab5e0fc7d6]*/
1959
233k
{
1960
233k
    PyObject *key, *it, *tmp;
1961
233k
    int rv;
1962
1963
233k
    if ((PyObject *)so == other) {
1964
0
        if (PySet_GET_SIZE(so) == 0)
1965
0
            Py_RETURN_TRUE;
1966
0
        else
1967
0
            Py_RETURN_FALSE;
1968
0
    }
1969
1970
233k
    if (PyAnySet_CheckExact(other)) {
1971
36
        Py_ssize_t pos = 0;
1972
36
        setentry *entry;
1973
1974
36
        if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) {
1975
4
            tmp = (PyObject *)so;
1976
4
            so = (PySetObject *)other;
1977
4
            other = tmp;
1978
4
        }
1979
36
        while (set_next((PySetObject *)other, &pos, &entry)) {
1980
0
            PyObject *key = entry->key;
1981
0
            Py_INCREF(key);
1982
0
            rv = set_contains_entry(so, key, entry->hash);
1983
0
            Py_DECREF(key);
1984
0
            if (rv < 0) {
1985
0
                return NULL;
1986
0
            }
1987
0
            if (rv) {
1988
0
                Py_RETURN_FALSE;
1989
0
            }
1990
0
        }
1991
36
        Py_RETURN_TRUE;
1992
36
    }
1993
1994
233k
    it = PyObject_GetIter(other);
1995
233k
    if (it == NULL)
1996
0
        return NULL;
1997
1998
19.0M
    while ((key = PyIter_Next(it)) != NULL) {
1999
18.7M
        rv = set_contains_key(so, key);
2000
18.7M
        Py_DECREF(key);
2001
18.7M
        if (rv < 0) {
2002
0
            Py_DECREF(it);
2003
0
            return NULL;
2004
0
        }
2005
18.7M
        if (rv) {
2006
17.0k
            Py_DECREF(it);
2007
17.0k
            Py_RETURN_FALSE;
2008
17.0k
        }
2009
18.7M
    }
2010
216k
    Py_DECREF(it);
2011
216k
    if (PyErr_Occurred())
2012
0
        return NULL;
2013
216k
    Py_RETURN_TRUE;
2014
216k
}
2015
2016
static int
2017
set_difference_update_internal(PySetObject *so, PyObject *other)
2018
78
{
2019
78
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so);
2020
78
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(other);
2021
2022
78
    if ((PyObject *)so == other)
2023
0
        return set_clear_internal((PyObject*)so);
2024
2025
78
    if (PyAnySet_Check(other)) {
2026
78
        setentry *entry;
2027
78
        Py_ssize_t pos = 0;
2028
2029
        /* Optimization:  When the other set is more than 8 times
2030
           larger than the base set, replace the other set with
2031
           intersection of the two sets.
2032
        */
2033
78
        if ((PySet_GET_SIZE(other) >> 3) > PySet_GET_SIZE(so)) {
2034
0
            other = set_intersection(so, other);
2035
0
            if (other == NULL)
2036
0
                return -1;
2037
78
        } else {
2038
78
            Py_INCREF(other);
2039
78
        }
2040
2041
118
        while (set_next((PySetObject *)other, &pos, &entry)) {
2042
40
            PyObject *key = entry->key;
2043
40
            Py_INCREF(key);
2044
40
            if (set_discard_entry(so, key, entry->hash) < 0) {
2045
0
                Py_DECREF(other);
2046
0
                Py_DECREF(key);
2047
0
                return -1;
2048
0
            }
2049
40
            Py_DECREF(key);
2050
40
        }
2051
2052
78
        Py_DECREF(other);
2053
78
    } else {
2054
0
        PyObject *key, *it;
2055
0
        it = PyObject_GetIter(other);
2056
0
        if (it == NULL)
2057
0
            return -1;
2058
2059
0
        while ((key = PyIter_Next(it)) != NULL) {
2060
0
            if (set_discard_key(so, key) < 0) {
2061
0
                Py_DECREF(it);
2062
0
                Py_DECREF(key);
2063
0
                return -1;
2064
0
            }
2065
0
            Py_DECREF(key);
2066
0
        }
2067
0
        Py_DECREF(it);
2068
0
        if (PyErr_Occurred())
2069
0
            return -1;
2070
0
    }
2071
    /* If more than 1/4th are dummies, then resize them away. */
2072
78
    if ((size_t)(so->fill - so->used) <= (size_t)so->mask / 4)
2073
78
        return 0;
2074
0
    return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
2075
78
}
2076
2077
/*[clinic input]
2078
set.difference_update
2079
    so: setobject
2080
    *others: array
2081
2082
Update the set, removing elements found in others.
2083
[clinic start generated code]*/
2084
2085
static PyObject *
2086
set_difference_update_impl(PySetObject *so, PyObject * const *others,
2087
                           Py_ssize_t others_length)
2088
/*[clinic end generated code: output=04a22179b322cfe6 input=93ac28ba5b233696]*/
2089
0
{
2090
0
    Py_ssize_t i;
2091
2092
0
    for (i = 0; i < others_length; i++) {
2093
0
        PyObject *other = others[i];
2094
0
        int rv;
2095
0
        Py_BEGIN_CRITICAL_SECTION2(so, other);
2096
0
        rv = set_difference_update_internal(so, other);
2097
0
        Py_END_CRITICAL_SECTION2();
2098
0
        if (rv) {
2099
0
            return NULL;
2100
0
        }
2101
0
    }
2102
0
    Py_RETURN_NONE;
2103
0
}
2104
2105
static PyObject *
2106
set_copy_and_difference_untracked(PySetObject *so, PyObject *other)
2107
22
{
2108
22
    PyObject *result;
2109
2110
22
    result = set_copy_untracked_lock_held(so);
2111
22
    if (result == NULL)
2112
0
        return NULL;
2113
22
    if (set_difference_update_internal((PySetObject *) result, other) == 0)
2114
22
        return result;
2115
0
    Py_DECREF(result);
2116
0
    return NULL;
2117
22
}
2118
2119
static PyObject *
2120
set_difference_untracked(PySetObject *so, PyObject *other)
2121
24
{
2122
24
    PyObject *result;
2123
24
    PyObject *key;
2124
24
    Py_hash_t hash;
2125
24
    setentry *entry;
2126
24
    Py_ssize_t pos = 0, other_size;
2127
24
    int rv;
2128
2129
24
    if (PyAnySet_Check(other)) {
2130
24
        other_size = PySet_GET_SIZE(other);
2131
24
    }
2132
0
    else if (PyAnyDict_CheckExact(other)) {
2133
0
        other_size = PyDict_GET_SIZE(other);
2134
0
    }
2135
0
    else {
2136
0
        return set_copy_and_difference_untracked(so, other);
2137
0
    }
2138
2139
    /* If len(so) much more than len(other), it's more efficient to simply copy
2140
     * so and then iterate other looking for common elements. */
2141
24
    if ((PySet_GET_SIZE(so) >> 2) > other_size) {
2142
22
        return set_copy_and_difference_untracked(so, other);
2143
22
    }
2144
2145
2
    result = make_new_set_basetype_untracked(Py_TYPE(so), NULL);
2146
2
    if (result == NULL)
2147
0
        return NULL;
2148
2149
2
    if (PyAnyDict_CheckExact(other)) {
2150
0
        while (set_next(so, &pos, &entry)) {
2151
0
            key = entry->key;
2152
0
            hash = entry->hash;
2153
0
            Py_INCREF(key);
2154
0
            rv = _PyDict_Contains_KnownHash(other, key, hash);
2155
0
            if (rv < 0) {
2156
0
                Py_DECREF(result);
2157
0
                Py_DECREF(key);
2158
0
                return NULL;
2159
0
            }
2160
0
            if (!rv) {
2161
0
                if (set_add_entry((PySetObject *)result, key, hash)) {
2162
0
                    Py_DECREF(result);
2163
0
                    Py_DECREF(key);
2164
0
                    return NULL;
2165
0
                }
2166
0
            }
2167
0
            Py_DECREF(key);
2168
0
        }
2169
0
        return result;
2170
0
    }
2171
2172
    /* Iterate over so, checking for common elements in other. */
2173
28
    while (set_next(so, &pos, &entry)) {
2174
26
        key = entry->key;
2175
26
        hash = entry->hash;
2176
26
        Py_INCREF(key);
2177
26
        rv = set_contains_entry((PySetObject *)other, key, hash);
2178
26
        if (rv < 0) {
2179
0
            Py_DECREF(result);
2180
0
            Py_DECREF(key);
2181
0
            return NULL;
2182
0
        }
2183
26
        if (!rv) {
2184
20
            if (set_add_entry((PySetObject *)result, key, hash)) {
2185
0
                Py_DECREF(result);
2186
0
                Py_DECREF(key);
2187
0
                return NULL;
2188
0
            }
2189
20
        }
2190
26
        Py_DECREF(key);
2191
26
    }
2192
2
    return result;
2193
2
}
2194
2195
/*[clinic input]
2196
@permit_long_summary
2197
set.difference as set_difference_multi
2198
    so: setobject
2199
    *others: array
2200
2201
Return a new set with elements in the set that are not in the others.
2202
[clinic start generated code]*/
2203
2204
static PyObject *
2205
set_difference_multi_impl(PySetObject *so, PyObject * const *others,
2206
                          Py_ssize_t others_length)
2207
/*[clinic end generated code: output=b0d33fb05d5477a7 input=e0fbedbf79d91d4e]*/
2208
0
{
2209
0
    Py_ssize_t i;
2210
0
    PyObject *result, *other;
2211
2212
0
    if (others_length == 0) {
2213
0
        return set_copy((PyObject *)so, NULL);
2214
0
    }
2215
2216
0
    other = others[0];
2217
0
    Py_BEGIN_CRITICAL_SECTION2(so, other);
2218
0
    result = set_difference_untracked(so, other);
2219
0
    Py_END_CRITICAL_SECTION2();
2220
0
    if (result == NULL)
2221
0
        return NULL;
2222
2223
0
    for (i = 1; i < others_length; i++) {
2224
0
        other = others[i];
2225
0
        int rv;
2226
0
        Py_BEGIN_CRITICAL_SECTION(other);
2227
0
        rv = set_difference_update_internal((PySetObject *)result, other);
2228
0
        Py_END_CRITICAL_SECTION();
2229
0
        if (rv) {
2230
0
            Py_DECREF(result);
2231
0
            return NULL;
2232
0
        }
2233
0
    }
2234
0
    _PyObject_GC_TRACK(result);
2235
0
    return result;
2236
0
}
2237
2238
static PyObject *
2239
set_sub(PyObject *self, PyObject *other)
2240
24
{
2241
24
    if (!PyAnySet_Check(self) || !PyAnySet_Check(other))
2242
0
        Py_RETURN_NOTIMPLEMENTED;
2243
24
    PySetObject *so = _PySet_CAST(self);
2244
2245
24
    PyObject *rv;
2246
24
    Py_BEGIN_CRITICAL_SECTION2(so, other);
2247
24
    rv = set_difference_untracked(so, other);
2248
24
    Py_END_CRITICAL_SECTION2();
2249
24
    if (rv != NULL) {
2250
24
        _PyObject_GC_TRACK(rv);
2251
24
    }
2252
24
    return rv;
2253
24
}
2254
2255
static PyObject *
2256
set_isub(PyObject *self, PyObject *other)
2257
56
{
2258
56
    if (!PyAnySet_Check(other))
2259
0
        Py_RETURN_NOTIMPLEMENTED;
2260
56
    PySetObject *so = _PySet_CAST(self);
2261
2262
56
    int rv;
2263
56
    Py_BEGIN_CRITICAL_SECTION2(so, other);
2264
56
    rv = set_difference_update_internal(so, other);
2265
56
    Py_END_CRITICAL_SECTION2();
2266
56
    if (rv < 0) {
2267
0
        return NULL;
2268
0
    }
2269
56
    return Py_NewRef(so);
2270
56
}
2271
2272
static int
2273
set_symmetric_difference_update_dict(PySetObject *so, PyObject *other)
2274
0
{
2275
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so);
2276
#ifdef Py_DEBUG
2277
    if (!PyFrozenDict_CheckExact(other)) {
2278
        _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(other);
2279
    }
2280
#endif
2281
2282
0
    Py_ssize_t pos = 0;
2283
0
    PyObject *key, *value;
2284
0
    Py_hash_t hash;
2285
0
    while (_PyDict_Next(other, &pos, &key, &value, &hash)) {
2286
0
        Py_INCREF(key);
2287
0
        int rv = set_discard_entry(so, key, hash);
2288
0
        if (rv < 0) {
2289
0
            Py_DECREF(key);
2290
0
            return -1;
2291
0
        }
2292
0
        if (rv == DISCARD_NOTFOUND) {
2293
0
            if (set_add_entry(so, key, hash)) {
2294
0
                Py_DECREF(key);
2295
0
                return -1;
2296
0
            }
2297
0
        }
2298
0
        Py_DECREF(key);
2299
0
    }
2300
0
    return 0;
2301
0
}
2302
2303
static int
2304
set_symmetric_difference_update_set(PySetObject *so, PySetObject *other)
2305
0
{
2306
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so);
2307
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(other);
2308
2309
0
    Py_ssize_t pos = 0;
2310
0
    setentry *entry;
2311
0
    while (set_next(other, &pos, &entry)) {
2312
0
        PyObject *key = Py_NewRef(entry->key);
2313
0
        Py_hash_t hash = entry->hash;
2314
0
        int rv = set_discard_entry(so, key, hash);
2315
0
        if (rv < 0) {
2316
0
            Py_DECREF(key);
2317
0
            return -1;
2318
0
        }
2319
0
        if (rv == DISCARD_NOTFOUND) {
2320
0
            if (set_add_entry(so, key, hash)) {
2321
0
                Py_DECREF(key);
2322
0
                return -1;
2323
0
            }
2324
0
        }
2325
0
        Py_DECREF(key);
2326
0
    }
2327
0
    return 0;
2328
0
}
2329
2330
/*[clinic input]
2331
@permit_long_summary
2332
set.symmetric_difference_update
2333
    so: setobject
2334
    other: object
2335
    /
2336
2337
Update the set, keeping only elements found in either set, but not in both.
2338
[clinic start generated code]*/
2339
2340
static PyObject *
2341
set_symmetric_difference_update_impl(PySetObject *so, PyObject *other)
2342
/*[clinic end generated code: output=79f80b4ee5da66c1 input=86a3dddac9bfb15e]*/
2343
0
{
2344
0
    if (Py_Is((PyObject *)so, other)) {
2345
0
        return set_clear((PyObject *)so, NULL);
2346
0
    }
2347
2348
0
    int rv;
2349
0
    if (PyDict_CheckExact(other)) {
2350
0
        Py_BEGIN_CRITICAL_SECTION2(so, other);
2351
0
        rv = set_symmetric_difference_update_dict(so, other);
2352
0
        Py_END_CRITICAL_SECTION2();
2353
0
    }
2354
0
    else if (PyFrozenDict_CheckExact(other)) {
2355
0
        Py_BEGIN_CRITICAL_SECTION(so);
2356
0
        rv = set_symmetric_difference_update_dict(so, other);
2357
0
        Py_END_CRITICAL_SECTION();
2358
0
    }
2359
0
    else if (PyAnySet_Check(other)) {
2360
0
        Py_BEGIN_CRITICAL_SECTION2(so, other);
2361
0
        rv = set_symmetric_difference_update_set(so, (PySetObject *)other);
2362
0
        Py_END_CRITICAL_SECTION2();
2363
0
    }
2364
0
    else {
2365
0
        PySetObject *otherset = (PySetObject *)make_new_set_basetype(Py_TYPE(so), other);
2366
0
        if (otherset == NULL) {
2367
0
            return NULL;
2368
0
        }
2369
2370
0
        Py_BEGIN_CRITICAL_SECTION(so);
2371
0
        rv = set_symmetric_difference_update_set(so, otherset);
2372
0
        Py_END_CRITICAL_SECTION();
2373
2374
0
        Py_DECREF(otherset);
2375
0
    }
2376
0
    if (rv < 0) {
2377
0
        return NULL;
2378
0
    }
2379
0
    Py_RETURN_NONE;
2380
0
}
2381
2382
/*[clinic input]
2383
@permit_long_summary
2384
@critical_section so other
2385
set.symmetric_difference
2386
    so: setobject
2387
    other: object
2388
    /
2389
2390
Return a new set with elements in either the set or other but not both.
2391
[clinic start generated code]*/
2392
2393
static PyObject *
2394
set_symmetric_difference_impl(PySetObject *so, PyObject *other)
2395
/*[clinic end generated code: output=270ee0b5d42b0797 input=8c29b0be90d47feb]*/
2396
0
{
2397
0
    PySetObject *result =
2398
0
        (PySetObject *)make_new_set_basetype_untracked(Py_TYPE(so), NULL);
2399
0
    if (result == NULL) {
2400
0
        return NULL;
2401
0
    }
2402
0
    if (set_update_lock_held(result, other) < 0) {
2403
0
        Py_DECREF(result);
2404
0
        return NULL;
2405
0
    }
2406
0
    if (set_symmetric_difference_update_set(result, so) < 0) {
2407
0
        Py_DECREF(result);
2408
0
        return NULL;
2409
0
    }
2410
0
    _PyObject_GC_TRACK(result);
2411
0
    return (PyObject *)result;
2412
0
}
2413
2414
static PyObject *
2415
set_xor(PyObject *self, PyObject *other)
2416
0
{
2417
0
    if (!PyAnySet_Check(self) || !PyAnySet_Check(other))
2418
0
        Py_RETURN_NOTIMPLEMENTED;
2419
0
    PySetObject *so = _PySet_CAST(self);
2420
0
    return set_symmetric_difference((PyObject*)so, other);
2421
0
}
2422
2423
static PyObject *
2424
set_ixor(PyObject *self, PyObject *other)
2425
0
{
2426
0
    PyObject *result;
2427
2428
0
    if (!PyAnySet_Check(other))
2429
0
        Py_RETURN_NOTIMPLEMENTED;
2430
0
    PySetObject *so = _PySet_CAST(self);
2431
2432
0
    result = set_symmetric_difference_update((PyObject*)so, other);
2433
0
    if (result == NULL)
2434
0
        return NULL;
2435
0
    Py_DECREF(result);
2436
0
    return Py_NewRef(so);
2437
0
}
2438
2439
/*[clinic input]
2440
@critical_section so other
2441
set.issubset
2442
    so: setobject
2443
    other: object
2444
    /
2445
2446
Report whether another set contains this set.
2447
[clinic start generated code]*/
2448
2449
static PyObject *
2450
set_issubset_impl(PySetObject *so, PyObject *other)
2451
/*[clinic end generated code: output=b2b59d5f314555ce input=f2a4fd0f2537758b]*/
2452
117k
{
2453
117k
    setentry *entry;
2454
117k
    Py_ssize_t pos = 0;
2455
117k
    int rv;
2456
2457
117k
    if (!PyAnySet_Check(other)) {
2458
4
        PyObject *tmp = set_intersection(so, other);
2459
4
        if (tmp == NULL) {
2460
0
            return NULL;
2461
0
        }
2462
4
        int result = (PySet_GET_SIZE(tmp) == PySet_GET_SIZE(so));
2463
4
        Py_DECREF(tmp);
2464
4
        return PyBool_FromLong(result);
2465
4
    }
2466
117k
    if (PySet_GET_SIZE(so) > PySet_GET_SIZE(other))
2467
0
        Py_RETURN_FALSE;
2468
2469
187k
    while (set_next(so, &pos, &entry)) {
2470
69.5k
        PyObject *key = entry->key;
2471
69.5k
        Py_INCREF(key);
2472
69.5k
        rv = set_contains_entry((PySetObject *)other, key, entry->hash);
2473
69.5k
        Py_DECREF(key);
2474
69.5k
        if (rv < 0) {
2475
0
            return NULL;
2476
0
        }
2477
69.5k
        if (!rv) {
2478
0
            Py_RETURN_FALSE;
2479
0
        }
2480
69.5k
    }
2481
117k
    Py_RETURN_TRUE;
2482
117k
}
2483
2484
/*[clinic input]
2485
@critical_section so other
2486
set.issuperset
2487
    so: setobject
2488
    other: object
2489
    /
2490
2491
Report whether this set contains another set.
2492
[clinic start generated code]*/
2493
2494
static PyObject *
2495
set_issuperset_impl(PySetObject *so, PyObject *other)
2496
/*[clinic end generated code: output=ecf00ce552c09461 input=5f2e1f262e6e4ccc]*/
2497
3.93k
{
2498
3.93k
    if (PyAnySet_Check(other)) {
2499
0
        return set_issubset(other, (PyObject *)so);
2500
0
    }
2501
2502
3.93k
    PyObject *key, *it = PyObject_GetIter(other);
2503
3.93k
    if (it == NULL) {
2504
0
        return NULL;
2505
0
    }
2506
21.1k
    while ((key = PyIter_Next(it)) != NULL) {
2507
17.2k
        int rv = set_contains_key(so, key);
2508
17.2k
        Py_DECREF(key);
2509
17.2k
        if (rv < 0) {
2510
0
            Py_DECREF(it);
2511
0
            return NULL;
2512
0
        }
2513
17.2k
        if (!rv) {
2514
12
            Py_DECREF(it);
2515
12
            Py_RETURN_FALSE;
2516
12
        }
2517
17.2k
    }
2518
3.92k
    Py_DECREF(it);
2519
3.92k
    if (PyErr_Occurred()) {
2520
0
        return NULL;
2521
0
    }
2522
3.92k
    Py_RETURN_TRUE;
2523
3.92k
}
2524
2525
static PyObject *
2526
set_richcompare(PyObject *self, PyObject *w, int op)
2527
117k
{
2528
117k
    PySetObject *v = _PySet_CAST(self);
2529
117k
    PyObject *r1;
2530
117k
    int r2;
2531
2532
117k
    if(!PyAnySet_Check(w))
2533
0
        Py_RETURN_NOTIMPLEMENTED;
2534
2535
117k
    switch (op) {
2536
117k
    case Py_EQ:
2537
117k
        if (PySet_GET_SIZE(v) != PySet_GET_SIZE(w))
2538
116
            Py_RETURN_FALSE;
2539
117k
        Py_hash_t v_hash = FT_ATOMIC_LOAD_SSIZE_RELAXED(v->hash);
2540
117k
        Py_hash_t w_hash = FT_ATOMIC_LOAD_SSIZE_RELAXED(((PySetObject *)w)->hash);
2541
117k
        if (v_hash != -1 && w_hash != -1 && v_hash != w_hash)
2542
0
            Py_RETURN_FALSE;
2543
117k
        return set_issubset((PyObject*)v, w);
2544
0
    case Py_NE:
2545
0
        r1 = set_richcompare((PyObject*)v, w, Py_EQ);
2546
0
        if (r1 == NULL)
2547
0
            return NULL;
2548
0
        r2 = PyObject_IsTrue(r1);
2549
0
        Py_DECREF(r1);
2550
0
        if (r2 < 0)
2551
0
            return NULL;
2552
0
        return PyBool_FromLong(!r2);
2553
146
    case Py_LE:
2554
146
        return set_issubset((PyObject*)v, w);
2555
0
    case Py_GE:
2556
0
        return set_issuperset((PyObject*)v, w);
2557
0
    case Py_LT:
2558
0
        if (PySet_GET_SIZE(v) >= PySet_GET_SIZE(w))
2559
0
            Py_RETURN_FALSE;
2560
0
        return set_issubset((PyObject*)v, w);
2561
0
    case Py_GT:
2562
0
        if (PySet_GET_SIZE(v) <= PySet_GET_SIZE(w))
2563
0
            Py_RETURN_FALSE;
2564
0
        return set_issuperset((PyObject*)v, w);
2565
117k
    }
2566
117k
    Py_RETURN_NOTIMPLEMENTED;
2567
117k
}
2568
2569
/*[clinic input]
2570
@critical_section
2571
set.add
2572
    so: setobject
2573
    object as key: object
2574
    /
2575
2576
Add an element to a set.
2577
2578
This has no effect if the element is already present.
2579
[clinic start generated code]*/
2580
2581
static PyObject *
2582
set_add_impl(PySetObject *so, PyObject *key)
2583
/*[clinic end generated code: output=4cc4a937f1425c96 input=03baf62cb0e66514]*/
2584
23.1M
{
2585
23.1M
    if (set_add_key(so, key))
2586
0
        return NULL;
2587
23.1M
    Py_RETURN_NONE;
2588
23.1M
}
2589
2590
int
2591
_PySet_Contains(PySetObject *so, PyObject *key)
2592
294M
{
2593
294M
    assert(so);
2594
2595
294M
    Py_hash_t hash = PyObject_Hash(key);
2596
294M
    if (hash == -1) {
2597
0
        if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) {
2598
0
            set_unhashable_type(key);
2599
0
            return -1;
2600
0
        }
2601
0
        PyErr_Clear();
2602
        // Note that 'key' could be a set() or frozenset() object.  Unlike most
2603
        // container types, set allows membership testing with a set key, even
2604
        // though it is not hashable.
2605
0
        Py_BEGIN_CRITICAL_SECTION(key);
2606
0
        hash = frozenset_hash_impl(key);
2607
0
        Py_END_CRITICAL_SECTION();
2608
0
    }
2609
294M
    return set_contains_entry(so, key, hash);
2610
294M
}
2611
2612
static int
2613
set_contains(PyObject *self, PyObject *key)
2614
960
{
2615
960
    PySetObject *so = _PySet_CAST(self);
2616
960
    return _PySet_Contains(so, key);
2617
960
}
2618
2619
/*[clinic input]
2620
@coexist
2621
set.__contains__
2622
    so: setobject
2623
    object as key: object
2624
    /
2625
2626
x.__contains__(y) <==> y in x.
2627
[clinic start generated code]*/
2628
2629
static PyObject *
2630
set___contains___impl(PySetObject *so, PyObject *key)
2631
/*[clinic end generated code: output=b44863d034b3c70e input=cf4c72db704e4cf0]*/
2632
2.21M
{
2633
2.21M
    long result;
2634
2635
2.21M
    result = _PySet_Contains(so, key);
2636
2.21M
    if (result < 0)
2637
0
        return NULL;
2638
2.21M
    return PyBool_FromLong(result);
2639
2.21M
}
2640
2641
/*[clinic input]
2642
@coexist
2643
frozenset.__contains__
2644
    so: setobject
2645
    object as key: object
2646
    /
2647
2648
x.__contains__(y) <==> y in x.
2649
[clinic start generated code]*/
2650
2651
static PyObject *
2652
frozenset___contains___impl(PySetObject *so, PyObject *key)
2653
/*[clinic end generated code: output=2301ed91bc3a6dd5 input=2f04922a98d8bab7]*/
2654
3.52k
{
2655
3.52k
    Py_hash_t hash = PyObject_Hash(key);
2656
3.52k
    if (hash == -1) {
2657
0
        if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) {
2658
0
            set_unhashable_type(key);
2659
0
            return NULL;
2660
0
        }
2661
0
        PyErr_Clear();
2662
0
        Py_BEGIN_CRITICAL_SECTION(key);
2663
0
        hash = frozenset_hash_impl(key);
2664
0
        Py_END_CRITICAL_SECTION();
2665
0
    }
2666
3.52k
    setentry *entry; // unused
2667
3.52k
    int status = set_do_lookup(so, so->table, so->mask, key, hash, &entry,
2668
3.52k
                           set_compare_frozenset);
2669
3.52k
    if (status < 0)
2670
0
        return NULL;
2671
3.52k
    return PyBool_FromLong(status);
2672
3.52k
}
2673
2674
/*[clinic input]
2675
@critical_section
2676
set.remove
2677
    so: setobject
2678
    object as key: object
2679
    /
2680
2681
Remove an element from a set; it must be a member.
2682
2683
If the element is not a member, raise a KeyError.
2684
[clinic start generated code]*/
2685
2686
static PyObject *
2687
set_remove_impl(PySetObject *so, PyObject *key)
2688
/*[clinic end generated code: output=0b9134a2a2200363 input=893e1cb1df98227a]*/
2689
0
{
2690
0
    int rv;
2691
2692
0
    rv = set_discard_key(so, key);
2693
0
    if (rv < 0) {
2694
0
        if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
2695
0
            return NULL;
2696
0
        PyErr_Clear();
2697
0
        Py_hash_t hash;
2698
0
        Py_BEGIN_CRITICAL_SECTION(key);
2699
0
        hash = frozenset_hash_impl(key);
2700
0
        Py_END_CRITICAL_SECTION();
2701
0
        rv = set_discard_entry(so, key, hash);
2702
0
        if (rv < 0)
2703
0
            return NULL;
2704
0
    }
2705
2706
0
    if (rv == DISCARD_NOTFOUND) {
2707
0
        _PyErr_SetKeyError(key);
2708
0
        return NULL;
2709
0
    }
2710
0
    Py_RETURN_NONE;
2711
0
}
2712
2713
/*[clinic input]
2714
@critical_section
2715
set.discard
2716
    so: setobject
2717
    object as key: object
2718
    /
2719
2720
Remove an element from a set if it is a member.
2721
2722
Unlike set.remove(), the discard() method does not raise
2723
an exception when an element is missing from the set.
2724
[clinic start generated code]*/
2725
2726
static PyObject *
2727
set_discard_impl(PySetObject *so, PyObject *key)
2728
/*[clinic end generated code: output=eec3b687bf32759e input=861cb7fb69b4def0]*/
2729
264
{
2730
264
    int rv;
2731
2732
264
    rv = set_discard_key(so, key);
2733
264
    if (rv < 0) {
2734
0
        if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
2735
0
            return NULL;
2736
0
        PyErr_Clear();
2737
0
        Py_hash_t hash;
2738
0
        Py_BEGIN_CRITICAL_SECTION(key);
2739
0
        hash = frozenset_hash_impl(key);
2740
0
        Py_END_CRITICAL_SECTION();
2741
0
        rv = set_discard_entry(so, key, hash);
2742
0
        if (rv < 0)
2743
0
            return NULL;
2744
0
    }
2745
264
    Py_RETURN_NONE;
2746
264
}
2747
2748
/*[clinic input]
2749
@critical_section
2750
set.__reduce__
2751
    so: setobject
2752
2753
Return state information for pickling.
2754
[clinic start generated code]*/
2755
2756
static PyObject *
2757
set___reduce___impl(PySetObject *so)
2758
/*[clinic end generated code: output=9af7d0e029df87ee input=59405a4249e82f71]*/
2759
0
{
2760
0
    PyObject *keys=NULL, *args=NULL, *result=NULL, *state=NULL;
2761
2762
0
    keys = PySequence_List((PyObject *)so);
2763
0
    if (keys == NULL)
2764
0
        goto done;
2765
0
    args = PyTuple_Pack(1, keys);
2766
0
    if (args == NULL)
2767
0
        goto done;
2768
0
    state = _PyObject_GetState((PyObject *)so);
2769
0
    if (state == NULL)
2770
0
        goto done;
2771
0
    result = PyTuple_Pack(3, Py_TYPE(so), args, state);
2772
0
done:
2773
0
    Py_XDECREF(args);
2774
0
    Py_XDECREF(keys);
2775
0
    Py_XDECREF(state);
2776
0
    return result;
2777
0
}
2778
2779
/*[clinic input]
2780
@critical_section
2781
set.__sizeof__
2782
    so: setobject
2783
2784
S.__sizeof__() -> size of S in memory, in bytes.
2785
[clinic start generated code]*/
2786
2787
static PyObject *
2788
set___sizeof___impl(PySetObject *so)
2789
/*[clinic end generated code: output=4bfa3df7bd38ed88 input=09e1a09f168eaa23]*/
2790
0
{
2791
0
    size_t res = _PyObject_SIZE(Py_TYPE(so));
2792
0
    if (so->table != so->smalltable) {
2793
0
        res += ((size_t)so->mask + 1) * sizeof(setentry);
2794
0
    }
2795
0
    return PyLong_FromSize_t(res);
2796
0
}
2797
2798
static int
2799
set_init(PyObject *so, PyObject *args, PyObject *kwds)
2800
0
{
2801
0
    PySetObject *self = _PySet_CAST(so);
2802
0
    PyObject *iterable = NULL;
2803
2804
0
    if (!_PyArg_NoKeywords("set", kwds))
2805
0
        return -1;
2806
0
    if (!PyArg_UnpackTuple(args, Py_TYPE(self)->tp_name, 0, 1, &iterable))
2807
0
        return -1;
2808
2809
0
    if (_PyObject_IsUniquelyReferenced((PyObject *)self) && self->fill == 0) {
2810
0
        self->hash = -1;
2811
0
        if (iterable == NULL) {
2812
0
            return 0;
2813
0
        }
2814
0
        return set_update_local(self, iterable);
2815
0
    }
2816
0
    Py_BEGIN_CRITICAL_SECTION(self);
2817
0
    if (self->fill)
2818
0
        set_clear_internal((PyObject*)self);
2819
0
    self->hash = -1;
2820
0
    Py_END_CRITICAL_SECTION();
2821
2822
0
    if (iterable == NULL)
2823
0
        return 0;
2824
0
    return set_update_internal(self, iterable);
2825
0
}
2826
2827
static PyObject*
2828
set_vectorcall(PyObject *type, PyObject * const*args,
2829
               size_t nargsf, PyObject *kwnames)
2830
12.3M
{
2831
12.3M
    assert(PyType_Check(type));
2832
2833
12.3M
    if (!_PyArg_NoKwnames("set", kwnames)) {
2834
0
        return NULL;
2835
0
    }
2836
2837
12.3M
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
2838
12.3M
    if (!_PyArg_CheckPositional("set", nargs, 0, 1)) {
2839
0
        return NULL;
2840
0
    }
2841
2842
12.3M
    if (nargs) {
2843
18.2k
        return make_new_set(_PyType_CAST(type), args[0]);
2844
18.2k
    }
2845
2846
12.3M
    return make_new_set(_PyType_CAST(type), NULL);
2847
12.3M
}
2848
2849
static PySequenceMethods set_as_sequence = {
2850
    set_len,                            /* sq_length */
2851
    0,                                  /* sq_concat */
2852
    0,                                  /* sq_repeat */
2853
    0,                                  /* sq_item */
2854
    0,                                  /* sq_slice */
2855
    0,                                  /* sq_ass_item */
2856
    0,                                  /* sq_ass_slice */
2857
    set_contains,                       /* sq_contains */
2858
};
2859
2860
/* set object ********************************************************/
2861
2862
static PyMethodDef set_methods[] = {
2863
    SET_ADD_METHODDEF
2864
    SET_CLEAR_METHODDEF
2865
    SET___CONTAINS___METHODDEF
2866
    SET_COPY_METHODDEF
2867
    SET_DISCARD_METHODDEF
2868
    SET_DIFFERENCE_MULTI_METHODDEF
2869
    SET_DIFFERENCE_UPDATE_METHODDEF
2870
    SET_INTERSECTION_MULTI_METHODDEF
2871
    SET_INTERSECTION_UPDATE_MULTI_METHODDEF
2872
    SET_ISDISJOINT_METHODDEF
2873
    SET_ISSUBSET_METHODDEF
2874
    SET_ISSUPERSET_METHODDEF
2875
    SET_POP_METHODDEF
2876
    SET___REDUCE___METHODDEF
2877
    SET_REMOVE_METHODDEF
2878
    SET___SIZEOF___METHODDEF
2879
    SET_SYMMETRIC_DIFFERENCE_METHODDEF
2880
    SET_SYMMETRIC_DIFFERENCE_UPDATE_METHODDEF
2881
    SET_UNION_METHODDEF
2882
    SET_UPDATE_METHODDEF
2883
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
2884
     PyDoc_STR("sets are generic over the type of their elements")},
2885
    {NULL,              NULL}   /* sentinel */
2886
};
2887
2888
static PyNumberMethods set_as_number = {
2889
    0,                                  /*nb_add*/
2890
    set_sub,                            /*nb_subtract*/
2891
    0,                                  /*nb_multiply*/
2892
    0,                                  /*nb_remainder*/
2893
    0,                                  /*nb_divmod*/
2894
    0,                                  /*nb_power*/
2895
    0,                                  /*nb_negative*/
2896
    0,                                  /*nb_positive*/
2897
    0,                                  /*nb_absolute*/
2898
    0,                                  /*nb_bool*/
2899
    0,                                  /*nb_invert*/
2900
    0,                                  /*nb_lshift*/
2901
    0,                                  /*nb_rshift*/
2902
    set_and,                            /*nb_and*/
2903
    set_xor,                            /*nb_xor*/
2904
    set_or,                             /*nb_or*/
2905
    0,                                  /*nb_int*/
2906
    0,                                  /*nb_reserved*/
2907
    0,                                  /*nb_float*/
2908
    0,                                  /*nb_inplace_add*/
2909
    set_isub,                           /*nb_inplace_subtract*/
2910
    0,                                  /*nb_inplace_multiply*/
2911
    0,                                  /*nb_inplace_remainder*/
2912
    0,                                  /*nb_inplace_power*/
2913
    0,                                  /*nb_inplace_lshift*/
2914
    0,                                  /*nb_inplace_rshift*/
2915
    set_iand,                           /*nb_inplace_and*/
2916
    set_ixor,                           /*nb_inplace_xor*/
2917
    set_ior,                            /*nb_inplace_or*/
2918
};
2919
2920
PyDoc_STRVAR(set_doc,
2921
"set(iterable=(), /)\n\
2922
--\n\
2923
\n\
2924
Build an unordered collection of unique elements.");
2925
2926
PyTypeObject PySet_Type = {
2927
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2928
    "set",                              /* tp_name */
2929
    sizeof(PySetObject),                /* tp_basicsize */
2930
    0,                                  /* tp_itemsize */
2931
    /* methods */
2932
    set_dealloc,                        /* tp_dealloc */
2933
    0,                                  /* tp_vectorcall_offset */
2934
    0,                                  /* tp_getattr */
2935
    0,                                  /* tp_setattr */
2936
    0,                                  /* tp_as_async */
2937
    set_repr,                           /* tp_repr */
2938
    &set_as_number,                     /* tp_as_number */
2939
    &set_as_sequence,                   /* tp_as_sequence */
2940
    0,                                  /* tp_as_mapping */
2941
    PyObject_HashNotImplemented,        /* tp_hash */
2942
    0,                                  /* tp_call */
2943
    0,                                  /* tp_str */
2944
    PyObject_GenericGetAttr,            /* tp_getattro */
2945
    0,                                  /* tp_setattro */
2946
    0,                                  /* tp_as_buffer */
2947
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2948
        Py_TPFLAGS_BASETYPE |
2949
        _Py_TPFLAGS_MATCH_SELF,         /* tp_flags */
2950
    set_doc,                            /* tp_doc */
2951
    set_traverse,                       /* tp_traverse */
2952
    set_clear_internal,                 /* tp_clear */
2953
    set_richcompare,                    /* tp_richcompare */
2954
    offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */
2955
    set_iter,                           /* tp_iter */
2956
    0,                                  /* tp_iternext */
2957
    set_methods,                        /* tp_methods */
2958
    0,                                  /* tp_members */
2959
    0,                                  /* tp_getset */
2960
    0,                                  /* tp_base */
2961
    0,                                  /* tp_dict */
2962
    0,                                  /* tp_descr_get */
2963
    0,                                  /* tp_descr_set */
2964
    0,                                  /* tp_dictoffset */
2965
    set_init,                           /* tp_init */
2966
    _PyType_AllocNoTrack,               /* tp_alloc */
2967
    set_new,                            /* tp_new */
2968
    PyObject_GC_Del,                    /* tp_free */
2969
    .tp_vectorcall = set_vectorcall,
2970
    .tp_version_tag = _Py_TYPE_VERSION_SET,
2971
};
2972
2973
/* frozenset object ********************************************************/
2974
2975
2976
static PyMethodDef frozenset_methods[] = {
2977
    FROZENSET___CONTAINS___METHODDEF
2978
    FROZENSET_COPY_METHODDEF
2979
    SET_DIFFERENCE_MULTI_METHODDEF
2980
    SET_INTERSECTION_MULTI_METHODDEF
2981
    SET_ISDISJOINT_METHODDEF
2982
    SET_ISSUBSET_METHODDEF
2983
    SET_ISSUPERSET_METHODDEF
2984
    SET___REDUCE___METHODDEF
2985
    SET___SIZEOF___METHODDEF
2986
    SET_SYMMETRIC_DIFFERENCE_METHODDEF
2987
    SET_UNION_METHODDEF
2988
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
2989
     PyDoc_STR("frozensets are generic over the type of their elements")},
2990
    {NULL,              NULL}   /* sentinel */
2991
};
2992
2993
static PyNumberMethods frozenset_as_number = {
2994
    0,                                  /*nb_add*/
2995
    set_sub,                            /*nb_subtract*/
2996
    0,                                  /*nb_multiply*/
2997
    0,                                  /*nb_remainder*/
2998
    0,                                  /*nb_divmod*/
2999
    0,                                  /*nb_power*/
3000
    0,                                  /*nb_negative*/
3001
    0,                                  /*nb_positive*/
3002
    0,                                  /*nb_absolute*/
3003
    0,                                  /*nb_bool*/
3004
    0,                                  /*nb_invert*/
3005
    0,                                  /*nb_lshift*/
3006
    0,                                  /*nb_rshift*/
3007
    set_and,                            /*nb_and*/
3008
    set_xor,                            /*nb_xor*/
3009
    set_or,                             /*nb_or*/
3010
};
3011
3012
PyDoc_STRVAR(frozenset_doc,
3013
"frozenset(iterable=(), /)\n\
3014
--\n\
3015
\n\
3016
Build an immutable unordered collection of unique elements.");
3017
3018
PyTypeObject PyFrozenSet_Type = {
3019
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
3020
    "frozenset",                        /* tp_name */
3021
    sizeof(PySetObject),                /* tp_basicsize */
3022
    0,                                  /* tp_itemsize */
3023
    /* methods */
3024
    set_dealloc,                        /* tp_dealloc */
3025
    0,                                  /* tp_vectorcall_offset */
3026
    0,                                  /* tp_getattr */
3027
    0,                                  /* tp_setattr */
3028
    0,                                  /* tp_as_async */
3029
    set_repr,                           /* tp_repr */
3030
    &frozenset_as_number,               /* tp_as_number */
3031
    &set_as_sequence,                   /* tp_as_sequence */
3032
    0,                                  /* tp_as_mapping */
3033
    frozenset_hash,                     /* tp_hash */
3034
    0,                                  /* tp_call */
3035
    0,                                  /* tp_str */
3036
    PyObject_GenericGetAttr,            /* tp_getattro */
3037
    0,                                  /* tp_setattro */
3038
    0,                                  /* tp_as_buffer */
3039
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3040
        Py_TPFLAGS_BASETYPE |
3041
        _Py_TPFLAGS_MATCH_SELF,         /* tp_flags */
3042
    frozenset_doc,                      /* tp_doc */
3043
    set_traverse,                       /* tp_traverse */
3044
    set_clear_internal,                 /* tp_clear */
3045
    set_richcompare,                    /* tp_richcompare */
3046
    offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */
3047
    set_iter,                           /* tp_iter */
3048
    0,                                  /* tp_iternext */
3049
    frozenset_methods,                  /* tp_methods */
3050
    0,                                  /* tp_members */
3051
    0,                                  /* tp_getset */
3052
    0,                                  /* tp_base */
3053
    0,                                  /* tp_dict */
3054
    0,                                  /* tp_descr_get */
3055
    0,                                  /* tp_descr_set */
3056
    0,                                  /* tp_dictoffset */
3057
    0,                                  /* tp_init */
3058
    _PyType_AllocNoTrack,               /* tp_alloc */
3059
    frozenset_new,                      /* tp_new */
3060
    PyObject_GC_Del,                    /* tp_free */
3061
    .tp_vectorcall = frozenset_vectorcall,
3062
    .tp_version_tag = _Py_TYPE_VERSION_FROZEN_SET,
3063
};
3064
3065
3066
/***** C API functions *************************************************/
3067
3068
PyObject *
3069
PySet_New(PyObject *iterable)
3070
405k
{
3071
405k
    return make_new_set(&PySet_Type, iterable);
3072
405k
}
3073
3074
PyObject *
3075
PyFrozenSet_New(PyObject *iterable)
3076
4.43k
{
3077
4.43k
    PyObject *result = make_new_set(&PyFrozenSet_Type, iterable);
3078
4.43k
    if (result != NULL) {
3079
4.43k
        _PyFrozenSet_MaybeUntrack(result);
3080
4.43k
    }
3081
4.43k
    return result;
3082
4.43k
}
3083
3084
Py_ssize_t
3085
PySet_Size(PyObject *anyset)
3086
245
{
3087
245
    if (!PyAnySet_Check(anyset)) {
3088
0
        PyErr_BadInternalCall();
3089
0
        return -1;
3090
0
    }
3091
245
    return set_len(anyset);
3092
245
}
3093
3094
int
3095
PySet_Clear(PyObject *set)
3096
19
{
3097
19
    if (!PySet_Check(set)) {
3098
0
        PyErr_BadInternalCall();
3099
0
        return -1;
3100
0
    }
3101
19
    (void)set_clear(set, NULL);
3102
19
    return 0;
3103
19
}
3104
3105
void
3106
_PySet_ClearInternal(PySetObject *so)
3107
0
{
3108
0
    (void)set_clear_internal((PyObject*)so);
3109
0
}
3110
3111
int
3112
PySet_Contains(PyObject *anyset, PyObject *key)
3113
34.4k
{
3114
34.4k
    if (!PyAnySet_Check(anyset)) {
3115
0
        PyErr_BadInternalCall();
3116
0
        return -1;
3117
0
    }
3118
3119
34.4k
    PySetObject *so = (PySetObject *)anyset;
3120
34.4k
    Py_hash_t hash = PyObject_Hash(key);
3121
34.4k
    if (hash == -1) {
3122
0
        set_unhashable_type(key);
3123
0
        return -1;
3124
0
    }
3125
34.4k
    return set_contains_entry(so, key, hash);
3126
34.4k
}
3127
3128
int
3129
PySet_Discard(PyObject *set, PyObject *key)
3130
35.0k
{
3131
35.0k
    if (!PySet_Check(set)) {
3132
0
        PyErr_BadInternalCall();
3133
0
        return -1;
3134
0
    }
3135
3136
35.0k
    int rv;
3137
35.0k
    Py_BEGIN_CRITICAL_SECTION(set);
3138
35.0k
    rv = set_discard_key((PySetObject *)set, key);
3139
35.0k
    Py_END_CRITICAL_SECTION();
3140
35.0k
    return rv;
3141
35.0k
}
3142
3143
int
3144
PySet_Add(PyObject *anyset, PyObject *key)
3145
28.2k
{
3146
28.2k
    if (PySet_Check(anyset)) {
3147
23.7k
        int rv;
3148
23.7k
        Py_BEGIN_CRITICAL_SECTION(anyset);
3149
23.7k
        rv = set_add_key((PySetObject *)anyset, key);
3150
23.7k
        Py_END_CRITICAL_SECTION();
3151
23.7k
        return rv;
3152
23.7k
    }
3153
3154
4.47k
    if (PyFrozenSet_Check(anyset) && _PyObject_IsUniquelyReferenced(anyset)) {
3155
        // We can only change frozensets if they are uniquely referenced. The
3156
        // API limits the usage of `PySet_Add` to "fill in the values of brand
3157
        // new frozensets before they are exposed to other code". In this case,
3158
        // this can be done without a lock.
3159
        // Since another key is added to the set, we must track the frozenset
3160
        // if needed.
3161
4.47k
        if (PyFrozenSet_CheckExact(anyset) && !PyObject_GC_IsTracked(anyset) && PyObject_GC_IsTracked(key)) {
3162
4
            _PyObject_GC_TRACK(anyset);
3163
4
        }
3164
4.47k
        return set_add_key((PySetObject *)anyset, key);
3165
4.47k
    }
3166
3167
0
    PyErr_BadInternalCall();
3168
0
    return -1;
3169
4.47k
}
3170
3171
int
3172
_PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, Py_hash_t *hash)
3173
2.97k
{
3174
2.97k
    setentry *entry;
3175
3176
2.97k
    if (!PyAnySet_Check(set)) {
3177
0
        PyErr_BadInternalCall();
3178
0
        return -1;
3179
0
    }
3180
2.97k
    if (set_next((PySetObject *)set, pos, &entry) == 0)
3181
368
        return 0;
3182
2.60k
    *key = entry->key;
3183
2.60k
    *hash = entry->hash;
3184
2.60k
    return 1;
3185
2.97k
}
3186
3187
int
3188
_PySet_NextEntryRef(PyObject *set, Py_ssize_t *pos, PyObject **key, Py_hash_t *hash)
3189
4.60M
{
3190
4.60M
    setentry *entry;
3191
3192
4.60M
    if (!PyAnySet_Check(set)) {
3193
0
        PyErr_BadInternalCall();
3194
0
        return -1;
3195
0
    }
3196
4.60M
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(set);
3197
4.60M
    if (set_next((PySetObject *)set, pos, &entry) == 0)
3198
1.30M
        return 0;
3199
3.29M
    *key = Py_NewRef(entry->key);
3200
3.29M
    *hash = entry->hash;
3201
3.29M
    return 1;
3202
4.60M
}
3203
3204
PyObject *
3205
PySet_Pop(PyObject *set)
3206
0
{
3207
0
    if (!PySet_Check(set)) {
3208
0
        PyErr_BadInternalCall();
3209
0
        return NULL;
3210
0
    }
3211
0
    return set_pop(set, NULL);
3212
0
}
3213
3214
int
3215
_PySet_Update(PyObject *set, PyObject *iterable)
3216
42.8k
{
3217
42.8k
    if (!PySet_Check(set)) {
3218
0
        PyErr_BadInternalCall();
3219
0
        return -1;
3220
0
    }
3221
42.8k
    return set_update_internal((PySetObject *)set, iterable);
3222
42.8k
}
3223
3224
/* Exported for the gdb plugin's benefit. */
3225
PyObject *_PySet_Dummy = dummy;
3226
3227
/***** Dummy Struct  *************************************************/
3228
3229
static PyObject *
3230
dummy_repr(PyObject *op)
3231
0
{
3232
0
    return PyUnicode_FromString("<dummy key>");
3233
0
}
3234
3235
static void _Py_NO_RETURN
3236
dummy_dealloc(PyObject* ignore)
3237
0
{
3238
0
    Py_FatalError("deallocating <dummy key>");
3239
0
}
3240
3241
static PyTypeObject _PySetDummy_Type = {
3242
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
3243
    "<dummy key> type",
3244
    0,
3245
    0,
3246
    dummy_dealloc,      /*tp_dealloc*/ /*never called*/
3247
    0,                  /*tp_vectorcall_offset*/
3248
    0,                  /*tp_getattr*/
3249
    0,                  /*tp_setattr*/
3250
    0,                  /*tp_as_async*/
3251
    dummy_repr,         /*tp_repr*/
3252
    0,                  /*tp_as_number*/
3253
    0,                  /*tp_as_sequence*/
3254
    0,                  /*tp_as_mapping*/
3255
    0,                  /*tp_hash */
3256
    0,                  /*tp_call */
3257
    0,                  /*tp_str */
3258
    0,                  /*tp_getattro */
3259
    0,                  /*tp_setattro */
3260
    0,                  /*tp_as_buffer */
3261
    Py_TPFLAGS_DEFAULT, /*tp_flags */
3262
};
3263
3264
static PyObject _dummy_struct = _PyObject_HEAD_INIT(&_PySetDummy_Type);