-
Notifications
You must be signed in to change notification settings - Fork 661
/
big_bit_set.go
87 lines (73 loc) · 2.09 KB
/
big_bit_set.go
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
// Copyright (C) 2019-2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package ids
import (
"fmt"
"math/big"
"math/bits"
)
// BigBitSet is a bit-set backed by a big.Int
// Holds values ranging from [0, INT_MAX] (arch-dependent)
// Trying to use negative values will result in a panic.
// This implementation is NOT thread-safe.
type BigBitSet struct {
bits *big.Int
}
// NewBigBitSet returns a new instance of BigBitSet with [bits] set to 1.
//
// Invariants:
// 1. Negative bits will cause a panic.
// 2. Duplicate bits are allowed but will cause a no-op.
func NewBigBitSet(bits ...int) BigBitSet {
b := BigBitSet{new(big.Int)}
for _, bit := range bits {
b.Add(bit)
}
return b
}
// Add sets the [i]'th bit to 1
func (b BigBitSet) Add(i int) {
b.bits.SetBit(b.bits, i, 1)
}
// Union performs the set union with another set.
// This adds all elements in [other] to [b]
func (b BigBitSet) Union(other BigBitSet) {
b.bits.Or(b.bits, other.bits)
}
// Intersection performs the set intersection with another set
// This sets [b] to include only elements in both [b] and [other]
func (b BigBitSet) Intersection(other BigBitSet) {
b.bits.And(b.bits, other.bits)
}
// Difference removes all the elements in [other] from this set
func (b BigBitSet) Difference(other BigBitSet) {
b.bits.AndNot(b.bits, other.bits)
}
// Remove sets the [i]'th bit to 0
func (b BigBitSet) Remove(i int) {
b.bits.SetBit(b.bits, i, 0)
}
// Clear empties out the bitset
func (b BigBitSet) Clear() {
b.bits.SetUint64(0)
}
// Contains returns true if the [i]'th bit is 1, and false otherwise
func (b BigBitSet) Contains(i int) bool {
return b.bits.Bit(i) == 1
}
// Len returns the bit length of this bitset
func (b BigBitSet) Len() int {
return b.bits.BitLen()
}
// HammingWeight returns the amount of 1's in the bitset
func (b BigBitSet) HammingWeight() int {
result := 0
for _, word := range b.bits.Bits() {
result += bits.OnesCount(uint(word))
}
return result
}
// String returns the hex representation of this bitset
func (b BigBitSet) String() string {
return fmt.Sprintf("%x", b.bits.Bytes())
}