-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbit.go
More file actions
43 lines (37 loc) · 810 Bytes
/
bit.go
File metadata and controls
43 lines (37 loc) · 810 Bytes
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
// Package bit implements variable-size bit-fields
package bit
// Field is a variable-length bit-field
type Field []byte
// Set bit
func (f *Field) Set(k int) {
n, m := k>>3, byte(1<<uint(k&7))
if len(*f) <= n {
*f = append(*f, make([]byte, n-len(*f)+1)...)
}
(*f)[n] |= m
}
// IsSet checks if bit is set
func (f *Field) IsSet(k int) bool {
n, m := k>>3, byte(1<<uint(k&7))
return len(*f) > n && (*f)[n]&m != 0
}
// Clear bit
func (f *Field) Clear(k int) {
n, m := k>>3, byte(1<<uint(k&7))
if len(*f) > n {
(*f)[n] &^= m
}
}
// IsClear checks if bit is cleared
func (f *Field) IsClear(k int) bool {
n, m := k>>3, byte(1<<uint(k&7))
return len(*f) <= n || (*f)[n]&m == 0
}
func (f *Field) Shrink() {
for i := len(*f); i > 0; i-- {
if (*f)[i-1] != 0 {
break
}
*f = (*f)[:i-1]
}
}