README.md
1.94 Kb · 61 lines
Bitset Package
Package implements an arbitrary-size bit set, also known as bit array.
Bit sets are useful when you need a compact way to track large sets of boolean flags, such as permissions, feature toggles, or membership sets, using significantly less memory than a slice of booleans while also supporting fast bulk operations across entire sets.
API
New(size uint64) BitSet- Returns a new BitSet pre-allocated forsizebitsBitSet.Set(i uint64)- Turn on the bit at positioniBitSet.Clear(i uint64)- Turn off the bit at positioniBitSet.ClearAll()- Turn off all bitsBitSet.Compact()- Reclaim memory by removing trailing zero wordsBitSet.IsSet(i uint64) bool- Check whether the bit at positioniis setBitSet.Size() int- Return the total number of bits currently allocatedBitSet.Len() int- Return the number of set bitsBitSet.And(other BitSet)- In-place intersection with another setBitSet.Or(other BitSet)- In-place union with another setBitSet.Xor(other BitSet)- In-place symmetric difference with another setBitSet.Equal(other BitSet) bool- Check whether two sets have the same bits setBitSet.String() string- Return a binary (MSB-first) representation of the setBitSet.PaddedString() string- Return a zero-padded binary (MSB-first) representation of the set
Usage
1package main
2
3import "gno.land/p/jeronimoalbi/bitset"
4
5const (
6 PermRead = 0
7 PermWrite = 1
8 PermDelete = 2
9 PermAdmin = 3
10)
11
12func main() {
13 var perms bitset.BitSet
14 perms.Set(PermRead)
15 perms.Set(PermWrite)
16
17 println("Can read:", perms.IsSet(PermRead))
18 println("Can write:", perms.IsSet(PermWrite))
19 println("Can delete:", perms.IsSet(PermDelete))
20 println("Is admin:", perms.IsSet(PermAdmin))
21 println("Permissions set:", perms.Len())
22}
23
24// Output:
25// Can read: true
26// Can write: true
27// Can delete: false
28// Is admin: false
29// Permissions set: 2