aboutsummaryrefslogtreecommitdiff
path: root/bitfield/bitfield.go
diff options
context:
space:
mode:
Diffstat (limited to 'bitfield/bitfield.go')
-rw-r--r--bitfield/bitfield.go38
1 files changed, 38 insertions, 0 deletions
diff --git a/bitfield/bitfield.go b/bitfield/bitfield.go
new file mode 100644
index 0000000..2346a2c
--- /dev/null
+++ b/bitfield/bitfield.go
@@ -0,0 +1,38 @@
+package bitfield
+
+type BitField []byte
+
+func New(n int) BitField {
+ l := n / 8
+ if pad := (8 - n%8) % 8; pad != 0 {
+ l++
+ }
+ return make(BitField, l)
+}
+
+func (b BitField) At(i int) bool {
+ x := i / 8
+ y := 7 - uint(i%8)
+ if x < 0 || x > len(b) {
+ panic("out of range")
+ }
+ return (int(b[x]>>y) & 1) == 1
+}
+
+func (b BitField) Set(i int) {
+ x := i / 8
+ y := 7 - uint(i%8)
+ if x < 0 || x > len(b) {
+ panic("out of range")
+ }
+ b[x] |= 1 << y
+}
+
+func (b BitField) Clear(i int) {
+ x := i / 8
+ y := 7 - uint(i%8)
+ if x < 0 || x > len(b) {
+ panic("out of range")
+ }
+ b[x] &= ^(1 << y)
+}