Repository navigation
Expand file tree
/
Copy pathbitset.go
More file actions
693 lines (640 loc) · 21.8 KB
/
Copy pathbitset.go
File metadata and controls
693 lines (640 loc) · 21.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
package sets
import (
"database/sql/driver"
"encoding/json"
"fmt"
"iter"
"math"
"math/bits"
"math/rand/v2"
"slices"
)
// Integer is the element constraint for BitSet: any integer type, including named
// types via the ~ forms. It is a subset of cmp.Ordered, so every Integer type can
// also be used with the OrderedSet helpers.
type Integer interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}
// BitSet is an integer set backed by a dense bitmap: one bit per value in the span
// between the smallest and largest element the set currently covers. It is always
// sorted in ascending order (like SortedSet, Sort is a no-op). It is not safe for
// concurrent use; wrap it with NewLockedOrderedWrapping when concurrency is needed.
//
// BitSet's zero value is ready to use.
//
// # Memory model
//
// Memory is proportional to the SPAN of the elements (max − min), not to how many
// elements are stored: covering a span of S values costs S/8 bytes, rounded up to
// 8-byte words. Compared to Map's roughly 50 bytes per element, a BitSet is smaller
// whenever more than about 1 in every 400 values of the span is present, and is
// dramatically smaller for dense data (a full uint16 universe costs 8 KiB total).
// The flip side is pathological for sparse, far-apart values: after Add(0),
// Add(1 << 40) must allocate ~128 GiB of words. Adding an element far outside the
// current span panics if the required backing array cannot be allocated (or, on
// 32-bit platforms, cannot be represented). BitSet is therefore best suited to
// naturally bounded, reasonably dense domains: IDs, ports, enum values, rune
// tables, and the like.
//
// Storage grows to cover new elements but is never released automatically: Remove
// clears a bit without shrinking the span, so a set that once held 0 and 1<<20
// keeps ~128 KiB until Compact or Clear is called. Reserve preallocates a span up
// front to avoid regrowth; Compact reallocates to the tightest span covering the
// current elements; Clear releases the backing array entirely.
//
// Complexity (S = span in values, W = S/64 words):
// - Add: O(1) within the current span; O(W) when extending it
// - Remove: O(1)
// - Contains: O(1)
// - At, Index: O(W) (popcount scan)
// - Iterator: O(W + N)
// - Max, Min: O(1) when the span edges are occupied; O(W) worst case, when Removes have
// left zero words at the span edges
// - Union, Intersection, Difference, SymmetricDifference with another BitSet
// of the same element type: O(W) word-wise, via the package-level functions
// (BitSet implements the optional Unioner, Intersectioner, Differencer, and
// SymmetricDifferencer interfaces)
// - Equal, Disjoint, Subset (and thus Superset) with another BitSet of the
// same element type: O(W) word-wise with early exit, no iteration or
// hashing, via the package-level functions (BitSet implements the optional
// Equaler, Disjointer, and Subsetter interfaces)
type BitSet[M Integer] struct {
words []uint64 // bit j of words[i] covers universe index (start+i)*64 + j
start uint64 // universe word index of words[0]; meaningful only when len(words) > 0
card int
}
var _ OrderedSet[int] = new(BitSet[int])
var _ driver.Valuer = new(BitSet[int])
var _ Unioner[int] = new(BitSet[int])
var _ Intersectioner[int] = new(BitSet[int])
var _ Differencer[int] = new(BitSet[int])
var _ SymmetricDifferencer[int] = new(BitSet[int])
var _ Maxer[int] = new(BitSet[int])
var _ Minner[int] = new(BitSet[int])
var _ Equaler[int] = new(BitSet[int])
var _ Disjointer[int] = new(BitSet[int])
var _ Subsetter[int] = new(BitSet[int])
// NewBitSet returns an empty *BitSet[M].
func NewBitSet[M Integer]() *BitSet[M] {
return &BitSet[M]{}
}
// NewBitSetFrom returns a new *BitSet[M] filled with the values from the sequence.
func NewBitSetFrom[M Integer](seq iter.Seq[M]) *BitSet[M] {
var s BitSet[M]
for m := range seq {
s.Add(m)
}
return &s
}
// NewBitSetWith returns a new *BitSet[M] with the values provided.
func NewBitSetWith[M Integer](m ...M) *BitSet[M] {
return NewBitSetFrom(slices.Values(m))
}
// signBit is 1<<63 when M is signed and 0 when M is unsigned. XORing it onto a
// value converted to uint64 maps M's ordering onto uint64 ordering, giving every
// element a "universe index" in [0, 2^64) that sorts the same way the elements do.
func signBit[M Integer]() uint64 {
var zero M
if zero-1 < zero { // signed types wrap to -1; unsigned types wrap to their maximum
return 1 << 63
}
return 0
}
func toUniverse[M Integer](m M) uint64 { return uint64(m) ^ signBit[M]() }
func fromUniverse[M Integer](u uint64) M { return M(u ^ signBit[M]()) }
// spanWords returns the number of words needed to cover universe word indexes lo
// through hi inclusive. It panics when that count would overflow an int or imply
// an allocation larger than the address space allows; make itself panics below
// that bound. Either way an unallocatable span fails loudly instead of wrapping.
func spanWords(lo, hi uint64) int {
n := hi - lo + 1
if n == 0 || n > math.MaxInt>>3 {
panic("sets: BitSet span too large to allocate")
}
return int(n)
}
// grow extends the backing slice to cover universe word w. Growth allocates whole
// words for the entire new span — the memory cost documented on the type.
func (s *BitSet[M]) grow(w uint64) {
if len(s.words) == 0 {
s.start = w
s.words = append(s.words, 0)
return
}
end := s.start + uint64(len(s.words)) // one past the last covered word
switch {
case w < s.start:
grown := make([]uint64, spanWords(w, end-1))
copy(grown[s.start-w:], s.words)
s.words = grown
s.start = w
case w >= end:
n := spanWords(s.start, w)
old := len(s.words)
s.words = slices.Grow(s.words, n-old)[:n]
clear(s.words[old:]) // spare capacity may hold stale words from a past trim
}
}
// trim re-slices away leading and trailing zero words. It does not release memory
// (see Compact); it keeps the span tight for rank scans and word-wise operations.
func (s *BitSet[M]) trim() {
i := 0
for i < len(s.words) && s.words[i] == 0 {
i++
}
if i == len(s.words) {
s.words, s.start = nil, 0
return
}
s.words = s.words[i:]
s.start += uint64(i)
j := len(s.words)
for s.words[j-1] == 0 {
j--
}
s.words = s.words[:j]
}
// Contains returns true if the set contains the element.
func (s *BitSet[M]) Contains(m M) bool {
u := toUniverse(m)
w := u >> 6
if len(s.words) == 0 || w < s.start || w >= s.start+uint64(len(s.words)) {
return false
}
return s.words[w-s.start]&(1<<(u&63)) != 0
}
// Clear removes all elements from the set and returns the number of elements
// removed. Unlike the other implementations, Clear releases the backing array:
// its size is proportional to the retired span, which is usually exactly the
// memory a caller clearing a BitSet wants back.
func (s *BitSet[M]) Clear() int {
n := s.card
s.words, s.start, s.card = nil, 0, 0
return n
}
// Add an element to the set. Returns true if the element was added, false if it was
// already present. Adding an element outside the current span grows the backing
// array to cover it (see the type comment for the memory implications) and panics
// if that allocation is impossible.
func (s *BitSet[M]) Add(m M) bool {
u := toUniverse(m)
s.grow(u >> 6)
i := (u >> 6) - s.start
bit := uint64(1) << (u & 63)
if s.words[i]&bit != 0 {
return false
}
s.words[i] |= bit
s.card++
return true
}
// Remove an element from the set. Returns true if the element was removed, false if
// it was not present. Remove never shrinks the backing array; call Compact to
// release memory after removing span-extreme elements.
func (s *BitSet[M]) Remove(m M) bool {
u := toUniverse(m)
w := u >> 6
if len(s.words) == 0 || w < s.start || w >= s.start+uint64(len(s.words)) {
return false
}
bit := uint64(1) << (u & 63)
if s.words[w-s.start]&bit == 0 {
return false
}
s.words[w-s.start] &^= bit
s.card--
return true
}
// Cardinality returns the number of elements in the set.
func (s *BitSet[M]) Cardinality() int {
if s == nil {
return 0
}
return s.card
}
// Iterator yields all elements in the set in ascending order.
func (s *BitSet[M]) Iterator(yield func(M) bool) {
for i, w := range s.words {
base := (s.start + uint64(i)) << 6
for w != 0 {
b := bits.TrailingZeros64(w)
if !yield(fromUniverse[M](base | uint64(b))) {
return
}
w &= w - 1 // clear the lowest set bit
}
}
}
// Clone returns a copy of the set. The underlying type is the same as the original set.
func (s *BitSet[M]) Clone() Set[M] {
return &BitSet[M]{words: slices.Clone(s.words), start: s.start, card: s.card}
}
// Ordered iteration yields the index and value of each element in the set in ascending order.
func (s *BitSet[M]) Ordered(yield func(int, M) bool) {
var n int
for i, w := range s.words {
base := (s.start + uint64(i)) << 6
for w != 0 {
b := bits.TrailingZeros64(w)
if !yield(n, fromUniverse[M](base|uint64(b))) {
return
}
n++
w &= w - 1
}
}
}
// Backwards iteration yields the index and value of each element in the set in descending order.
func (s *BitSet[M]) Backwards(yield func(int, M) bool) {
n := s.card - 1
for i := len(s.words) - 1; i >= 0; i-- {
w := s.words[i]
base := (s.start + uint64(i)) << 6
for w != 0 {
b := 63 - bits.LeadingZeros64(w)
if !yield(n, fromUniverse[M](base|uint64(b))) {
return
}
n--
w &^= 1 << uint(b)
}
}
}
// Range returns an iterator over the elements v for which lo <= v <= hi, in
// ascending order. A call costs O(W) for the words overlapping [lo, hi] plus the
// number of elements yielded. If lo > hi the iterator yields nothing.
func (s *BitSet[M]) Range(lo, hi M) iter.Seq[M] {
return func(yield func(M) bool) {
if hi < lo || len(s.words) == 0 {
return
}
ul, uh := toUniverse(lo), toUniverse(hi)
// clamp to the covered span; the -1 wraps correctly when the span
// reaches the top of the universe
if first := s.start << 6; ul < first {
ul = first
}
if last := ((s.start + uint64(len(s.words))) << 6) - 1; uh > last {
uh = last
}
if uh < ul {
return
}
for wi := ul >> 6; wi <= uh>>6; wi++ {
w := s.words[wi-s.start]
if wi == ul>>6 {
w &= ^uint64(0) << (ul & 63)
}
if wi == uh>>6 {
w &= ^uint64(0) >> (63 - uh&63)
}
base := wi << 6
for w != 0 {
b := bits.TrailingZeros64(w)
if !yield(fromUniverse[M](base | uint64(b))) {
return
}
w &= w - 1
}
}
}
}
// Reserve grows the backing array to cover the inclusive element range [lo, hi] in
// a single allocation, so subsequent Adds within the range never regrow. It does
// not add any elements. If lo > hi, Reserve does nothing.
func (s *BitSet[M]) Reserve(lo, hi M) {
if hi < lo {
return
}
s.grow(toUniverse(lo) >> 6)
s.grow(toUniverse(hi) >> 6)
}
// Compact reallocates the backing array to the smallest size covering the current
// elements. Use it to release memory after Remove has shrunk the occupied span or
// after a Reserve that turned out to be too generous. If the set is empty the
// backing array is released entirely.
func (s *BitSet[M]) Compact() {
s.trim()
if s.words != nil {
s.words = slices.Clip(slices.Clone(s.words))
}
}
// NewEmptyOrdered returns a new empty ordered set of the same underlying type.
func (s *BitSet[M]) NewEmptyOrdered() OrderedSet[M] {
return NewBitSet[M]()
}
// NewEmpty returns a new empty set of the same underlying type.
func (s *BitSet[M]) NewEmpty() Set[M] {
return NewBitSet[M]()
}
// Pop removes and returns a random element from the set. If the set is empty, it
// returns the zero value of M and false. Selecting the element is a rank scan, so
// Pop is O(W).
func (s *BitSet[M]) Pop() (M, bool) {
if s.card == 0 {
var m M
return m, false
}
m, _ := s.At(rand.IntN(s.card))
s.Remove(m)
return m, true
}
// Sort is a no-op: the set is always sorted in ascending order.
func (s *BitSet[M]) Sort() {}
// At returns the element at the index. If the index is out of bounds, the second
// return value is false.
func (s *BitSet[M]) At(i int) (M, bool) {
if i < 0 || i >= s.card {
var zero M
return zero, false
}
rank := i
for wi, w := range s.words {
n := bits.OnesCount64(w)
if rank >= n {
rank -= n
continue
}
for ; rank > 0; rank-- {
w &= w - 1
}
b := bits.TrailingZeros64(w)
return fromUniverse[M]((s.start+uint64(wi))<<6 | uint64(b)), true
}
var zero M // unreachable while card matches the stored bits
return zero, false
}
// Index returns the index of the element in the set, or -1 if not present.
func (s *BitSet[M]) Index(m M) int {
u := toUniverse(m)
w := u >> 6
if len(s.words) == 0 || w < s.start || w >= s.start+uint64(len(s.words)) {
return -1
}
bit := uint64(1) << (u & 63)
if s.words[w-s.start]&bit == 0 {
return -1
}
rank := bits.OnesCount64(s.words[w-s.start] & (bit - 1))
for _, pw := range s.words[:w-s.start] {
rank += bits.OnesCount64(pw)
}
return rank
}
func (s *BitSet[M]) elements() []M {
out := make([]M, 0, s.card)
for m := range s.Iterator {
out = append(out, m)
}
return out
}
// String returns a string representation of the set. It returns a string of the form BitSet[T](<elements>).
func (s *BitSet[M]) String() string {
var m M
return fmt.Sprintf("BitSet[%T](%v)", m, s.elements())
}
// Value implements the driver.Valuer interface. It returns the JSON representation of the set.
func (s *BitSet[M]) Value() (driver.Value, error) {
return s.MarshalJSON()
}
// MarshalJSON implements json.Marshaler. It will marshal the set into a JSON array
// of the elements in the set in ascending order. If the set is empty an empty JSON
// array is returned.
func (s *BitSet[M]) MarshalJSON() ([]byte, error) {
if s.card == 0 {
return []byte("[]"), nil
}
d, err := json.Marshal(s.elements())
if err != nil {
return d, fmt.Errorf("marshaling bit set: %w", err)
}
return d, nil
}
// UnmarshalJSON implements json.Unmarshaler. It expects a JSON array of the
// elements in the set. The elements do not need to be sorted or unique. If the
// JSON is invalid, it returns an error and the set is left unchanged.
func (s *BitSet[M]) UnmarshalJSON(d []byte) error {
var t []M
if err := json.Unmarshal(d, &t); err != nil {
return fmt.Errorf("unmarshaling bit set: %w", err)
}
s.Clear()
for _, m := range t {
s.Add(m)
}
return nil
}
// Scan implements the sql.Scanner interface. It scans the value from the database into the set. It expects a JSON array
// of the elements in the set. If the JSON is invalid an error is returned. If the value is nil an empty set is
// returned.
func (s *BitSet[M]) Scan(src any) error {
return scanValue[M](src, s.Clear, s.UnmarshalJSON)
}
// Union implements Unioner: when other is also a *BitSet[M] it returns the word-wise union
// (combining 64 elements per operation) and true; otherwise it returns nil and false. Prefer the
// package-level Union function, which uses this automatically and handles the fallback.
func (s *BitSet[M]) Union(other Set[M]) (Set[M], bool) {
o, ok := other.(*BitSet[M])
if !ok {
return nil, false
}
return s.union(o), true
}
// Intersection implements Intersectioner: when other is also a *BitSet[M] it returns the word-wise
// intersection and true; otherwise it returns nil and false. Prefer the package-level Intersection
// function, which uses this automatically and handles the fallback.
func (s *BitSet[M]) Intersection(other Set[M]) (Set[M], bool) {
o, ok := other.(*BitSet[M])
if !ok {
return nil, false
}
return s.intersect(o), true
}
// Difference implements Differencer: when other is also a *BitSet[M] it returns the word-wise
// difference and true; otherwise it returns nil and false. Prefer the package-level Difference
// function, which uses this automatically and handles the fallback.
func (s *BitSet[M]) Difference(other Set[M]) (Set[M], bool) {
o, ok := other.(*BitSet[M])
if !ok {
return nil, false
}
return s.difference(o), true
}
// SymmetricDifference implements SymmetricDifferencer: when other is also a *BitSet[M] it returns
// the word-wise symmetric difference and true; otherwise it returns nil and false. Prefer the
// package-level SymmetricDifference function, which uses this automatically and handles the fallback.
func (s *BitSet[M]) SymmetricDifference(other Set[M]) (Set[M], bool) {
o, ok := other.(*BitSet[M])
if !ok {
return nil, false
}
return s.symmetricDifference(o), true
}
// Max implements Maxer: it returns the largest element by scanning backwards from the end of the
// span for the highest set bit. The second return value is false if the set is empty. Prefer the
// package-level Max function, which uses this automatically.
func (s *BitSet[M]) Max() (M, bool) {
if s == nil || s.card == 0 {
var zero M
return zero, false
}
for i := len(s.words) - 1; i >= 0; i-- {
if w := s.words[i]; w != 0 {
b := 63 - bits.LeadingZeros64(w)
return fromUniverse[M]((s.start+uint64(i))<<6 | uint64(b)), true
}
}
var zero M
return zero, false
}
// Min implements Minner: it returns the smallest element by scanning forwards from the start of
// the span for the lowest set bit. The second return value is false if the set is empty. Prefer
// the package-level Min function, which uses this automatically.
func (s *BitSet[M]) Min() (M, bool) {
if s == nil || s.card == 0 {
var zero M
return zero, false
}
for i, w := range s.words {
if w != 0 {
b := bits.TrailingZeros64(w)
return fromUniverse[M]((s.start+uint64(i))<<6 | uint64(b)), true
}
}
var zero M
return zero, false
}
// word returns the word covering universe word index w, or 0 when w is outside the span.
func (s *BitSet[M]) word(w uint64) uint64 {
if w < s.start || w >= s.start+uint64(len(s.words)) {
return 0
}
return s.words[w-s.start]
}
// Equal implements Equaler: when other is also a *BitSet[M] it compares cardinalities and then
// words and reports handled; otherwise it reports false, false. Prefer the package-level Equal
// function, which uses this automatically and handles the fallback.
func (s *BitSet[M]) Equal(other Set[M]) (bool, bool) {
o, ok := other.(*BitSet[M])
if !ok || s == nil || o == nil { // typed-nil operands decline to the generic path
return false, false
}
if s.card != o.card {
return false, true
}
// Scanning only s's span suffices: if every word there matches, o's population within that
// span equals s.card == o.card, so o cannot hold bits outside it. Removes may leave zero
// edge words, so equal sets can have different spans — the missing-word-is-zero comparison
// handles that.
for i, w := range s.words {
if w != o.word(s.start+uint64(i)) {
return false, true
}
}
return true, true
}
// Disjoint implements Disjointer: when other is also a *BitSet[M] it ANDs the words where the two
// spans overlap and reports handled; otherwise it reports false, false. Prefer the package-level
// Disjoint function, which uses this automatically and handles the fallback.
func (s *BitSet[M]) Disjoint(other Set[M]) (bool, bool) {
o, ok := other.(*BitSet[M])
if !ok || s == nil || o == nil { // typed-nil operands decline to the generic path
return false, false
}
lo := max(s.start, o.start)
hi := min(s.start+uint64(len(s.words)), o.start+uint64(len(o.words))) // one past the overlap
for w := lo; w < hi; w++ {
if s.words[w-s.start]&o.words[w-o.start] != 0 {
return false, true
}
}
return true, true
}
// Subset implements Subsetter: when other is also a *BitSet[M] it reports whether the receiver
// has any bit not set in other (word-wise AND NOT) and handled; otherwise it reports false,
// false. Prefer the package-level Subset function, which uses this automatically and handles the
// fallback.
func (s *BitSet[M]) Subset(other Set[M]) (bool, bool) {
o, ok := other.(*BitSet[M])
if !ok || s == nil || o == nil { // typed-nil operands decline to the generic path
return false, false
}
if s.card > o.card {
return false, true
}
for i, w := range s.words {
if w&^o.word(s.start+uint64(i)) != 0 {
return false, true
}
}
return true, true
}
func (s *BitSet[M]) recount() {
s.card = 0
for _, w := range s.words {
s.card += bits.OnesCount64(w)
}
}
// merge returns a new BitSet covering the combined span of s and o, with each word
// initialized to s's bits combined with o's bits by op. The combined span can be
// much larger than either input's when the two sets are far apart (see the type
// comment on memory).
func (s *BitSet[M]) merge(o *BitSet[M], op func(a, b uint64) uint64) *BitSet[M] {
if len(s.words) == 0 {
return o.Clone().(*BitSet[M])
}
if len(o.words) == 0 {
return s.Clone().(*BitSet[M])
}
start := min(s.start, o.start)
end := max(s.start+uint64(len(s.words)), o.start+uint64(len(o.words)))
c := &BitSet[M]{words: make([]uint64, spanWords(start, end-1)), start: start}
copy(c.words[s.start-start:], s.words)
for i, w := range o.words {
j := o.start - start + uint64(i)
c.words[j] = op(c.words[j], w)
}
c.recount()
c.trim()
return c
}
func (s *BitSet[M]) union(o *BitSet[M]) *BitSet[M] {
return s.merge(o, func(a, b uint64) uint64 { return a | b })
}
func (s *BitSet[M]) symmetricDifference(o *BitSet[M]) *BitSet[M] {
return s.merge(o, func(a, b uint64) uint64 { return a ^ b })
}
func (s *BitSet[M]) intersect(o *BitSet[M]) *BitSet[M] {
c := &BitSet[M]{}
if len(s.words) == 0 || len(o.words) == 0 {
return c
}
start := max(s.start, o.start)
end := min(s.start+uint64(len(s.words)), o.start+uint64(len(o.words)))
if end <= start {
return c
}
c.words = make([]uint64, end-start) // bounded by the smaller input, no overflow
c.start = start
for i := range c.words {
c.words[i] = s.words[start-s.start+uint64(i)] & o.words[start-o.start+uint64(i)]
}
c.recount()
c.trim()
return c
}
func (s *BitSet[M]) difference(o *BitSet[M]) *BitSet[M] {
c := s.Clone().(*BitSet[M])
if len(c.words) == 0 || len(o.words) == 0 {
return c
}
start := max(s.start, o.start)
end := min(s.start+uint64(len(s.words)), o.start+uint64(len(o.words)))
for w := start; w < end; w++ {
c.words[w-c.start] &^= o.words[w-o.start]
}
c.recount()
c.trim()
return c
}