### Installing the BitSet Library in Go Source: https://github.com/bits-and-blooms/bitset/blob/master/README.md Standard Go command to fetch and install the bitset library into your project's GOPATH. ```bash go get github.com/bits-and-blooms/bitset ``` -------------------------------- ### GetWord64AtBit - Read 64 consecutive bits as a uint64 Source: https://context7.com/bits-and-blooms/bitset/llms.txt Retrieves the 64-bit window starting at bit index `i`, spanning word boundaries when necessary. ```APIDOC ## GetWord64AtBit ### Description Retrieves the 64-bit window starting at bit index `i`, spanning word boundaries when necessary. ### Method `GetWord64AtBit(i uint) uint64` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go b := bitset.New(128) b.Set(0).Set(63).Set(64) word := b.GetWord64AtBit(0) fmt.Printf("bits 0-63: %064b\n", word) // bit 0 and bit 63 are set ``` ### Response #### Success Response (200) Returns a `uint64` representing the 64 bits starting from index `i`. #### Response Example None provided. ``` -------------------------------- ### Iterate Over Set Bits Source: https://context7.com/bits-and-blooms/bitset/llms.txt Use `NextSet` in a loop to efficiently iterate over all set bits starting from a given index. It returns the index of the next set bit and a boolean indicating if a set bit was found. ```go b := bitset.New(200) b.Set(5).Set(42).Set(100).Set(199) for i, ok := b.NextSet(0); ok; i, ok = b.NextSet(i + 1) { fmt.Println("set bit:", i) } // Output: // set bit: 5 // set bit: 42 // set bit: 100 // set bit: 199 ``` -------------------------------- ### Flip Range of Bits Source: https://context7.com/bits-and-blooms/bitset/llms.txt Use `FlipRange` to toggle all bits within the half-open interval `[start, end)`. This is efficient for inverting multiple bits simultaneously. ```go b := bitset.New(16) b.FlipRange(4, 12) // set bits 4..11 fmt.Println(b.Count()) // 8 b.FlipRange(4, 8) // unset bits 4..7 fmt.Println(b.Count()) // 4 (bits 8..11 remain) ``` -------------------------------- ### PreviousSet - Reverse Iteration Over Set Bits Source: https://context7.com/bits-and-blooms/bitset/llms.txt Scans for set bits starting from a given index and moving downwards towards zero. Useful for reverse traversal. ```go b := bitset.New(100) b.Set(10).Set(25).Set(50).Set(75) // Walk backwards from bit 60 for i, ok := b.PreviousSet(60); ok; i, ok = b.PreviousSet(i - 1) { fmt.Println("previous set:", i) if i == 0 { break } } // Output: // previous set: 50 // previous set: 25 // previous set: 10 ``` -------------------------------- ### FlipRange - Toggle a range of bits Source: https://context7.com/bits-and-blooms/bitset/llms.txt Flips all bits in the half-open interval `[start, end)`. ```APIDOC ## FlipRange ### Description Flips all bits in the half-open interval `[start, end)`. ### Method `FlipRange(start, end uint)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go b := bitset.New(16) b.FlipRange(4, 12) // set bits 4..11 fmt.Println(b.Count()) // 8 b.FlipRange(4, 8) // unset bits 4..7 fmt.Println(b.Count()) // 4 (bits 8..11 remain) ``` ### Response #### Success Response (200) None explicitly documented, but the operation modifies the BitSet in place. #### Response Example None provided. ``` -------------------------------- ### PreviousSet / PreviousClear Source: https://context7.com/bits-and-blooms/bitset/llms.txt Scans for set or clear bits starting from a given index and moving downwards towards zero. ```APIDOC ## PreviousSet / PreviousClear — reverse iteration ### Description Scan set or clear bits from a starting index downward toward zero. ### Method `PreviousSet(i uint) (uint, bool)` `PreviousClear(i uint) (uint, bool)` ### Parameters #### Path Parameters - `i` (uint) - The index to start searching from. ### Request Example ```go b := bitset.New(100) b.Set(10).Set(25).Set(50).Set(75) // Walk backwards from bit 60 for i, ok := b.PreviousSet(60); ok; i, ok = b.PreviousSet(i - 1) { fmt.Println("previous set:", i) if i == 0 { break } } ``` ### Response #### Success Response - `i` (uint) - The index of the previous set or clear bit. - `ok` (bool) - True if a set or clear bit was found, false otherwise. ``` -------------------------------- ### Read 64 Consecutive Bits Source: https://context7.com/bits-and-blooms/bitset/llms.txt The `GetWord64AtBit` method retrieves a 64-bit unsigned integer representing the bits starting at index `i`. It handles word boundaries correctly, allowing access to contiguous bit segments. ```go b := bitset.New(128) b.Set(0).Set(63).Set(64) word := b.GetWord64AtBit(0) fmt.Printf("bits 0-63: %064b\n", word) // bit 0 and bit 63 are set ``` -------------------------------- ### Basic BitSet Usage and Chaining in Go Source: https://github.com/bits-and-blooms/bitset/blob/master/README.md Demonstrates fundamental BitSet operations like setting, testing, clearing bits, and chaining methods. Also shows iteration over set bits and intersection operations. Requires Go 1.23+ for `EachSet()`. ```go package main import ( "fmt" "math/rand" "github.com/bits-and-blooms/bitset" ) func main() { fmt.Printf("Hello from BitSet!\n") var b bitset.BitSet // play some Go Fish for i := 0; i < 100; i++ { card1 := uint(rand.Intn(52)) card2 := uint(rand.Intn(52)) b.Set(card1) if b.Test(card2) { fmt.Println("Go Fish!") } b.Clear(card1) } // Chaining b.Set(10).Set(11) for i, e := b.NextSet(0); e; i, e = b.NextSet(i + 1) { fmt.Println("The following bit is set:", i) } if b.Intersection(bitset.New(100).Set(10)).Count() == 1 { fmt.Println("Intersection works.") } else { fmt.Println("Intersection doesn't work???") } } ``` -------------------------------- ### New - Create a BitSet with a capacity hint Source: https://context7.com/bits-and-blooms/bitset/llms.txt Allocates a new *BitSet pre-sized for at least `length` bits. The hint avoids reallocations when the maximum bit index is known upfront. On allocation failure it returns a zero-capacity BitSet rather than panicking. ```APIDOC ## New ### Description Allocates a new `*BitSet` pre-sized for at least `length` bits. The hint avoids reallocations when the maximum bit index is known upfront. On allocation failure it returns a zero-capacity BitSet rather than panicking. ### Method `New(length uint)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "github.com/bits-and-blooms/bitset" ) func main() { // Hint that we'll use up to 1000 bits b := bitset.New(1000) b.Set(42).Set(100).Set(999) fmt.Println(b.Test(42)) // true fmt.Println(b.Test(43)) // false fmt.Println(b.Len()) // 1000 fmt.Println(b.Count()) // 3 } ``` ### Response #### Success Response (200) Returns a pointer to a new `BitSet`. #### Response Example None provided. ``` -------------------------------- ### Create BitSet with Capacity Hint Source: https://context7.com/bits-and-blooms/bitset/llms.txt Use `bitset.New` to pre-allocate a BitSet with a capacity hint, avoiding reallocations if the maximum bit index is known. Returns a zero-capacity BitSet on allocation failure. ```go package main import ( "fmt" "github.com/bits-and-blooms/bitset" ) func main() { // Hint that we'll use up to 1000 bits b := bitset.New(1000) b.Set(42).Set(100).Set(999) fmt.Println(b.Test(42)) // true fmt.Println(b.Test(43)) // false fmt.Println(b.Len()) // 1000 fmt.Println(b.Count()) // 3 } ``` -------------------------------- ### Run All Tests in Go Source: https://github.com/bits-and-blooms/bitset/blob/master/README.md Execute all tests for the project and check code coverage. Ensure these commands pass before committing code. ```bash go test ``` ```bash go test -cover ``` -------------------------------- ### Converting Between BitSet and Roaring Bitmaps in Go Source: https://github.com/bits-and-blooms/bitset/blob/master/README.md Illustrates how to convert between the library's BitSet and compressed Roaring bitmaps using provided helper functions. This is useful for managing memory with large sets of bits. ```go mybitset := roaringbitmap.ToBitSet() newroaringbitmap := roaring.FromBitSet(mybitset) ``` -------------------------------- ### BitSet Serialization to Bytes in Go Source: https://github.com/bits-and-blooms/bitset/blob/master/README.md Shows how to serialize a BitSet to a byte buffer using `WriteTo` and deserialize it back using `ReadFrom`. It's recommended to wrap streams with `bufio` for better performance when dealing with files or network connections. ```go const length = 9585 const oneEvery = 97 bs := bitset.New(length) // Add some bits for i := uint(0); i < length; i += oneEvery { bs = bs.Set(i) } var buf bytes.Buffer n, err := bs.WriteTo(&buf) if err != nil { // failure } // Here n == buf.Len() ``` ```go // Read back from buf bs = bitset.New() n, err = bs.ReadFrom(&buf) if err != nil { // error } // n is the number of bytes read ``` -------------------------------- ### MustNew - Create a BitSet, panicking on invalid size Source: https://context7.com/bits-and-blooms/bitset/llms.txt Like `New` but panics immediately if `length` exceeds the platform capacity, making allocation failures explicit. ```APIDOC ## MustNew ### Description Like `New` but panics immediately if `length` exceeds the platform capacity, making allocation failures explicit. ### Method `MustNew(length uint)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go b := bitset.MustNew(128) b.Set(0).Set(63).Set(127) fmt.Println(b.Count()) // 3 ``` ### Response #### Success Response (200) Returns a pointer to a new `BitSet`. #### Response Example None provided. ``` -------------------------------- ### Create BitSet and Panic on Invalid Size Source: https://context7.com/bits-and-blooms/bitset/llms.txt Use `bitset.MustNew` for creating a BitSet when allocation failure should result in a panic, making errors explicit. This is useful when a valid allocation is a strict requirement. ```go b := bitset.MustNew(128) b.Set(0).Set(63).Set(127) fmt.Println(b.Count()) // 3 ``` -------------------------------- ### Any, None, All - Existence Tests Source: https://context7.com/bits-and-blooms/bitset/llms.txt Efficiently checks if any bit is set, no bits are set, or all bits are set within the bitset. ```go b := bitset.New(8) fmt.Println(b.None()) // true (empty) fmt.Println(b.Any()) // false b.Set(3) fmt.Println(b.Any()) // true fmt.Println(b.None()) // false fmt.Println(b.All()) // false b.SetAll() fmt.Println(b.All()) // true ``` -------------------------------- ### From - Construct from a []uint64 word slice Source: https://context7.com/bits-and-blooms/bitset/llms.txt Wraps an existing slice of 64-bit words as a BitSet without copying. Changes to the slice after construction are reflected in the BitSet. Use `FromWithLength` when the logical bit length is smaller than `len(buf)*64`. ```APIDOC ## From ### Description Wraps an existing slice of 64-bit words as a BitSet without copying. Changes to the slice after construction are reflected in the BitSet. Use `FromWithLength` when the logical bit length is smaller than `len(buf)*64`. ### Method `From(buf []uint64)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Build a BitSet from raw 64-bit words words := []uint64{0b1010, 0b0001} // bits 1,3 and bit 64 are set b := bitset.From(words) fmt.Println(b.Test(1)) // true fmt.Println(b.Test(2)) // false fmt.Println(b.Test(64)) // true ``` ### Response #### Success Response (200) Returns a pointer to a new `BitSet` wrapping the provided `[]uint64` slice. #### Response Example None provided. ``` -------------------------------- ### WriteTo and ReadFrom for BitSet Serialization Source: https://context7.com/bits-and-blooms/bitset/llms.txt Serializes and deserializes a BitSet to/from binary streams. Wrap streams with `bufio` for optimal performance, especially with files or network connections. ```go import ( "bufio" "bytes" "fmt" "github.com/bits-and-blooms/bitset" "os" ) // --- Serialize --- bs := bitset.New(9585) for i := uint(0); i < 9585; i += 97 { bs.Set(i) } var buf bytes.Buffer n, err := bs.WriteTo(&buf) if err != nil { panic(err) } fmt.Printf("wrote %d bytes\n", n) // --- Deserialize --- restored := bitset.New(0) n, err = restored.ReadFrom(&buf) if err != nil { panic(err) } fmt.Println(restored.Equal(bs)) // true // --- File I/O with bufio --- f, _ := os.Create("bitset.bin") w := bufio.NewWriter(f) bs.WriteTo(w) w.Flush() f.Close() ``` -------------------------------- ### Construct BitSet from uint64 Slice Source: https://context7.com/bits-and-blooms/bitset/llms.txt Use `bitset.From` to wrap an existing `[]uint64` slice as a BitSet without copying. Changes to the underlying slice will affect the BitSet. Use `FromWithLength` if the logical bit length is less than `len(buf)*64`. ```go // Build a BitSet from raw 64-bit words words := []uint64{0b1010, 0b0001} // bits 1,3 and bit 64 are set b := bitset.From(words) fmt.Println(b.Test(1)) // true fmt.Println(b.Test(2)) // false fmt.Println(b.Test(64)) // true ``` -------------------------------- ### Any / None / All Source: https://context7.com/bits-and-blooms/bitset/llms.txt Efficiently tests whether any bit is set, no bit is set, or all bits are set within the bitset. ```APIDOC ## Any / None / All — existence tests ### Description Efficiently test whether any bit is set, no bit is set, or all bits are set. ### Method `Any() bool` `None() bool` `All() bool` ### Parameters None ### Request Example ```go b := bitset.New(8) fmt.Println(b.None()) // true (empty) fmt.Println(b.Any()) // false b.Set(3) fmt.Println(b.Any()) // true fmt.Println(b.None()) // false fmt.Println(b.All()) // false b.SetAll() fmt.Println(b.All()) // true ``` ### Response #### Success Response - `bool` - True if the condition (Any, None, or All) is met, false otherwise. ``` -------------------------------- ### Binary Marshaling and Unmarshaling Source: https://context7.com/bits-and-blooms/bitset/llms.txt Implement `encoding.BinaryMarshaler` and `encoding.BinaryUnmarshaler` for binary codecs like gob or encoding/binary. Ensure the same binary order is used for marshaling and unmarshaling. ```go bs := bitset.New(64).Set(7).Set(42).Set(63) data, err := bs.MarshalBinary() if err != nil { panic(err) } bs2 := bitset.New(0) if err := bs2.UnmarshalBinary(data); err != nil { panic(err) } fmt.Println(bs.Equal(bs2)) // true ``` -------------------------------- ### WriteTo / ReadFrom Source: https://context7.com/bits-and-blooms/bitset/llms.txt Serializes and deserializes a BitSet to/from a binary stream using `io.Writer` and `io.Reader`. Supports efficient file and network I/O when wrapped with `bufio`. ```APIDOC ## WriteTo / ReadFrom ### Description Serializes and deserializes a BitSet to/from any `io.Writer`/`io.Reader` in a portable binary format (8-byte length header + word data). Wrap streams in `bufio` for best performance with files or network connections. ### Method `WriteTo(w io.Writer) (n int64, err error)` `ReadFrom(r io.Reader) (n int64, err error)` ### Example ```go import ( "bufio" "bytes" "fmt" "github.com/bits-and-blooms/bitset" "os" ) // --- Serialize --- bs := bitset.New(9585) for i := uint(0); i < 9585; i += 97 { bs.Set(i) } var buf bytes.Buffer n, err := bs.WriteTo(&buf) if err != nil { panic(err) } fmt.Printf("wrote %d bytes\n", n) // --- Deserialize --- restored := bitset.New(0) n, err = restored.ReadFrom(&buf) if err != nil { panic(err) } fmt.Println(restored.Equal(bs)) // true // --- File I/O with bufio --- f, _ := os.Create("bitset.bin") w := bufio.NewWriter(f) bs.WriteTo(w) w.Flush() f.Close() ``` ``` -------------------------------- ### Copy and CopyFull for BitSet Data Transfer Source: https://context7.com/bits-and-blooms/bitset/llms.txt Copies bits into an existing BitSet. `Copy` copies up to the minimum length of source and destination, while `CopyFull` ensures the destination becomes identical to the source, reallocating if needed. ```go src := bitset.New(64).Set(10).Set(20) dst := bitset.New(64) src.CopyFull(dst) fmt.Println(dst.Equal(src)) // true ``` -------------------------------- ### Replace Backing Storage In-Place Source: https://context7.com/bits-and-blooms/bitset/llms.txt Replaces the BitSet's internal storage with the provided `[]uint64` without allocation. Useful when the backing array is managed externally (e.g., memory-mapped files). ```go b := bitset.New(0) data := []uint64{0b111, 0b101} b.SetBitsetFrom(data) fmt.Println(b.String()) // {0,1,2,64,66} ``` -------------------------------- ### Control Binary Byte Order (Endianness) Source: https://context7.com/bits-and-blooms/bitset/llms.txt Configure the byte order for `WriteTo`/`ReadFrom` and binary marshaling. The default is big-endian. Both the writer and reader must use the same order. Use `defer bitset.BigEndian()` to restore the default after switching. ```go bitset.LittleEndian() // switch to little-endian default bitset.BigEndian() // restore default bs := bitset.New(64).Set(0).Set(63) data, _ := bs.MarshalBinary() bs2 := bitset.New(0) bitset.LittleEndian() bs2.UnmarshalBinary(data) fmt.Println(bs.Equal(bs2)) // true ``` -------------------------------- ### Complement Source: https://context7.com/bits-and-blooms/bitset/llms.txt Returns a new BitSet with all bits flipped up to the current `Len()`. ```APIDOC ## Complement ### Description Returns a new BitSet with all bits flipped up to the current `Len()`. ### Method `Complement() *BitSet` ### Example ```go b := bitset.New(8) b.Set(0).Set(2).Set(4).Set(6) c := b.Complement() fmt.Println(c.String()) // {1,3,5,7} ``` ``` -------------------------------- ### JSON Marshaling and Unmarshaling Source: https://context7.com/bits-and-blooms/bitset/llms.txt Implements `encoding.json` interfaces using base64 encoding. By default, URL encoding is used; switch to standard encoding with `bitset.Base64StdEncoding()` if needed. Ensure the same encoding is used for marshaling and unmarshaling. ```go import ( "encoding/json" "fmt" "github.com/bits-and-blooms/bitset" ) type Config struct { Features bitset.BitSet `json:"features"` } bs := bitset.New(32) bs.Set(0).Set(5).Set(31) // feature flags 0, 5, 31 cfg := Config{Features: *bs} data, _ := json.Marshal(cfg) fmt.Println(string(data)) // {"features":"AAAAAAAAAAABAAACAAAAAA=="} (example) var cfg2 Config json.Unmarshal(data, &cfg2) fmt.Println(cfg2.Features.Equal(bs)) // true ``` -------------------------------- ### SetBitsetFrom Source: https://context7.com/bits-and-blooms/bitset/llms.txt Replaces the BitSet's internal storage in-place with a provided `[]uint64` slice. ```APIDOC ## SetBitsetFrom ### Description Replaces the BitSet's internal storage with the provided `[]uint64` without allocation. Useful when the backing array is managed externally (e.g., memory-mapped files). ### Method `SetBitsetFrom(words []uint64)` ### Request Example ```go b := bitset.New(0) data := []uint64{0b111, 0b101} b.SetBitsetFrom(data) fmt.Println(b.String()) // {0,1,2,64,66} ``` ``` -------------------------------- ### Mutate Single Bit with Chaining Source: https://context7.com/bits-and-blooms/bitset/llms.txt Demonstrates chaining of `Set`, `Flip`, and `Clear` methods for efficient bit manipulation. `Set` grows the set, `Clear` never reallocates, and `Flip` toggles the bit's state. All return `*BitSet`. ```go b := bitset.New(64) // Chaining b.Set(10).Set(20).Flip(10).Clear(20) fmt.Println(b.Test(10)) // false (was set, then flipped off) fmt.Println(b.Test(20)) // false (was set, then cleared) fmt.Println(b.Test(0)) // false ``` -------------------------------- ### Direct Access to Internal Word Slice Source: https://context7.com/bits-and-blooms/bitset/llms.txt Returns the backing `[]uint64` slice without copying. Mutations to the returned slice directly affect the BitSet. Intended for advanced users implementing custom bulk operations. ```go b := bitset.New(128).Set(0).Set(64) words := b.Words() fmt.Printf("word[0]=%d word[1]=%d\n", words[0], words[1]) // 1 1 words[0] = 0xFF // directly clears/sets bits 0-7 fmt.Println(b.Count()) // 9 (8 bits from 0xFF + bit 64) ``` -------------------------------- ### Rank and Select - Order-Statistics Operations Source: https://context7.com/bits-and-blooms/bitset/llms.txt Rank(i) counts set bits up to index i. Select(j) finds the index of the j-th set bit. ```go b := bitset.New(64) b.Set(5).Set(15).Set(25).Set(35) fmt.Println(b.Rank(15)) // 2 (bits 5 and 15 are set at or before index 15) fmt.Println(b.Select(0)) // 5 (0th set bit) fmt.Println(b.Select(2)) // 25 (2nd set bit) ``` -------------------------------- ### LittleEndian / BigEndian / BinaryOrder Source: https://context7.com/bits-and-blooms/bitset/llms.txt Configure the byte order used for WriteTo/ReadFrom and binary marshaling. Defaults to big-endian. ```APIDOC ## LittleEndian / BigEndian / BinaryOrder ### Description Configure the byte order used for `WriteTo`/`ReadFrom` and binary marshaling. Default is big-endian. Both writer and reader must use the same order. ### Method `LittleEndian()` `BigEndian()` `BinaryOrder(order binary.ByteOrder)` ### Request Example ```go bitset.LittleEndian() // switch to little-endian default defer bitset.BigEndian() // restore default bs := bitset.New(64).Set(0).Set(63) data, _ := bs.MarshalBinary() bs2 := bitset.New(0) bitset.LittleEndian() bs2.UnmarshalBinary(data) fmt.Println(bs.Equal(bs2)) // true ``` ``` -------------------------------- ### Copy / CopyFull Source: https://context7.com/bits-and-blooms/bitset/llms.txt Copies bits from a source BitSet to a destination BitSet. `Copy` copies up to the minimum length of the two sets, while `CopyFull` ensures the destination becomes identical to the source, reallocating if necessary. ```APIDOC ## Copy / CopyFull ### Description Copies bits from a source BitSet into a destination BitSet. `Copy` copies up to `min(src.Len(), dst.Len())` bits. `CopyFull` makes `dst` identical to `src`, reallocating if necessary. ### Method `Copy(src *BitSet)` `CopyFull(dst *BitSet)` ### Example ```go src := bitset.New(64).Set(10).Set(20) dst := bitset.New(64) src.CopyFull(dst) fmt.Println(dst.Equal(src)) // true ``` ``` -------------------------------- ### Switch JSON to Standard Base64 Encoding Source: https://context7.com/bits-and-blooms/bitset/llms.txt Switches JSON marshaling from URL-safe base64 (`base64.URLEncoding`) to standard base64 (`base64.StdEncoding`). This affects the characters used for encoding. ```go bitset.Base64StdEncoding() bs := bitset.New(8).Set(3) data, _ := bs.MarshalJSON() fmt.Println(string(data)) // uses standard alphabet (+/ instead of -_) ``` -------------------------------- ### Shrink / Compact Source: https://context7.com/bits-and-blooms/bitset/llms.txt Reduces memory usage by trimming the backing slice. `Shrink` takes the highest bit index, while `Compact` automatically finds it. ```APIDOC ## Shrink / Compact ### Description Reduces memory usage by trimming the backing slice so that `lastbitindex` is the highest addressable bit. `Compact` automatically finds the highest set bit and calls `Shrink`. ### Method `Shrink(lastbitindex uint)` `Compact()` ### Example ```go b := bitset.New(100000) b.Set(10).Set(20) b.Compact() // releases memory, new length = 21 fmt.Println(b.Len()) // 21 fmt.Println(b.Count()) // 2 ``` ``` -------------------------------- ### NextSetMany - Retrieve Multiple Set Bits Source: https://context7.com/bits-and-blooms/bitset/llms.txt Efficiently retrieves multiple set bits at once into a reusable buffer. More performant than repeated NextSet calls for bulk processing. ```go b := bitset.New(1000) for i := uint(0); i < 1000; i += 7 { b.Set(i) } buffer := make([]uint, 64) // reuse this buffer for j, buf := b.NextSetMany(0, buffer); len(buf) > 0; j, buf = b.NextSetMany(j+1, buffer) { for _, bit := range buf { _ = bit // process each set bit } } fmt.Println("total set bits:", b.Count()) // 143 ``` -------------------------------- ### Shrink and Compact for Memory Management Source: https://context7.com/bits-and-blooms/bitset/llms.txt Reduces memory usage by trimming the backing slice. `Compact` automatically finds the highest set bit and shrinks. ```go b := bitset.New(100000) b.Set(10).Set(20) b.Compact() // releases memory, new length = 21 fmt.Println(b.Len()) // 21 fmt.Println(b.Count()) // 2 ``` -------------------------------- ### AppendTo and AsSlice - Collect Set Bits Source: https://context7.com/bits-and-blooms/bitset/llms.txt Collects all set bit indices into a slice. AppendTo grows the slice as needed, while AsSlice uses a pre-allocated buffer. ```go b := bitset.New(64) b.Set(0).Set(7).Set(63) // AppendTo — grows the slice as needed all := b.AppendTo(nil) fmt.Println(all) // [0 7 63] // AsSlice — no allocation, caller provides capacity buf := make([]uint, b.Count()) result := b.AsSlice(buf) fmt.Println(result) // [0 7 63] ``` -------------------------------- ### EachSet - Go 1.23 Range Iterator for Set Bits Source: https://context7.com/bits-and-blooms/bitset/llms.txt Provides an iter.Seq[uint] for use with Go 1.23+ for-range loops, iterating over all set bits. ```go //go:build go1.23 b := bitset.New(100) b.Set(1).Set(5).Set(99) for bit := range b.EachSet() { fmt.Println(bit) } // Output: 1 5 99 ``` -------------------------------- ### Raw Binary Dump Source: https://context7.com/bits-and-blooms/bitset/llms.txt Returns the internal word representation as a binary string. The most significant word is printed first, and index 0 is at the right end. Useful for low-level debugging. ```go b := bitset.New(8).Set(0).Set(7) fmt.Println(b.DumpAsBits()) // 0000000000000000000000000000000000000000000000000000000010000001. ``` -------------------------------- ### DumpAsBits Source: https://context7.com/bits-and-blooms/bitset/llms.txt Returns the internal word representation as a binary string, useful for low-level debugging. ```APIDOC ## DumpAsBits ### Description Returns the internal word representation as a binary string, with the most significant word printed first and index 0 at the right end. Useful for low-level debugging. ### Method `DumpAsBits() string` ### Request Example ```go b := bitset.New(8).Set(0).Set(7) fmt.Println(b.DumpAsBits()) // 0000000000000000000000000000000000000000000000000000000010000001. ``` ### Response - `string`: A binary string representation of the internal word storage. ``` -------------------------------- ### Words Source: https://context7.com/bits-and-blooms/bitset/llms.txt Provides direct access to the internal `[]uint64` slice, allowing in-place mutations. ```APIDOC ## Words ### Description Returns the backing `[]uint64` slice without copying. Mutations to the returned slice directly affect the BitSet. Intended for advanced users implementing custom bulk operations. ### Method `Words() []uint64` ### Request Example ```go b := bitset.New(128).Set(0).Set(64) words := b.Words() fmt.Printf("word[0]=%d word[1]=%d\n", words[0], words[1]) // 1 1 words[0] = 0xFF // directly clears/sets bits 0-7 fmt.Println(b.Count()) // 9 (8 bits from 0xFF + bit 64) ``` ### Response - `[]uint64`: The internal slice representing the bit storage. ``` -------------------------------- ### String Source: https://context7.com/bits-and-blooms/bitset/llms.txt Returns a human-readable string representation of the set bit indices, e.g., {1,5,42}. ```APIDOC ## String ### Description Returns the set bit indices surrounded by braces, e.g. `{1,5,42}`. Truncated at 262144 bits to prevent memory exhaustion. ### Method `String() string` ### Request Example ```go b := bitset.New(10).Set(1).Set(5).Set(9) fmt.Println(b.String()) // {1,5,9} ``` ### Response - `string`: A string representation of the set bits. ``` -------------------------------- ### Rank / Select Source: https://context7.com/bits-and-blooms/bitset/llms.txt Provides order-statistics operations. `Rank(i)` counts set bits up to index `i`, and `Select(j)` finds the index of the j-th set bit. ```APIDOC ## Rank / Select — order-statistics operations ### Description `Rank(i)` returns how many bits are set at positions 0..i (inclusive). `Select(j)` returns the index of the j-th set bit (0-based). ### Method `Rank(i uint) uint` `Select(j uint) (uint, bool)` ### Parameters #### Path Parameters - `i` (uint) - The index up to which to count set bits (for `Rank`). - `j` (uint) - The 0-based index of the set bit to find (for `Select`). ### Request Example ```go b := bitset.New(64) b.Set(5).Set(15).Set(25).Set(35) fmt.Println(b.Rank(15)) // 2 (bits 5 and 15 are set at or before index 15) fmt.Println(b.Select(0)) // 5 (0th set bit) fmt.Println(b.Select(2)) // 25 (2nd set bit) ``` ### Response #### Success Response - `Rank` returns `uint` - The number of set bits up to index `i`. - `Select` returns `(uint, bool)` - The index of the j-th set bit and true if found, or 0 and false if not found. ``` -------------------------------- ### Set / Clear / Flip - Mutate a single bit Source: https://context7.com/bits-and-blooms/bitset/llms.txt `Set(i)` sets bit `i` to 1, auto-growing the set. `Clear(i)` sets bit `i` to 0 (never reallocates). `Flip(i)` toggles bit `i`. All three return `*BitSet` for chaining. ```APIDOC ## Set / Clear / Flip ### Description `Set(i)` sets bit `i` to 1, auto-growing the set. `Clear(i)` sets bit `i` to 0 (never reallocates). `Flip(i)` toggles bit `i`. All three return `*BitSet` for chaining. ### Method `Set(i uint) *BitSet` `Clear(i uint) *BitSet` `Flip(i uint) *BitSet` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go b := bitset.New(64) // Chaining b.Set(10).Set(20).Flip(10).Clear(20) fmt.Println(b.Test(10)) // false (was set, then flipped off) fmt.Println(b.Test(20)) // false (was set, then cleared) fmt.Println(b.Test(0)) // false ``` ### Response #### Success Response (200) Returns the `*BitSet` receiver for chaining. #### Response Example None provided. ``` -------------------------------- ### Clone BitSet for Independent Copying Source: https://context7.com/bits-and-blooms/bitset/llms.txt Returns an independent deep copy of the BitSet. Changes to the clone do not affect the original. ```go a := bitset.New(64).Set(1).Set(2).Set(3) b := a.Clone() b.Set(4) // does not affect a fmt.Println(a.Count()) // 3 fmt.Println(b.Count()) // 4 ``` -------------------------------- ### AppendTo / AsSlice Source: https://context7.com/bits-and-blooms/bitset/llms.txt Collects all set bit indices into a slice. `AppendTo` grows the slice as needed, while `AsSlice` requires a pre-allocated slice. ```APIDOC ## AppendTo / AsSlice — collect all set bits into a slice ### Description `AppendTo` appends all set bit indices to an existing slice. `AsSlice` writes them into a pre-allocated slice (panics if too small). ### Method `AppendTo(slice []uint) []uint` `AsSlice(slice []uint) []uint` ### Parameters #### Path Parameters - `slice` ([]uint) - The slice to append to or write into. ### Request Example ```go b := bitset.New(64) b.Set(0).Set(7).Set(63) // AppendTo — grows the slice as needed all := b.AppendTo(nil) fmt.Println(all) // [0 7 63] // AsSlice — no allocation, caller provides capacity buf := make([]uint, b.Count()) result := b.AsSlice(buf) fmt.Println(result) // [0 7 63] ``` ### Response #### Success Response - `[]uint` - A slice containing the indices of all set bits. ``` -------------------------------- ### EachSet Source: https://context7.com/bits-and-blooms/bitset/llms.txt Provides a Go 1.23 range-over-function iterator for all set bits. ```APIDOC ## EachSet — Go 1.23 range-over-function iterator ### Description Returns an `iter.Seq[uint]` that can be used directly in a `for range` loop (requires Go 1.23+). ### Method `EachSet() iter.Seq[uint]` ### Parameters None ### Request Example ```go //go:build go1.23 b := bitset.New(100) b.Set(1).Set(5).Set(99) for bit := range b.EachSet() { fmt.Println(bit) } ``` ### Response #### Success Response - `iter.Seq[uint]` - An iterator that yields the indices of all set bits. ``` -------------------------------- ### InsertAt and DeleteAt for Structural Bit Manipulation Source: https://context7.com/bits-and-blooms/bitset/llms.txt Inserts a 0 bit at a position, shifting higher bits left, or deletes a bit, shifting higher bits right. Use for dynamic set modifications. ```go b := bitset.New(8) b.Set(0).Set(1).Set(2) // {0,1,2} b.InsertAt(1) // insert 0 at position 1; old bit-1 becomes bit-2 fmt.Println(b.String()) // {0,2,3} b.DeleteAt(0) // remove position 0; all bits shift right by 1 fmt.Println(b.String()) // {1,2} ``` -------------------------------- ### Cap Source: https://context7.com/bits-and-blooms/bitset/llms.txt Returns the maximum addressable bit index for the current platform. ```APIDOC ## Cap ### Description Returns the largest bit index the platform can address (`^uint(0)`). Useful for range validation before passing user input to `Set`. ### Method `Cap() uint64` ### Request Example ```go fmt.Printf("max bit index: %d\n", bitset.Cap()) // 64-bit: max bit index: 18446744073709551615 // 32-bit: max bit index: 4294967295 ``` ### Response - `uint64`: The maximum addressable bit index. ``` -------------------------------- ### NextSetMany Source: https://context7.com/bits-and-blooms/bitset/llms.txt Retrieves multiple set bits at once, filling a reusable buffer. This is more efficient than repeated `NextSet` calls for bulk processing. ```APIDOC ## NextSetMany — retrieve multiple set bits at once ### Description Fills a reusable buffer with up to `cap(buffer)` set bits starting from index `i`. More efficient than repeated `NextSet` calls for bulk processing. ### Method `NextSetMany(i uint, buffer []uint) (uint, []uint)` ### Parameters #### Path Parameters - `i` (uint) - The starting index to search for set bits. - `buffer` ([]uint) - A reusable buffer to fill with set bit indices. ### Request Example ```go b := bitset.New(1000) for i := uint(0); i < 1000; i += 7 { b.Set(i) } buffer := make([]uint, 64) // reuse this buffer for j, buf := b.NextSetMany(0, buffer); len(buf) > 0; j, buf = b.NextSetMany(j+1, buffer) { for _, bit := range buf { _ = bit // process each set bit } } ``` ### Response #### Success Response - `j` (uint) - The index after the last bit found in the buffer. - `buf` ([]uint) - A slice containing the indices of the set bits found, up to the capacity of the provided buffer. ``` -------------------------------- ### Test if Bit is Set Source: https://context7.com/bits-and-blooms/bitset/llms.txt The `Test` method safely checks if bit `i` is set, returning `false` for indices beyond the current length without panicking. This is useful for querying bit states. ```go b := bitset.New(8) b.Set(3) fmt.Println(b.Test(3)) // true fmt.Println(b.Test(1000)) // false (out of range, no panic) ``` -------------------------------- ### NextSet - Iterate over set bits one at a time Source: https://context7.com/bits-and-blooms/bitset/llms.txt Returns the next set bit at or after index `i`, plus a validity bool. The standard loop idiom is shown below. ```APIDOC ## NextSet ### Description Returns the next set bit at or after index `i`, plus a validity bool. The standard loop idiom is shown below. ### Method `NextSet(i uint) (uint, bool)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go b := bitset.New(200) b.Set(5).Set(42).Set(100).Set(199) for i, ok := b.NextSet(0); ok; i, ok = b.NextSet(i + 1) { fmt.Println("set bit:", i) } // Output: // set bit: 5 // set bit: 42 // set bit: 100 // set bit: 199 ``` ### Response #### Success Response (200) Returns a tuple: the index of the next set bit, and a boolean indicating if a set bit was found. #### Response Example None provided. ``` -------------------------------- ### ShiftLeft and ShiftRight for Bit Manipulation Source: https://context7.com/bits-and-blooms/bitset/llms.txt Performs logical bit shifts, moving all set bits left or right by a specified number of positions. Analogous to bitwise shift operators. ```go b := bitset.New(16) b.Set(2).Set(4).Set(6) // {2,4,6} b.ShiftLeft(3) fmt.Println(b.String()) // {5,7,9} b.ShiftRight(3) fmt.Println(b.String()) // {2,4,6} ``` -------------------------------- ### Base64StdEncoding Source: https://context7.com/bits-and-blooms/bitset/llms.txt Switches JSON marshaling from URL-safe base64 to standard base64 encoding. ```APIDOC ## Base64StdEncoding ### Description Switches JSON marshaling from URL-safe base64 (`base64.URLEncoding`) to standard base64 (`base64.StdEncoding`). ### Method `Base64StdEncoding()` ### Request Example ```go bitset.Base64StdEncoding() bs := bitset.New(8).Set(3) data, _ := bs.MarshalJSON() fmt.Println(string(data)) // uses standard alphabet (+/ instead of -_) ``` ``` -------------------------------- ### Clone Source: https://context7.com/bits-and-blooms/bitset/llms.txt Creates a deep copy of the BitSet, ensuring that modifications to the copy do not affect the original. ```APIDOC ## Clone ### Description Returns an independent copy of the BitSet with the same bits set. ### Method `Clone() *BitSet` ### Example ```go a := bitset.New(64).Set(1).Set(2).Set(3) b := a.Clone() b.Set(4) // does not affect a fmt.Println(a.Count()) // 3 fmt.Println(b.Count()) // 4 ``` ``` -------------------------------- ### Extract Bits from BitSet using a Mask Source: https://context7.com/bits-and-blooms/bitset/llms.txt Gathers bits from the source at positions where the mask has a 1, packing them consecutively into a new BitSet. Useful for selecting specific bits. ```go src := bitset.New(8).Set(1).Set(3).Set(5).Set(7) mask := bitset.New(8).Set(1).Set(3).Set(5) // gather bits at positions 1,3,5 out := src.Extract(mask) // out has bits at 0,1,2 (compact form) fmt.Println(out.String()) // {0,1,2} (all three mask positions were set in src) ``` -------------------------------- ### Len - Logical Length of the Bitset Source: https://context7.com/bits-and-blooms/bitset/llms.txt Returns the number of addressable bit positions, which may grow automatically if bits beyond the initial capacity are set. ```go b := bitset.New(128) fmt.Println(b.Len()) // 128 b.Set(200) fmt.Println(b.Len()) // 201 (auto-grew) ``` -------------------------------- ### Deposit / DepositTo Source: https://context7.com/bits-and-blooms/bitset/llms.txt Scatters bits from the source BitSet to positions specified by a mask in the destination BitSet. This is the inverse of `Extract`. ```APIDOC ## Deposit / DepositTo ### Description Takes consecutive bits from the source and places them at the positions specified by `mask` in the destination. This is the inverse of Extract. ### Method `Deposit(mask *BitSet) *BitSet` `DepositTo(dst *BitSet, mask *BitSet)` ### Example ```go src := bitset.New(3).Set(0).Set(2) // compact bits: positions 0 and 2 mask := bitset.New(8).Set(1).Set(4).Set(7) // scatter to positions 1,4,7 out := src.Deposit(mask) fmt.Println(out.String()) // {1,7} (bit0->pos1=set, bit1->pos4=clear, bit2->pos7=set) ``` ``` -------------------------------- ### Extract / ExtractTo Source: https://context7.com/bits-and-blooms/bitset/llms.txt Gathers bits from the source BitSet at positions specified by a mask, packing them consecutively into a new or existing BitSet. ```APIDOC ## Extract / ExtractTo ### Description Picks out the bits from the source at positions where `mask` has a 1, and packs them consecutively into a new (or existing) BitSet. ### Method `Extract(mask *BitSet) *BitSet` `ExtractTo(dst *BitSet, mask *BitSet)` ### Example ```go src := bitset.New(8).Set(1).Set(3).Set(5).Set(7) mask := bitset.New(8).Set(1).Set(3).Set(5) // gather bits at positions 1,3,5 out := src.Extract(mask) // out has bits at 0,1,2 (compact form) fmt.Println(out.String()) // {0,1,2} (all three mask positions were set in src) ``` ``` -------------------------------- ### Equal BitSet Comparison Source: https://context7.com/bits-and-blooms/bitset/llms.txt Checks for deep equality between two BitSets. Returns true only if both sets have the same length and identical bits. ```go a := bitset.New(8).Set(1).Set(5) b := bitset.New(8).Set(1).Set(5) c := bitset.New(8).Set(1) fmt.Println(a.Equal(b)) // true fmt.Println(a.Equal(c)) // false ```