-
-
Save alinpopa/c41197e39639b14b7c4ea450ff35005a to your computer and use it in GitHub Desktop.
bitset
This file contains hidden or 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 "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