-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbitvector2.go
More file actions
111 lines (92 loc) · 2.38 KB
/
bitvector2.go
File metadata and controls
111 lines (92 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package bitfield
import (
"math/bits"
)
var _ = Bitfield(Bitvector2{})
// Bitvector2 is a bitfield with a known size of 2. There is no length bit
// present in the underlying byte array.
type Bitvector2 []byte
const bitvector2ByteSize = 1
const bitvector2BitSize = 2
// NewBitvector2 creates a new bitvector of size 2.
func NewBitvector2() Bitvector2 {
byteArray := [bitvector2ByteSize]byte{}
return byteArray[:]
}
// BitAt returns the bit value at the given index. If the index requested
// exceeds the number of bits in the bitvector, then this method returns false.
func (b Bitvector2) BitAt(idx uint64) bool {
// Out of bounds, must be false.
if idx >= b.Len() || len(b) != bitvector2ByteSize {
return false
}
i := uint8(1 << idx)
return b[0]&i == i
}
// SetBitAt will set the bit at the given index to the given value. If the index
// requested exceeds the number of bits in the bitvector, then this method returns
// false.
func (b Bitvector2) SetBitAt(idx uint64, val bool) {
// Out of bounds, do nothing.
if idx >= b.Len() || len(b) != bitvector2ByteSize {
return
}
bit := uint8(1 << idx)
if val {
b[0] |= bit
} else {
b[0] &^= bit
}
}
// Len returns the number of bits in the bitvector.
func (b Bitvector2) Len() uint64 {
return bitvector2BitSize
}
// Count returns the number of 1s in the bitvector.
func (b Bitvector2) Count() uint64 {
if len(b) == 0 {
return 0
}
return uint64(bits.OnesCount8(b.Bytes()[0]))
}
// Bytes returns the bytes data representing the bitvector2. This method
// bitmasks the underlying data to ensure that it is an accurate representation.
func (b Bitvector2) Bytes() []byte {
if len(b) == 0 {
return []byte{}
}
return []byte{b[0] & 0x03}
}
// Shift bitvector by i. If i >= 0, perform left shift, otherwise right shift.
func (b Bitvector2) Shift(i int) {
if len(b) == 0 {
return
}
// Shifting greater than 2 bits is pointless and can have unexpected behavior.
if i > 2 {
i = 2
} else if i < -2 {
i = -2
}
if i >= 0 {
b[0] <<= uint8(i)
} else {
b[0] >>= uint8(i * -1)
}
b[0] &= 0x03
}
// BitIndices returns the list of indices that are set to 1.
func (b Bitvector2) BitIndices() []int {
indices := make([]int, 0, 2)
if len(b) != bitvector2ByteSize {
return indices
}
bt := b[0]
for j := 0; j < bitvector2BitSize; j++ {
bit := byte(1 << uint(j))
if bt&bit == bit {
indices = append(indices, j)
}
}
return indices
}