Created
January 21, 2018 21:28
-
-
Save fstanis/1fb5a21489cf7476758dd41cc922363a to your computer and use it in GitHub Desktop.
Simple map-backed bitset in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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