Skip to content

Instantly share code, notes, and snippets.

@gabriel-tincu
Created August 29, 2017 10:31
Show Gist options
  • Save gabriel-tincu/29d6758fafed306f0189453d5a54ceb4 to your computer and use it in GitHub Desktop.
Save gabriel-tincu/29d6758fafed306f0189453d5a54ceb4 to your computer and use it in GitHub Desktop.
bitset
package bitset
import "fmt"
const (
chunkSize uint = 8
allSet uint64 = 1<<8 - 1
allReset uint64 = 0
)
type Bitset struct {
storage []byte
size uint
}
func NewBitset(size uint) (*Bitset, error) {
if size == 0 {
return nil, fmt.Errorf("Cannot create a 0 size bitset")
}
storeSize := size / chunkSize
if size % chunkSize != 0 {
storeSize++
}
storage := make([]byte, storeSize)
return &Bitset{storage: storage, size: size}, nil
}
func (b *Bitset) SetAll() {
for i := range b.storage {
b.storage[i] = byte(allSet)
}
}
func (b *Bitset) ResetAll() {
for i := range b.storage {
b.storage[i] = byte(allReset)
}
}
func (b *Bitset) Set(position uint) error {
if position > b.size {
return fmt.Errorf("Index exceeding bitset size")
}
index := position / chunkSize
indexPos := position % chunkSize
mask := 1 << indexPos
b.storage[index] = b.storage[index] | byte(mask)
return nil
}
func (b *Bitset) Get(position uint) (bool, error) {
if position > b.size {
return false, fmt.Errorf("Index exceeding bitset size")
}
index := position / chunkSize
indexPos := position % chunkSize
return (b.storage[index] >> indexPos) & 0x1 == 1, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment