Skip to content

Instantly share code, notes, and snippets.

@fstanis
Created January 21, 2018 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fstanis/1fb5a21489cf7476758dd41cc922363a to your computer and use it in GitHub Desktop.
Save fstanis/1fb5a21489cf7476758dd41cc922363a to your computer and use it in GitHub Desktop.
Simple map-backed bitset in Go
package bitset
import "errors"
// BitSet represents a set of booleans.
type BitSet struct {
buckets map[int]byte
}
// New creates a new BitSet.
func New() *BitSet {
return &BitSet{make(map[int]byte)}
}
// Set sets the bit at the given location to the given value. For example,
// bitset.Set(18, true) sets the bit at the position 18 to 1.
func (b *BitSet) Set(pos int, value bool) {
if pos < 0 {
panic(errors.New("index out of range"))
}
index := pos / 8
bit := uint(pos % 8)
current, ok := b.buckets[index]
if value {
current = current | (1 << bit)
} else {
current = current &^ (1 << bit)
}
if current != 0 {
b.buckets[index] = current
} else if ok {
delete(b.buckets, index)
}
}
// Get reads the bit value at the given position.
func (b *BitSet) Get(pos int) bool {
if pos < 0 {
panic(errors.New("index out of range"))
}
index := pos / 8
bit := uint(pos % 8)
if ((b.buckets[index] >> bit) & 1) == 1 {
return true
}
return false
}
// ToSlice returns a slice containing all the bit positions that are set to 1.
func (b *BitSet) ToSlice() (slice []int) {
for index, value := range b.buckets {
bit := 0
for value > 0 {
if (value & 1) == 1 {
slice = append(slice, index*8+bit)
}
bit++
value = value >> 1
}
}
return slice
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment