Coverage Report

Created: 2026-11-30 07:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/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
2.94M
#define dummy (&_dummy_struct)
65
66
17.9M
#define SET_LOOKKEY_FOUND 1
67
64.7M
#define SET_LOOKKEY_NO_MATCH 0
68
0
#define SET_LOOKKEY_ERROR (-1)
69
10.3M
#define SET_LOOKKEY_CHANGED (-2)
70
54.5M
#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
77.4k
#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
13.7M
{
141
13.7M
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so);
142
13.7M
    if (entry->hash == 0 && entry->key == NULL)
143
6.16M
        return SET_LOOKKEY_EMPTY;
144
7.60M
    if (entry->hash == hash) {
145
4.22M
        PyObject *startkey = entry->key;
146
4.22M
        assert(startkey != dummy);
147
4.22M
        if (startkey == key)
148
4.22M
            return SET_LOOKKEY_FOUND;
149
1.04k
        if (PyUnicode_CheckExact(startkey)
150
1.04k
            && PyUnicode_CheckExact(key)
151
959
            && unicode_eq(startkey, key))
152
959
            return SET_LOOKKEY_FOUND;
153
85
        table = so->table;
154
85
        Py_INCREF(startkey);
155
85
        int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
156
85
        Py_DECREF(startkey);
157
85
        if (cmp < 0)
158
0
            return SET_LOOKKEY_ERROR;
159
85
        if (table != so->table || entry->key != startkey)
160
0
            return SET_LOOKKEY_CHANGED;
161
85
        if (cmp > 0)
162
82
            return SET_LOOKKEY_FOUND;
163
85
    }
164
3.37M
    return SET_LOOKKEY_NO_MATCH;
165
7.60M
}
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
27.3M
{
175
27.3M
    assert(PyFrozenSet_Check(so));
176
27.3M
    PyObject *startkey = ep->key;
177
27.3M
    if (startkey == NULL) {
178
12.1M
        return SET_LOOKKEY_EMPTY;
179
12.1M
    }
180
15.2M
    if (startkey == key) {
181
13.7M
        return SET_LOOKKEY_FOUND;
182
13.7M
    }
183
1.53M
    Py_ssize_t ep_hash = ep->hash;
184
1.53M
    if (ep_hash == hash) {
185
45.3k
        int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
186
45.3k
        if (cmp < 0) {
187
0
            return SET_LOOKKEY_ERROR;
188
0
        }
189
45.3k
        assert(cmp == SET_LOOKKEY_FOUND || cmp == SET_LOOKKEY_NO_MATCH);
190
45.3k
        return cmp;
191
45.3k
    }
192
1.48M
    return SET_LOOKKEY_NO_MATCH;
193
1.53M
}
194
195
static void
196
set_zero_table(setentry *table, size_t size)
197
98.3k
{
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
98.3k
    memset(table, 0, sizeof(setentry)*size);
206
98.3k
#endif
207
98.3k
}
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
49.5M
#define LINEAR_PROBES 9
215
#endif
216
217
/* This must be >= 1 */
218
2.37M
#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
36.2M
{
224
36.2M
    setentry *entry;
225
36.2M
    size_t perturb = hash;
226
36.2M
    size_t i = (size_t)hash & mask; /* Unsigned for defined overflow behavior */
227
36.2M
    int probes;
228
36.2M
    int status;
229
230
38.3M
    while (1) {
231
38.3M
        entry = &table[i];
232
38.3M
        probes = (i + LINEAR_PROBES <= mask) ? LINEAR_PROBES: 0;
233
41.1M
        do {
234
41.1M
            status = compare_entry(so, table, entry, key, hash);
235
41.1M
            if (status != SET_LOOKKEY_NO_MATCH) {
236
36.2M
                if (status == SET_LOOKKEY_EMPTY) {
237
18.2M
                    return SET_LOOKKEY_NO_MATCH;
238
18.2M
                }
239
17.9M
                *epp = entry;
240
17.9M
                return status;
241
36.2M
            }
242
4.90M
            entry++;
243
4.90M
        } while (probes--);
244
2.10M
        perturb >>= PERTURB_SHIFT;
245
2.10M
        i = (i * 5 + 1 + perturb) & mask;
246
2.10M
    }
247
36.2M
    Py_UNREACHABLE();
248
36.2M
}
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
1.07M
{
255
1.07M
    setentry *table;
256
1.07M
    setentry *freeslot;
257
1.07M
    setentry *entry;
258
1.07M
    size_t perturb;
259
1.07M
    size_t mask;
260
1.07M
    size_t i;                       /* Unsigned for defined overflow behavior */
261
1.07M
    int probes;
262
1.07M
    int cmp;
263
264
1.07M
  restart:
265
266
1.07M
    mask = so->mask;
267
1.07M
    i = (size_t)hash & mask;
268
1.07M
    freeslot = NULL;
269
1.07M
    perturb = hash;
270
271
1.32M
    while (1) {
272
1.32M
        entry = &so->table[i];
273
1.32M
        probes = (i + LINEAR_PROBES <= mask) ? LINEAR_PROBES: 0;
274
1.46M
        do {
275
1.46M
            if (entry->hash == 0 && entry->key == NULL)
276
989k
                goto found_unused_or_dummy;
277
475k
            if (entry->hash == hash) {
278
156k
                PyObject *startkey = entry->key;
279
156k
                assert(startkey != dummy);
280
156k
                if (startkey == key)
281
40.8k
                    goto found_active;
282
115k
                if (PyUnicode_CheckExact(startkey)
283
115k
                    && PyUnicode_CheckExact(key)
284
32.8k
                    && unicode_eq(startkey, key))
285
32.8k
                    goto found_active;
286
82.3k
                table = so->table;
287
82.3k
                Py_INCREF(startkey);
288
82.3k
                cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
289
82.3k
                Py_DECREF(startkey);
290
82.3k
                if (cmp > 0)
291
15.1k
                    goto found_active;
292
67.2k
                if (cmp < 0)
293
0
                    goto comparison_error;
294
67.2k
                if (table != so->table || entry->key != startkey)
295
0
                    goto restart;
296
67.2k
                mask = so->mask;
297
67.2k
            }
298
319k
            else if (entry->hash == -1) {
299
22.1k
                assert (entry->key == dummy);
300
22.1k
                freeslot = entry;
301
22.1k
            }
302
387k
            entry++;
303
387k
        } while (probes--);
304
245k
        perturb >>= PERTURB_SHIFT;
305
245k
        i = (i * 5 + 1 + perturb) & mask;
306
245k
    }
307
308
989k
  found_unused_or_dummy:
309
989k
    if (freeslot == NULL)
310
973k
        goto found_unused;
311
16.2k
    if (freeslot->hash != -1) {
312
0
        goto restart;
313
0
    }
314
16.2k
    FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, so->used + 1);
315
16.2k
    FT_ATOMIC_STORE_SSIZE_RELAXED(freeslot->hash, hash);
316
16.2k
    FT_ATOMIC_STORE_PTR_RELEASE(freeslot->key, key);
317
16.2k
    return 0;
318
319
973k
  found_unused:
320
973k
    so->fill++;
321
973k
    FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, so->used + 1);
322
973k
    FT_ATOMIC_STORE_SSIZE_RELAXED(entry->hash, hash);
323
973k
    FT_ATOMIC_STORE_PTR_RELEASE(entry->key, key);
324
973k
    if ((size_t)so->fill*5 < mask*3)
325
942k
        return 0;
326
30.7k
    return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
327
328
88.9k
  found_active:
329
88.9k
    Py_DECREF(key);
330
88.9k
    return 0;
331
332
0
  comparison_error:
333
0
    Py_DECREF(key);
334
0
    return -1;
335
973k
}
336
337
static int
338
set_add_entry(PySetObject *so, PyObject *key, Py_hash_t hash)
339
1.05M
{
340
1.05M
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so);
341
342
1.05M
    return set_add_entry_takeref(so, Py_NewRef(key), hash);
343
1.05M
}
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
21.4k
{
364
21.4k
    Py_hash_t hash = PyObject_Hash(key);
365
21.4k
    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
21.4k
    return set_add_entry_takeref(so, key, hash);
373
21.4k
}
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
304k
{
386
304k
    setentry *entry;
387
304k
    size_t perturb = hash;
388
304k
    size_t i = (size_t)hash & mask;
389
304k
    size_t j;
390
391
327k
    while (1) {
392
327k
        entry = &table[i];
393
327k
        if (entry->key == NULL)
394
278k
            goto found_null;
395
48.8k
        if (i + LINEAR_PROBES <= mask) {
396
35.3k
            for (j = 0; j < LINEAR_PROBES; j++) {
397
35.2k
                entry++;
398
35.2k
                if (entry->key == NULL)
399
25.8k
                    goto found_null;
400
35.2k
            }
401
25.8k
        }
402
23.0k
        perturb >>= PERTURB_SHIFT;
403
23.0k
        i = (i * 5 + 1 + perturb) & mask;
404
23.0k
    }
405
304k
  found_null:
406
304k
    FT_ATOMIC_STORE_SSIZE_RELAXED(entry->hash, hash);
407
304k
    FT_ATOMIC_STORE_PTR_RELEASE(entry->key, key);
408
304k
}
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
36.2M
{
416
36.2M
    int status;
417
36.2M
    if (PyFrozenSet_CheckExact(so)) {
418
25.8M
        status = set_do_lookup(so, so->table, so->mask, key, hash, epp,
419
25.8M
                               set_compare_frozenset);
420
25.8M
    }
421
10.3M
    else {
422
10.3M
        Py_BEGIN_CRITICAL_SECTION(so);
423
10.3M
        do {
424
10.3M
            status = set_do_lookup(so, so->table, so->mask, key, hash, epp,
425
10.3M
                                   set_compare_entry_lock_held);
426
10.3M
        } while (status == SET_LOOKKEY_CHANGED);
427
10.3M
        Py_END_CRITICAL_SECTION();
428
10.3M
    }
429
36.2M
    assert(status == SET_LOOKKEY_FOUND ||
430
36.2M
           status == SET_LOOKKEY_NO_MATCH ||
431
36.2M
           status == SET_LOOKKEY_ERROR);
432
36.2M
    return status;
433
36.2M
}
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
77.4k
{
469
#ifdef Py_GIL_DISABLED
470
    if (use_qsbr) {
471
        _PyMem_FreeDelayed(entries, size * sizeof(setentry));
472
        return;
473
    }
474
#endif
475
77.4k
    PyMem_Free(entries);
476
77.4k
}
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
98.3k
{
486
98.3k
    setentry *oldtable, *newtable, *entry;
487
98.3k
    Py_ssize_t oldmask = so->mask;
488
98.3k
    Py_ssize_t oldsize = (size_t)oldmask + 1;
489
98.3k
    size_t newmask;
490
98.3k
    int is_oldtable_malloced;
491
98.3k
    setentry small_copy[PySet_MINSIZE];
492
493
98.3k
    assert(minused >= 0);
494
495
    /* Find the smallest table size > minused. */
496
    /* XXX speed-up with intrinsics */
497
98.3k
    size_t newsize = PySet_MINSIZE;
498
256k
    while (newsize <= (size_t)minused) {
499
158k
        newsize <<= 1; // The largest possible value is PY_SSIZE_T_MAX + 1.
500
158k
    }
501
502
    /* Get space for a new table. */
503
98.3k
    oldtable = so->table;
504
98.3k
    assert(oldtable != NULL);
505
98.3k
    is_oldtable_malloced = oldtable != so->smalltable;
506
507
98.3k
    if (newsize == PySet_MINSIZE) {
508
        /* A large table is shrinking, or we can't get any smaller. */
509
20.5k
        newtable = so->smalltable;
510
20.5k
        if (newtable == oldtable) {
511
20.5k
            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
20.5k
            assert(so->fill > so->used);
522
20.5k
            memcpy(small_copy, oldtable, sizeof(small_copy));
523
20.5k
            oldtable = small_copy;
524
20.5k
        }
525
20.5k
    }
526
77.7k
    else {
527
77.7k
        newtable = PyMem_NEW(setentry, newsize);
528
77.7k
        if (newtable == NULL) {
529
0
            PyErr_NoMemory();
530
0
            return -1;
531
0
        }
532
77.7k
    }
533
534
    /* Make the set empty, using the new table. */
535
98.3k
    assert(newtable != oldtable);
536
98.3k
    set_zero_table(newtable, newsize);
537
98.3k
    FT_ATOMIC_STORE_PTR_RELEASE(so->table, NULL);
538
98.3k
    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
98.3k
    newmask = (size_t)so->mask;
543
98.3k
    if (so->fill == so->used) {
544
742k
        for (entry = oldtable; entry <= oldtable + oldmask; entry++) {
545
670k
            if (entry->key != NULL) {
546
209k
                set_insert_clean(newtable, newmask, entry->key, entry->hash);
547
209k
            }
548
670k
        }
549
71.9k
    } else {
550
26.4k
        so->fill = so->used;
551
237k
        for (entry = oldtable; entry <= oldtable + oldmask; entry++) {
552
211k
            if (entry->key != NULL && entry->key != dummy) {
553
15.9k
                set_insert_clean(newtable, newmask, entry->key, entry->hash);
554
15.9k
            }
555
211k
        }
556
26.4k
    }
557
558
98.3k
    FT_ATOMIC_STORE_PTR_RELEASE(so->table, newtable);
559
560
98.3k
    if (is_oldtable_malloced)
561
4.27k
        free_entries(oldtable, oldsize, SET_IS_SHARED(so));
562
98.3k
    return 0;
563
98.3k
}
564
565
static int
566
set_contains_entry(PySetObject *so, PyObject *key, Py_hash_t hash)
567
35.7M
{
568
#ifdef Py_GIL_DISABLED
569
    return set_lookkey_threadsafe(so, key, hash);
570
#else
571
35.7M
    setentry *entry; // unused
572
35.7M
    return set_lookkey(so, key, hash, &entry);
573
35.7M
#endif
574
35.7M
}
575
576
407k
#define DISCARD_NOTFOUND 0
577
113k
#define DISCARD_FOUND 1
578
579
static int
580
set_discard_entry(PySetObject *so, PyObject *key, Py_hash_t hash)
581
470k
{
582
470k
    setentry *entry;
583
470k
    PyObject *old_key;
584
470k
    int status = set_lookkey(so, key, hash, &entry);
585
470k
    if (status < 0) {
586
0
        return -1;
587
0
    }
588
470k
    if (status == SET_LOOKKEY_NO_MATCH) {
589
357k
        return DISCARD_NOTFOUND;
590
357k
    }
591
470k
    assert(status == SET_LOOKKEY_FOUND);
592
113k
    old_key = entry->key;
593
113k
    FT_ATOMIC_STORE_SSIZE_RELAXED(entry->hash, -1);
594
113k
    FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, so->used - 1);
595
113k
    FT_ATOMIC_STORE_PTR_RELEASE(entry->key, dummy);
596
113k
    Py_DECREF(old_key);
597
113k
    return DISCARD_FOUND;
598
113k
}
599
600
static int
601
set_add_key(PySetObject *so, PyObject *key)
602
710k
{
603
710k
    Py_hash_t hash = PyObject_Hash(key);
604
710k
    if (hash == -1) {
605
0
        set_unhashable_type(key);
606
0
        return -1;
607
0
    }
608
710k
    return set_add_entry(so, key, hash);
609
710k
}
610
611
static int
612
set_contains_key(PySetObject *so, PyObject *key)
613
0
{
614
0
    Py_hash_t hash = PyObject_Hash(key);
615
0
    if (hash == -1) {
616
0
        set_unhashable_type(key);
617
0
        return -1;
618
0
    }
619
0
    return set_contains_entry(so, key, hash);
620
0
}
621
622
static int
623
set_discard_key(PySetObject *so, PyObject *key)
624
419k
{
625
419k
    Py_hash_t hash = PyObject_Hash(key);
626
419k
    if (hash == -1) {
627
0
        set_unhashable_type(key);
628
0
        return -1;
629
0
    }
630
419k
    return set_discard_entry(so, key, hash);
631
419k
}
632
633
static void
634
set_empty_to_minsize(PySetObject *so)
635
0
{
636
0
    FT_ATOMIC_STORE_PTR_RELEASE(so->table, NULL);
637
0
    set_zero_table(so->smalltable, PySet_MINSIZE);
638
0
    so->fill = 0;
639
0
    FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, 0);
640
0
    FT_ATOMIC_STORE_SSIZE_RELEASE(so->mask, PySet_MINSIZE - 1);
641
0
    FT_ATOMIC_STORE_SSIZE_RELAXED(so->hash, -1);
642
0
    FT_ATOMIC_STORE_PTR_RELEASE(so->table, so->smalltable);
643
0
}
644
645
static int
646
set_clear_internal(PyObject *self)
647
0
{
648
0
    PySetObject *so = _PySet_CAST(self);
649
0
    setentry *entry;
650
0
    setentry *table = so->table;
651
0
    Py_ssize_t fill = so->fill;
652
0
    Py_ssize_t used = so->used;
653
0
    Py_ssize_t oldsize = (size_t)so->mask + 1;
654
0
    int table_is_malloced = table != so->smalltable;
655
0
    setentry small_copy[PySet_MINSIZE];
656
657
0
    assert (PyAnySet_Check(so));
658
0
    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
0
    if (table_is_malloced)
667
0
        set_empty_to_minsize(so);
668
669
0
    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
0
        memcpy(small_copy, table, sizeof(small_copy));
675
0
        table = small_copy;
676
0
        set_empty_to_minsize(so);
677
0
    }
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
0
    for (entry = table; used > 0; entry++) {
685
0
        if (entry->key && entry->key != dummy) {
686
0
            used--;
687
0
            Py_DECREF(entry->key);
688
0
        }
689
0
    }
690
691
0
    if (table_is_malloced)
692
0
        free_entries(table, oldsize, SET_IS_SHARED(so));
693
0
    return 0;
694
0
}
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
818k
{
712
818k
    Py_ssize_t i;
713
818k
    Py_ssize_t mask;
714
818k
    setentry *entry;
715
716
818k
    assert (PyAnySet_Check(so));
717
818k
    i = *pos_ptr;
718
818k
    assert(i >= 0);
719
818k
    mask = so->mask;
720
818k
    entry = &so->table[i];
721
2.49M
    while (i <= mask && (entry->key == NULL || entry->key == dummy)) {
722
1.67M
        i++;
723
1.67M
        entry++;
724
1.67M
    }
725
818k
    *pos_ptr = i+1;
726
818k
    if (i > mask)
727
116k
        return 0;
728
818k
    assert(entry != NULL);
729
701k
    *entry_ptr = entry;
730
701k
    return 1;
731
701k
}
732
733
static void
734
set_dealloc(PyObject *self)
735
998k
{
736
998k
    PySetObject *so = _PySet_CAST(self);
737
0
    setentry *entry;
738
998k
    Py_ssize_t used = so->used;
739
998k
    Py_ssize_t oldsize = (size_t)so->mask + 1;
740
741
    /* bpo-31095: UnTrack is needed before calling any callbacks */
742
998k
    PyObject_GC_UnTrack(so);
743
998k
    FT_CLEAR_WEAKREFS(self, so->weakreflist);
744
745
5.47M
    for (entry = so->table; used > 0; entry++) {
746
4.48M
        if (entry->key && entry->key != dummy) {
747
1.44M
                used--;
748
1.44M
                Py_DECREF(entry->key);
749
1.44M
        }
750
4.48M
    }
751
998k
    if (so->table != so->smalltable)
752
73.1k
        free_entries(so->table, oldsize, SET_IS_SHARED(so));
753
998k
    Py_TYPE(so)->tp_free(so);
754
998k
}
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
404k
{
821
404k
    PySetObject *so = _PySet_CAST(self);
822
404k
    return FT_ATOMIC_LOAD_SSIZE_RELAXED(so->used);
823
404k
}
824
825
static int
826
set_merge_lock_held(PySetObject *so, PyObject *otherset)
827
656k
{
828
656k
    PySetObject *other;
829
656k
    PyObject *key;
830
656k
    Py_ssize_t i;
831
656k
    setentry *so_entry;
832
656k
    setentry *other_entry;
833
834
656k
    assert (PyAnySet_Check(so));
835
656k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so);
836
656k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(otherset);
837
838
656k
    other = _PySet_CAST(otherset);
839
656k
    if (other == so || other->used == 0)
840
        /* a.update(a) or a.update(set()); nothing to do */
841
450k
        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
206k
    if ((so->fill + other->used)*5 >= so->mask*3) {
847
47.0k
        if (set_table_resize(so, (so->used + other->used)*2) != 0)
848
0
            return -1;
849
47.0k
    }
850
206k
    so_entry = so->table;
851
206k
    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
206k
    if (so->fill == 0 && so->mask == other->mask && other->fill == other->used) {
856
2.26M
        for (i = 0; i <= other->mask; i++, so_entry++, other_entry++) {
857
2.10M
            key = other_entry->key;
858
2.10M
            if (key != NULL) {
859
603k
                assert(so_entry->key == NULL);
860
603k
                FT_ATOMIC_STORE_SSIZE_RELAXED(so_entry->hash, other_entry->hash);
861
603k
                FT_ATOMIC_STORE_PTR_RELEASE(so_entry->key, Py_NewRef(key));
862
603k
            }
863
2.10M
        }
864
163k
        so->fill = other->fill;
865
163k
        FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, other->used);
866
163k
        return 0;
867
163k
    }
868
869
    /* If our table is empty, we can use set_insert_clean() */
870
42.5k
    if (so->fill == 0) {
871
7.86k
        setentry *newtable = so->table;
872
7.86k
        size_t newmask = (size_t)so->mask;
873
7.86k
        so->fill = other->used;
874
7.86k
        FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, other->used);
875
344k
        for (i = other->mask + 1; i > 0 ; i--, other_entry++) {
876
336k
            key = other_entry->key;
877
336k
            if (key != NULL && key != dummy) {
878
79.2k
                set_insert_clean(newtable, newmask, Py_NewRef(key),
879
79.2k
                                 other_entry->hash);
880
79.2k
            }
881
336k
        }
882
7.86k
        return 0;
883
7.86k
    }
884
885
    /* We can't assure there are no duplicates, so do normal insertions */
886
916k
    for (i = 0; i <= other->mask; i++) {
887
881k
        other_entry = &other->table[i];
888
881k
        key = other_entry->key;
889
881k
        if (key != NULL && key != dummy) {
890
295k
            if (set_add_entry(so, key, other_entry->hash))
891
0
                return -1;
892
295k
        }
893
881k
    }
894
34.6k
    return 0;
895
34.6k
}
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
93.5k
{
911
    /* Make sure the search finger is in bounds */
912
93.5k
    setentry *entry = so->table + (so->finger & so->mask);
913
93.5k
    setentry *limit = so->table + so->mask;
914
93.5k
    PyObject *key;
915
916
93.5k
    if (so->used == 0) {
917
0
        PyErr_SetString(PyExc_KeyError, "pop from an empty set");
918
0
        return NULL;
919
0
    }
920
354k
    while (entry->key == NULL || entry->key==dummy) {
921
261k
        entry++;
922
261k
        if (entry > limit)
923
16.4k
            entry = so->table;
924
261k
    }
925
93.5k
    FT_ATOMIC_STORE_SSIZE_RELAXED(entry->hash, -1);
926
93.5k
    FT_ATOMIC_STORE_SSIZE_RELAXED(so->used, so->used - 1);
927
93.5k
    key = entry->key;
928
93.5k
    FT_ATOMIC_STORE_PTR_RELEASE(entry->key, dummy);
929
93.5k
    so->finger = entry - so->table + 1;   /* next place to start */
930
93.5k
    return key;
931
93.5k
}
932
933
static int
934
set_traverse(PyObject *self, visitproc visit, void *arg)
935
28.5k
{
936
28.5k
    PySetObject *so = _PySet_CAST(self);
937
0
    Py_ssize_t pos = 0;
938
28.5k
    setentry *entry;
939
940
341k
    while (set_next(so, &pos, &entry))
941
312k
        Py_VISIT(entry->key);
942
28.5k
    return 0;
943
28.5k
}
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
294k
{
953
294k
    return ((h ^ 89869747UL) ^ (h << 16)) * 3644798167UL;
954
294k
}
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
13.2k
{
972
13.2k
    PySetObject *so = _PySet_CAST(self);
973
0
    Py_uhash_t hash = 0;
974
13.2k
    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
301k
    for (entry = so->table; entry <= &so->table[so->mask]; entry++)
987
287k
        hash ^= _shuffle_bits(entry->hash);
988
989
    /* Remove the effect of an odd number of NULL entries */
990
13.2k
    if ((so->mask + 1 - so->fill) & 1)
991
6.56k
        hash ^= _shuffle_bits(0);
992
993
    /* Remove the effect of an odd number of dummy entries */
994
13.2k
    if ((so->fill - so->used) & 1)
995
0
        hash ^= _shuffle_bits(-1);
996
997
    /* Factor in the number of active entries */
998
13.2k
    hash ^= ((Py_uhash_t)PySet_GET_SIZE(self) + 1) * 1927868237UL;
999
1000
    /* Disperse patterns arising in nested frozensets */
1001
13.2k
    hash ^= (hash >> 11) ^ (hash >> 25);
1002
13.2k
    hash = hash * 69069U + 907133923UL;
1003
1004
    /* -1 is reserved as an error code */
1005
13.2k
    if (hash == (Py_uhash_t)-1)
1006
0
        hash = 590923713UL;
1007
1008
13.2k
    return (Py_hash_t)hash;
1009
13.2k
}
1010
1011
static Py_hash_t
1012
frozenset_hash(PyObject *self)
1013
19.4k
{
1014
19.4k
    PySetObject *so = _PySet_CAST(self);
1015
0
    Py_uhash_t hash;
1016
1017
19.4k
    if (FT_ATOMIC_LOAD_SSIZE_RELAXED(so->hash) != -1) {
1018
6.23k
        return FT_ATOMIC_LOAD_SSIZE_ACQUIRE(so->hash);
1019
6.23k
    }
1020
1021
13.2k
    hash = frozenset_hash_impl(self);
1022
13.2k
    FT_ATOMIC_STORE_SSIZE_RELEASE(so->hash, hash);
1023
13.2k
    return hash;
1024
19.4k
}
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
155k
{
1042
155k
    setiterobject *si = (setiterobject*)self;
1043
    /* bpo-31095: UnTrack is needed before calling any callbacks */
1044
155k
    _PyObject_GC_UNTRACK(si);
1045
155k
    Py_XDECREF(si->si_set);
1046
155k
    PyObject_GC_Del(si);
1047
155k
}
1048
1049
static int
1050
setiter_traverse(PyObject *self, visitproc visit, void *arg)
1051
0
{
1052
0
    setiterobject *si = (setiterobject*)self;
1053
0
    Py_VISIT(si->si_set);
1054
0
    return 0;
1055
0
}
1056
1057
static PyObject *
1058
setiter_len(PyObject *op, PyObject *Py_UNUSED(ignored))
1059
0
{
1060
0
    setiterobject *si = (setiterobject*)op;
1061
0
    Py_ssize_t len = 0;
1062
0
    PySetObject *so = si->si_set;
1063
0
    if (so != NULL) {
1064
0
        Py_ssize_t so_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(so->used);
1065
0
        Py_ssize_t si_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(si->si_used);
1066
0
        if (si_used == so_used) {
1067
0
            len = FT_ATOMIC_LOAD_SSIZE_RELAXED(si->len);
1068
0
        }
1069
0
    }
1070
0
    return PyLong_FromSsize_t(len);
1071
0
}
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
334k
#define SETITER_EXHAUSTED (-1)
1107
1108
static void
1109
setiter_set_exhausted(setiterobject *si, PySetObject *so)
1110
155k
{
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
155k
    si->si_set = NULL;
1116
155k
    Py_DECREF(so);
1117
155k
#endif
1118
155k
}
1119
1120
static PyObject *setiter_iternext(PyObject *self)
1121
334k
{
1122
334k
    setiterobject *si = (setiterobject*)self;
1123
334k
    PyObject *key = NULL;
1124
334k
    Py_ssize_t i, mask;
1125
334k
    setentry *entry;
1126
334k
    PySetObject *so = si->si_set;
1127
1128
334k
    if (so == NULL)
1129
0
        return NULL;
1130
334k
    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
334k
    Py_ssize_t so_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(so->used);
1139
334k
    Py_ssize_t si_used = FT_ATOMIC_LOAD_SSIZE_RELAXED(si->si_used);
1140
334k
    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
334k
    Py_BEGIN_CRITICAL_SECTION(so);
1151
334k
    i = si->si_pos;
1152
334k
    if (i != SETITER_EXHAUSTED) {
1153
334k
        assert(i >= 0);
1154
334k
        entry = so->table;
1155
334k
        mask = so->mask;
1156
1.46M
        while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy)) {
1157
1.13M
            i++;
1158
1.13M
        }
1159
334k
        if (i <= mask) {
1160
179k
            key = Py_NewRef(entry[i].key);
1161
179k
            FT_ATOMIC_STORE_SSIZE_RELAXED(si->si_pos, i + 1);
1162
179k
            FT_ATOMIC_STORE_SSIZE_RELAXED(si->len, si->len - 1);
1163
179k
        }
1164
155k
        else {
1165
155k
            setiter_set_exhausted(si, so);
1166
155k
        }
1167
334k
    }
1168
334k
    Py_END_CRITICAL_SECTION();
1169
334k
    return key;
1170
334k
}
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
155k
{
1208
155k
    Py_ssize_t size = set_len(so);
1209
155k
    setiterobject *si = PyObject_GC_New(setiterobject, &PySetIter_Type);
1210
155k
    if (si == NULL)
1211
0
        return NULL;
1212
155k
    si->si_set = (PySetObject*)Py_NewRef(so);
1213
155k
    si->si_used = size;
1214
155k
    si->si_pos = 0;
1215
155k
    si->len = size;
1216
155k
    _PyObject_GC_TRACK(si);
1217
155k
    return (PyObject *)si;
1218
155k
}
1219
1220
static int
1221
set_update_dict_lock_held(PySetObject *so, PyObject *other)
1222
20.6k
{
1223
20.6k
    assert(PyAnyDict_CheckExact(other));
1224
1225
20.6k
    _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
20.6k
    Py_ssize_t dictsize = PyDict_GET_SIZE(other);
1237
20.6k
    if ((so->fill + dictsize)*5 >= so->mask*3) {
1238
0
        if (set_table_resize(so, (so->used + dictsize)*2) != 0) {
1239
0
            return -1;
1240
0
        }
1241
0
    }
1242
1243
20.6k
    Py_ssize_t pos = 0;
1244
20.6k
    PyObject *key;
1245
20.6k
    PyObject *value;
1246
20.6k
    Py_hash_t hash;
1247
71.2k
    while (_PyDict_Next(other, &pos, &key, &value, &hash)) {
1248
50.5k
        if (set_add_entry(so, key, hash)) {
1249
0
            return -1;
1250
0
        }
1251
50.5k
    }
1252
20.6k
    return 0;
1253
20.6k
}
1254
1255
static int
1256
set_update_iterable_lock_held(PySetObject *so, PyObject *other)
1257
13.4k
{
1258
13.4k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so);
1259
1260
13.4k
    PyObject *it = PyObject_GetIter(other);
1261
13.4k
    if (it == NULL) {
1262
0
        return -1;
1263
0
    }
1264
1265
13.4k
    PyObject *key;
1266
121k
    while ((key = PyIter_Next(it)) != NULL) {
1267
108k
        if (set_add_key(so, key)) {
1268
0
            Py_DECREF(it);
1269
0
            Py_DECREF(key);
1270
0
            return -1;
1271
0
        }
1272
108k
        Py_DECREF(key);
1273
108k
    }
1274
13.4k
    Py_DECREF(it);
1275
13.4k
    if (PyErr_Occurred())
1276
0
        return -1;
1277
13.4k
    return 0;
1278
13.4k
}
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
311k
{
1296
311k
    assert(Py_REFCNT(so) == 1);
1297
311k
    if (PyAnySet_Check(other)) {
1298
277k
        int rv;
1299
277k
        Py_BEGIN_CRITICAL_SECTION(other);
1300
277k
        rv = set_merge_lock_held(so, other);
1301
277k
        Py_END_CRITICAL_SECTION();
1302
277k
        return rv;
1303
277k
    }
1304
34.0k
    else if (PyDict_CheckExact(other)) {
1305
20.6k
        int rv;
1306
20.6k
        Py_BEGIN_CRITICAL_SECTION(other);
1307
20.6k
        rv = set_update_dict_lock_held(so, other);
1308
20.6k
        Py_END_CRITICAL_SECTION();
1309
20.6k
        return rv;
1310
20.6k
    }
1311
13.4k
    else if (PyFrozenDict_CheckExact(other)) {
1312
0
        return set_update_dict_lock_held(so, other);
1313
0
    }
1314
13.4k
    return set_update_iterable_lock_held(so, other);
1315
311k
}
1316
1317
static int
1318
set_update_internal(PySetObject *so, PyObject *other)
1319
338k
{
1320
338k
    if (PyAnySet_Check(other)) {
1321
338k
        if (Py_Is((PyObject *)so, other)) {
1322
0
            return 0;
1323
0
        }
1324
338k
        int rv;
1325
338k
        Py_BEGIN_CRITICAL_SECTION2(so, other);
1326
338k
        rv = set_merge_lock_held(so, other);
1327
338k
        Py_END_CRITICAL_SECTION2();
1328
338k
        return rv;
1329
338k
    }
1330
0
    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
0
    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
0
    else {
1345
0
        int rv;
1346
0
        Py_BEGIN_CRITICAL_SECTION(so);
1347
0
        rv = set_update_iterable_lock_held(so, other);
1348
0
        Py_END_CRITICAL_SECTION();
1349
0
        return rv;
1350
0
    }
1351
338k
}
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
0
{
1366
0
    Py_ssize_t i;
1367
1368
0
    for (i = 0; i < others_length; i++) {
1369
0
        PyObject *other = others[i];
1370
0
        if (set_update_internal(so, other))
1371
0
            return NULL;
1372
0
    }
1373
0
    Py_RETURN_NONE;
1374
0
}
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
999k
{
1387
999k
    assert(PyType_Check(type));
1388
1389
    // fields are zero-initialized by _PyType_AllocNoTrack
1390
999k
    PySetObject *so = (PySetObject *)_PyType_AllocNoTrack(type, 0);
1391
999k
    if (so == NULL) {
1392
0
        return NULL;
1393
0
    }
1394
1395
999k
    assert(so->fill == 0);
1396
999k
    assert(so->used == 0);
1397
999k
    so->mask = PySet_MINSIZE - 1;
1398
999k
    so->table = so->smalltable;
1399
999k
    so->hash = -1;
1400
999k
    assert(so->finger == 0);
1401
999k
    assert(so->weakreflist == NULL);
1402
1403
999k
    if (iterable != NULL) {
1404
290k
        if (set_update_local(so, iterable)) {
1405
0
            Py_DECREF(so);
1406
0
            return NULL;
1407
0
        }
1408
290k
    }
1409
1410
999k
    return (PyObject *)so;
1411
999k
}
1412
1413
static PyObject *
1414
make_new_set(PyTypeObject *type, PyObject *iterable)
1415
958k
{
1416
958k
    PyObject *so = make_new_set_untracked(type, iterable);
1417
958k
    if (so != NULL) {
1418
958k
        _PyObject_GC_TRACK(so);
1419
958k
    }
1420
958k
    return so;
1421
958k
}
1422
1423
static PyObject *
1424
make_new_set_basetype_untracked(PyTypeObject *type, PyObject *iterable)
1425
41.1k
{
1426
41.1k
    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
41.1k
    return make_new_set_untracked(type, iterable);
1433
41.1k
}
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
14.3k
{
1449
14.3k
    assert(op != NULL);
1450
    // subclasses of a frozenset can generate reference cycles, so do not untrack
1451
14.3k
    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
14.3k
    Py_ssize_t pos = 0;
1456
14.3k
    setentry *entry;
1457
80.5k
    while (set_next((PySetObject *)op, &pos, &entry)) {
1458
71.9k
        if (_PyObject_GC_MAY_BE_TRACKED(entry->key)) {
1459
5.73k
            return;
1460
5.73k
        }
1461
71.9k
    }
1462
8.58k
    _PyObject_GC_UNTRACK(op);
1463
8.58k
}
1464
1465
static PyObject *
1466
make_new_frozenset(PyTypeObject *type, PyObject *iterable)
1467
75
{
1468
75
    if (type != &PyFrozenSet_Type) {
1469
0
        return make_new_set(type, iterable);
1470
0
    }
1471
1472
75
    if (iterable != NULL && PyFrozenSet_CheckExact(iterable)) {
1473
        /* frozenset(f) is idempotent */
1474
0
        return Py_NewRef(iterable);
1475
0
    }
1476
75
    PyObject *obj = make_new_set(type, iterable);
1477
75
    if (obj != NULL) {
1478
75
        _PyFrozenSet_MaybeUntrack(obj);
1479
75
    }
1480
75
    return obj;
1481
75
}
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
75
{
1505
75
    if (!_PyArg_NoKwnames("frozenset", kwnames)) {
1506
0
        return NULL;
1507
0
    }
1508
1509
75
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
1510
75
    if (!_PyArg_CheckPositional("frozenset", nargs, 0, 1)) {
1511
0
        return NULL;
1512
0
    }
1513
1514
75
    PyObject *iterable = (nargs ? args[0] : NULL);
1515
75
    return make_new_frozenset(_PyType_CAST(type), iterable);
1516
75
}
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
25
{
1608
25
    assert(set != NULL);
1609
25
    assert(PySet_CheckExact(set));
1610
25
    assert(_PyObject_IsUniquelyReferenced(set));
1611
25
    set->ob_type = &PyFrozenSet_Type;
1612
25
    _PyFrozenSet_MaybeUntrack(set);
1613
25
    return Py_NewRef(set);
1614
25
}
1615
1616
static PyObject *
1617
set_copy_untracked_lock_held(PySetObject *so)
1618
41.1k
{
1619
41.1k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so);
1620
41.1k
    PyObject *copy = make_new_set_basetype_untracked(Py_TYPE(so), NULL);
1621
41.1k
    if (copy == NULL) {
1622
0
        return NULL;
1623
0
    }
1624
41.1k
    if (set_merge_lock_held((PySetObject *)copy, (PyObject *)so) < 0) {
1625
0
        Py_DECREF(copy);
1626
0
        return NULL;
1627
0
    }
1628
41.1k
    return copy;
1629
41.1k
}
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
41.1k
{
1643
41.1k
    PyObject *copy = set_copy_untracked_lock_held(so);
1644
41.1k
    if (copy != NULL) {
1645
41.1k
        _PyObject_GC_TRACK(copy);
1646
41.1k
    }
1647
41.1k
    return copy;
1648
41.1k
}
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
0
{
1680
0
    set_clear_internal((PyObject*)so);
1681
0
    Py_RETURN_NONE;
1682
0
}
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
0
{
1697
0
    PySetObject *result;
1698
0
    PyObject *other;
1699
0
    Py_ssize_t i;
1700
1701
0
    result = (PySetObject *)make_new_set_basetype_untracked(Py_TYPE(so),
1702
0
                                                            (PyObject *)so);
1703
0
    if (result == NULL)
1704
0
        return NULL;
1705
1706
0
    for (i = 0; i < others_length; i++) {
1707
0
        other = others[i];
1708
0
        if ((PyObject *)so == other)
1709
0
            continue;
1710
0
        if (set_update_local(result, other)) {
1711
0
            Py_DECREF(result);
1712
0
            return NULL;
1713
0
        }
1714
0
    }
1715
0
    _PyObject_GC_TRACK(result);
1716
0
    return (PyObject *)result;
1717
0
}
1718
1719
static PyObject *
1720
set_or(PyObject *self, PyObject *other)
1721
20.5k
{
1722
20.5k
    PySetObject *result;
1723
1724
20.5k
    if (!PyAnySet_Check(self) || !PyAnySet_Check(other))
1725
0
        Py_RETURN_NOTIMPLEMENTED;
1726
1727
20.5k
    result = (PySetObject *)set_copy(self, NULL);
1728
20.5k
    if (result == NULL) {
1729
0
        return NULL;
1730
0
    }
1731
20.5k
    if (Py_Is(self, other)) {
1732
0
        return (PyObject *)result;
1733
0
    }
1734
20.5k
    if (set_update_local(result, other)) {
1735
0
        Py_DECREF(result);
1736
0
        return NULL;
1737
0
    }
1738
20.5k
    return (PyObject *)result;
1739
20.5k
}
1740
1741
static PyObject *
1742
set_ior(PyObject *self, PyObject *other)
1743
338k
{
1744
338k
    if (!PyAnySet_Check(other))
1745
0
        Py_RETURN_NOTIMPLEMENTED;
1746
338k
    PySetObject *so = _PySet_CAST(self);
1747
1748
338k
    if (set_update_internal(so, other)) {
1749
0
        return NULL;
1750
0
    }
1751
338k
    return Py_NewRef(so);
1752
338k
}
1753
1754
static PyObject *
1755
set_intersection(PySetObject *so, PyObject *other)
1756
49
{
1757
49
    PySetObject *result;
1758
49
    PyObject *key, *it, *tmp;
1759
49
    Py_hash_t hash;
1760
49
    int rv;
1761
1762
49
    if ((PyObject *)so == other)
1763
0
        return set_copy_impl(so);
1764
1765
49
    result = (PySetObject *)make_new_set_basetype_untracked(Py_TYPE(so), NULL);
1766
49
    if (result == NULL)
1767
0
        return NULL;
1768
1769
49
    if (PyAnySet_Check(other)) {
1770
49
        Py_ssize_t pos = 0;
1771
49
        setentry *entry;
1772
1773
49
        if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) {
1774
42
            tmp = (PyObject *)so;
1775
42
            so = (PySetObject *)other;
1776
42
            other = tmp;
1777
42
        }
1778
1779
63
        while (set_next((PySetObject *)other, &pos, &entry)) {
1780
14
            key = entry->key;
1781
14
            hash = entry->hash;
1782
14
            Py_INCREF(key);
1783
14
            rv = set_contains_entry(so, key, hash);
1784
14
            if (rv < 0) {
1785
0
                Py_DECREF(result);
1786
0
                Py_DECREF(key);
1787
0
                return NULL;
1788
0
            }
1789
14
            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
14
            Py_DECREF(key);
1797
14
        }
1798
49
        _PyObject_GC_TRACK(result);
1799
49
        return (PyObject *)result;
1800
49
    }
1801
1802
0
    it = PyObject_GetIter(other);
1803
0
    if (it == NULL) {
1804
0
        Py_DECREF(result);
1805
0
        return NULL;
1806
0
    }
1807
1808
0
    while ((key = PyIter_Next(it)) != NULL) {
1809
0
        hash = PyObject_Hash(key);
1810
0
        if (hash == -1)
1811
0
            goto error;
1812
0
        rv = set_contains_entry(so, key, hash);
1813
0
        if (rv < 0)
1814
0
            goto error;
1815
0
        if (rv) {
1816
0
            if (set_add_entry(result, key, hash))
1817
0
                goto error;
1818
0
            if (PySet_GET_SIZE(result) >= PySet_GET_SIZE(so)) {
1819
0
                Py_DECREF(key);
1820
0
                break;
1821
0
            }
1822
0
        }
1823
0
        Py_DECREF(key);
1824
0
    }
1825
0
    Py_DECREF(it);
1826
0
    if (PyErr_Occurred()) {
1827
0
        Py_DECREF(result);
1828
0
        return NULL;
1829
0
    }
1830
0
    _PyObject_GC_TRACK(result);
1831
0
    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
0
}
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
0
{
1852
0
    Py_ssize_t i;
1853
1854
0
    if (others_length == 0) {
1855
0
        return set_copy((PyObject *)so, NULL);
1856
0
    }
1857
1858
0
    PyObject *result = Py_NewRef(so);
1859
0
    for (i = 0; i < others_length; i++) {
1860
0
        PyObject *other = others[i];
1861
0
        PyObject *newresult;
1862
0
        Py_BEGIN_CRITICAL_SECTION2(result, other);
1863
0
        newresult = set_intersection((PySetObject *)result, other);
1864
0
        Py_END_CRITICAL_SECTION2();
1865
0
        if (newresult == NULL) {
1866
0
            Py_DECREF(result);
1867
0
            return NULL;
1868
0
        }
1869
0
        Py_SETREF(result, newresult);
1870
0
    }
1871
0
    return result;
1872
0
}
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
49
{
1915
49
    if (!PyAnySet_Check(self) || !PyAnySet_Check(other))
1916
0
        Py_RETURN_NOTIMPLEMENTED;
1917
49
    PySetObject *so = _PySet_CAST(self);
1918
1919
0
    PyObject *rv;
1920
49
    Py_BEGIN_CRITICAL_SECTION2(so, other);
1921
49
    rv = set_intersection(so, other);
1922
49
    Py_END_CRITICAL_SECTION2();
1923
1924
49
    return rv;
1925
49
}
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
0
{
1960
0
    PyObject *key, *it, *tmp;
1961
0
    int rv;
1962
1963
0
    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
0
    if (PyAnySet_CheckExact(other)) {
1971
0
        Py_ssize_t pos = 0;
1972
0
        setentry *entry;
1973
1974
0
        if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) {
1975
0
            tmp = (PyObject *)so;
1976
0
            so = (PySetObject *)other;
1977
0
            other = tmp;
1978
0
        }
1979
0
        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
0
        Py_RETURN_TRUE;
1992
0
    }
1993
1994
0
    it = PyObject_GetIter(other);
1995
0
    if (it == NULL)
1996
0
        return NULL;
1997
1998
0
    while ((key = PyIter_Next(it)) != NULL) {
1999
0
        rv = set_contains_key(so, key);
2000
0
        Py_DECREF(key);
2001
0
        if (rv < 0) {
2002
0
            Py_DECREF(it);
2003
0
            return NULL;
2004
0
        }
2005
0
        if (rv) {
2006
0
            Py_DECREF(it);
2007
0
            Py_RETURN_FALSE;
2008
0
        }
2009
0
    }
2010
0
    Py_DECREF(it);
2011
0
    if (PyErr_Occurred())
2012
0
        return NULL;
2013
0
    Py_RETURN_TRUE;
2014
0
}
2015
2016
static int
2017
set_difference_update_internal(PySetObject *so, PyObject *other)
2018
20.5k
{
2019
20.5k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so);
2020
20.5k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(other);
2021
2022
20.5k
    if ((PyObject *)so == other)
2023
0
        return set_clear_internal((PyObject*)so);
2024
2025
20.5k
    if (PyAnySet_Check(other)) {
2026
20.5k
        setentry *entry;
2027
20.5k
        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
20.5k
        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
20.5k
        } else {
2038
20.5k
            Py_INCREF(other);
2039
20.5k
        }
2040
2041
71.1k
        while (set_next((PySetObject *)other, &pos, &entry)) {
2042
50.5k
            PyObject *key = entry->key;
2043
50.5k
            Py_INCREF(key);
2044
50.5k
            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
50.5k
            Py_DECREF(key);
2050
50.5k
        }
2051
2052
20.5k
        Py_DECREF(other);
2053
20.5k
    } 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
20.5k
    if ((size_t)(so->fill - so->used) <= (size_t)so->mask / 4)
2073
0
        return 0;
2074
20.5k
    return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
2075
20.5k
}
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
20.5k
{
2090
20.5k
    Py_ssize_t i;
2091
2092
41.1k
    for (i = 0; i < others_length; i++) {
2093
20.5k
        PyObject *other = others[i];
2094
20.5k
        int rv;
2095
20.5k
        Py_BEGIN_CRITICAL_SECTION2(so, other);
2096
20.5k
        rv = set_difference_update_internal(so, other);
2097
20.5k
        Py_END_CRITICAL_SECTION2();
2098
20.5k
        if (rv) {
2099
0
            return NULL;
2100
0
        }
2101
20.5k
    }
2102
20.5k
    Py_RETURN_NONE;
2103
20.5k
}
2104
2105
static PyObject *
2106
set_copy_and_difference_untracked(PySetObject *so, PyObject *other)
2107
0
{
2108
0
    PyObject *result;
2109
2110
0
    result = set_copy_untracked_lock_held(so);
2111
0
    if (result == NULL)
2112
0
        return NULL;
2113
0
    if (set_difference_update_internal((PySetObject *) result, other) == 0)
2114
0
        return result;
2115
0
    Py_DECREF(result);
2116
0
    return NULL;
2117
0
}
2118
2119
static PyObject *
2120
set_difference_untracked(PySetObject *so, PyObject *other)
2121
0
{
2122
0
    PyObject *result;
2123
0
    PyObject *key;
2124
0
    Py_hash_t hash;
2125
0
    setentry *entry;
2126
0
    Py_ssize_t pos = 0, other_size;
2127
0
    int rv;
2128
2129
0
    if (PyAnySet_Check(other)) {
2130
0
        other_size = PySet_GET_SIZE(other);
2131
0
    }
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
0
    if ((PySet_GET_SIZE(so) >> 2) > other_size) {
2142
0
        return set_copy_and_difference_untracked(so, other);
2143
0
    }
2144
2145
0
    result = make_new_set_basetype_untracked(Py_TYPE(so), NULL);
2146
0
    if (result == NULL)
2147
0
        return NULL;
2148
2149
0
    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
0
    while (set_next(so, &pos, &entry)) {
2174
0
        key = entry->key;
2175
0
        hash = entry->hash;
2176
0
        Py_INCREF(key);
2177
0
        rv = set_contains_entry((PySetObject *)other, key, hash);
2178
0
        if (rv < 0) {
2179
0
            Py_DECREF(result);
2180
0
            Py_DECREF(key);
2181
0
            return NULL;
2182
0
        }
2183
0
        if (!rv) {
2184
0
            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
0
        }
2190
0
        Py_DECREF(key);
2191
0
    }
2192
0
    return result;
2193
0
}
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
0
{
2241
0
    if (!PyAnySet_Check(self) || !PyAnySet_Check(other))
2242
0
        Py_RETURN_NOTIMPLEMENTED;
2243
0
    PySetObject *so = _PySet_CAST(self);
2244
2245
0
    PyObject *rv;
2246
0
    Py_BEGIN_CRITICAL_SECTION2(so, other);
2247
0
    rv = set_difference_untracked(so, other);
2248
0
    Py_END_CRITICAL_SECTION2();
2249
0
    if (rv != NULL) {
2250
0
        _PyObject_GC_TRACK(rv);
2251
0
    }
2252
0
    return rv;
2253
0
}
2254
2255
static PyObject *
2256
set_isub(PyObject *self, PyObject *other)
2257
0
{
2258
0
    if (!PyAnySet_Check(other))
2259
0
        Py_RETURN_NOTIMPLEMENTED;
2260
0
    PySetObject *so = _PySet_CAST(self);
2261
2262
0
    int rv;
2263
0
    Py_BEGIN_CRITICAL_SECTION2(so, other);
2264
0
    rv = set_difference_update_internal(so, other);
2265
0
    Py_END_CRITICAL_SECTION2();
2266
0
    if (rv < 0) {
2267
0
        return NULL;
2268
0
    }
2269
0
    return Py_NewRef(so);
2270
0
}
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
7.24k
{
2453
7.24k
    setentry *entry;
2454
7.24k
    Py_ssize_t pos = 0;
2455
7.24k
    int rv;
2456
2457
7.24k
    if (!PyAnySet_Check(other)) {
2458
0
        PyObject *tmp = set_intersection(so, other);
2459
0
        if (tmp == NULL) {
2460
0
            return NULL;
2461
0
        }
2462
0
        int result = (PySet_GET_SIZE(tmp) == PySet_GET_SIZE(so));
2463
0
        Py_DECREF(tmp);
2464
0
        return PyBool_FromLong(result);
2465
0
    }
2466
7.24k
    if (PySet_GET_SIZE(so) > PySet_GET_SIZE(other))
2467
0
        Py_RETURN_FALSE;
2468
2469
50.3k
    while (set_next(so, &pos, &entry)) {
2470
43.2k
        PyObject *key = entry->key;
2471
43.2k
        Py_INCREF(key);
2472
43.2k
        rv = set_contains_entry((PySetObject *)other, key, entry->hash);
2473
43.2k
        Py_DECREF(key);
2474
43.2k
        if (rv < 0) {
2475
0
            return NULL;
2476
0
        }
2477
43.2k
        if (!rv) {
2478
115
            Py_RETURN_FALSE;
2479
115
        }
2480
43.2k
    }
2481
7.24k
    Py_RETURN_TRUE;
2482
7.24k
}
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
0
{
2498
0
    if (PyAnySet_Check(other)) {
2499
0
        return set_issubset(other, (PyObject *)so);
2500
0
    }
2501
2502
0
    PyObject *key, *it = PyObject_GetIter(other);
2503
0
    if (it == NULL) {
2504
0
        return NULL;
2505
0
    }
2506
0
    while ((key = PyIter_Next(it)) != NULL) {
2507
0
        int rv = set_contains_key(so, key);
2508
0
        Py_DECREF(key);
2509
0
        if (rv < 0) {
2510
0
            Py_DECREF(it);
2511
0
            return NULL;
2512
0
        }
2513
0
        if (!rv) {
2514
0
            Py_DECREF(it);
2515
0
            Py_RETURN_FALSE;
2516
0
        }
2517
0
    }
2518
0
    Py_DECREF(it);
2519
0
    if (PyErr_Occurred()) {
2520
0
        return NULL;
2521
0
    }
2522
0
    Py_RETURN_TRUE;
2523
0
}
2524
2525
static PyObject *
2526
set_richcompare(PyObject *self, PyObject *w, int op)
2527
27.8k
{
2528
27.8k
    PySetObject *v = _PySet_CAST(self);
2529
0
    PyObject *r1;
2530
27.8k
    int r2;
2531
2532
27.8k
    if(!PyAnySet_Check(w))
2533
20.5k
        Py_RETURN_NOTIMPLEMENTED;
2534
2535
7.24k
    switch (op) {
2536
7.20k
    case Py_EQ:
2537
7.20k
        if (PySet_GET_SIZE(v) != PySet_GET_SIZE(w))
2538
0
            Py_RETURN_FALSE;
2539
7.20k
        Py_hash_t v_hash = FT_ATOMIC_LOAD_SSIZE_RELAXED(v->hash);
2540
7.20k
        Py_hash_t w_hash = FT_ATOMIC_LOAD_SSIZE_RELAXED(((PySetObject *)w)->hash);
2541
7.20k
        if (v_hash != -1 && w_hash != -1 && v_hash != w_hash)
2542
0
            Py_RETURN_FALSE;
2543
7.20k
        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
44
    case Py_LE:
2554
44
        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
7.24k
    }
2566
7.24k
    Py_RETURN_NOTIMPLEMENTED;
2567
7.24k
}
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
337k
{
2585
337k
    if (set_add_key(so, key))
2586
0
        return NULL;
2587
337k
    Py_RETURN_NONE;
2588
337k
}
2589
2590
int
2591
_PySet_Contains(PySetObject *so, PyObject *key)
2592
35.1M
{
2593
35.1M
    assert(so);
2594
2595
35.1M
    Py_hash_t hash = PyObject_Hash(key);
2596
35.1M
    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
35.1M
    return set_contains_entry(so, key, hash);
2610
35.1M
}
2611
2612
static int
2613
set_contains(PyObject *self, PyObject *key)
2614
302
{
2615
302
    PySetObject *so = _PySet_CAST(self);
2616
0
    return _PySet_Contains(so, key);
2617
302
}
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
0
{
2633
0
    long result;
2634
2635
0
    result = _PySet_Contains(so, key);
2636
0
    if (result < 0)
2637
0
        return NULL;
2638
0
    return PyBool_FromLong(result);
2639
0
}
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
69
{
2655
69
    Py_hash_t hash = PyObject_Hash(key);
2656
69
    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
69
    setentry *entry; // unused
2667
69
    int status = set_do_lookup(so, so->table, so->mask, key, hash, &entry,
2668
69
                           set_compare_frozenset);
2669
69
    if (status < 0)
2670
0
        return NULL;
2671
69
    return PyBool_FromLong(status);
2672
69
}
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
50.5k
{
2690
50.5k
    int rv;
2691
2692
50.5k
    rv = set_discard_key(so, key);
2693
50.5k
    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
50.5k
    if (rv == DISCARD_NOTFOUND) {
2707
0
        _PyErr_SetKeyError(key);
2708
0
        return NULL;
2709
0
    }
2710
50.5k
    Py_RETURN_NONE;
2711
50.5k
}
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
0
{
2730
0
    int rv;
2731
2732
0
    rv = set_discard_key(so, key);
2733
0
    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
0
    Py_RETURN_NONE;
2746
0
}
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
78.1k
{
2831
78.1k
    assert(PyType_Check(type));
2832
2833
78.1k
    if (!_PyArg_NoKwnames("set", kwnames)) {
2834
0
        return NULL;
2835
0
    }
2836
2837
78.1k
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
2838
78.1k
    if (!_PyArg_CheckPositional("set", nargs, 0, 1)) {
2839
0
        return NULL;
2840
0
    }
2841
2842
78.1k
    if (nargs) {
2843
156
        return make_new_set(_PyType_CAST(type), args[0]);
2844
156
    }
2845
2846
77.9k
    return make_new_set(_PyType_CAST(type), NULL);
2847
77.9k
}
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
866k
{
3071
866k
    return make_new_set(&PySet_Type, iterable);
3072
866k
}
3073
3074
PyObject *
3075
PyFrozenSet_New(PyObject *iterable)
3076
14.2k
{
3077
14.2k
    PyObject *result = make_new_set(&PyFrozenSet_Type, iterable);
3078
14.2k
    if (result != NULL) {
3079
14.2k
        _PyFrozenSet_MaybeUntrack(result);
3080
14.2k
    }
3081
14.2k
    return result;
3082
14.2k
}
3083
3084
Py_ssize_t
3085
PySet_Size(PyObject *anyset)
3086
0
{
3087
0
    if (!PyAnySet_Check(anyset)) {
3088
0
        PyErr_BadInternalCall();
3089
0
        return -1;
3090
0
    }
3091
0
    return set_len(anyset);
3092
0
}
3093
3094
int
3095
PySet_Clear(PyObject *set)
3096
0
{
3097
0
    if (!PySet_Check(set)) {
3098
0
        PyErr_BadInternalCall();
3099
0
        return -1;
3100
0
    }
3101
0
    (void)set_clear(set, NULL);
3102
0
    return 0;
3103
0
}
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
571k
{
3114
571k
    if (!PyAnySet_Check(anyset)) {
3115
0
        PyErr_BadInternalCall();
3116
0
        return -1;
3117
0
    }
3118
3119
571k
    PySetObject *so = (PySetObject *)anyset;
3120
571k
    Py_hash_t hash = PyObject_Hash(key);
3121
571k
    if (hash == -1) {
3122
0
        set_unhashable_type(key);
3123
0
        return -1;
3124
0
    }
3125
571k
    return set_contains_entry(so, key, hash);
3126
571k
}
3127
3128
int
3129
PySet_Discard(PyObject *set, PyObject *key)
3130
368k
{
3131
368k
    if (!PySet_Check(set)) {
3132
0
        PyErr_BadInternalCall();
3133
0
        return -1;
3134
0
    }
3135
3136
368k
    int rv;
3137
368k
    Py_BEGIN_CRITICAL_SECTION(set);
3138
368k
    rv = set_discard_key((PySetObject *)set, key);
3139
368k
    Py_END_CRITICAL_SECTION();
3140
368k
    return rv;
3141
368k
}
3142
3143
int
3144
PySet_Add(PyObject *anyset, PyObject *key)
3145
265k
{
3146
265k
    if (PySet_Check(anyset)) {
3147
263k
        int rv;
3148
263k
        Py_BEGIN_CRITICAL_SECTION(anyset);
3149
263k
        rv = set_add_key((PySetObject *)anyset, key);
3150
263k
        Py_END_CRITICAL_SECTION();
3151
263k
        return rv;
3152
263k
    }
3153
3154
1.86k
    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
1.86k
        if (PyFrozenSet_CheckExact(anyset) && !PyObject_GC_IsTracked(anyset) && PyObject_GC_IsTracked(key)) {
3162
0
            _PyObject_GC_TRACK(anyset);
3163
0
        }
3164
1.86k
        return set_add_key((PySetObject *)anyset, key);
3165
1.86k
    }
3166
3167
0
    PyErr_BadInternalCall();
3168
0
    return -1;
3169
1.86k
}
3170
3171
int
3172
_PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, Py_hash_t *hash)
3173
65.0k
{
3174
65.0k
    setentry *entry;
3175
3176
65.0k
    if (!PyAnySet_Check(set)) {
3177
0
        PyErr_BadInternalCall();
3178
0
        return -1;
3179
0
    }
3180
65.0k
    if (set_next((PySetObject *)set, pos, &entry) == 0)
3181
8.74k
        return 0;
3182
56.3k
    *key = entry->key;
3183
56.3k
    *hash = entry->hash;
3184
56.3k
    return 1;
3185
65.0k
}
3186
3187
int
3188
_PySet_NextEntryRef(PyObject *set, Py_ssize_t *pos, PyObject **key, Py_hash_t *hash)
3189
209k
{
3190
209k
    setentry *entry;
3191
3192
209k
    if (!PyAnySet_Check(set)) {
3193
0
        PyErr_BadInternalCall();
3194
0
        return -1;
3195
0
    }
3196
209k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(set);
3197
209k
    if (set_next((PySetObject *)set, pos, &entry) == 0)
3198
43.1k
        return 0;
3199
166k
    *key = Py_NewRef(entry->key);
3200
166k
    *hash = entry->hash;
3201
166k
    return 1;
3202
209k
}
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
1
{
3217
1
    if (!PySet_Check(set)) {
3218
0
        PyErr_BadInternalCall();
3219
0
        return -1;
3220
0
    }
3221
1
    return set_update_internal((PySetObject *)set, iterable);
3222
1
}
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);