-
Notifications
You must be signed in to change notification settings - Fork 0
/
dynamic.go
78 lines (64 loc) · 1.61 KB
/
dynamic.go
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
package binflags
import (
"unsafe"
)
// Dynamic is a dynamic size implementation of the binflags.
// This implementation uses a map under the hood.
// The map's key is a uint.
// Specify an expected size for the map to improve performance.
// To initialize the Dynamic type, use make function or usual instatination:
//
// flags := make(Dynamic[uint], 3)
//
// or
//
// flags := make(Dynamic[uint])
//
// or
//
// flags := Dynamic[uint]{}
type Dynamic[T Integer] map[uint]T
// IsSet returns true if the flag is set.
// If the flag is not set, then it returns false.
// This function has O(1) complexity.
func (d Dynamic[T]) IsSet(bitNumber uint) bool {
size := uint(unsafe.Sizeof(d[0])) * BitsInByte
byteIdx := bitNumber / size
val, ok := d[byteIdx]
if !ok {
return false
}
bitIdx := uint8(bitNumber % size)
return IsSetBit(val, bitIdx)
}
// Set sets the flag.
// This function is idempotent.
// This function has O(1) complexity.
// It always returns true.
func (d Dynamic[T]) Set(bitNumber uint) bool {
size := uint(unsafe.Sizeof(d[0])) * BitsInByte
byteIdx := bitNumber / size
bitIdx := uint8(bitNumber % size)
d[byteIdx] = SetBit(d[byteIdx], bitIdx)
return true
}
// Unset unsets the flag.
// This function is idempotent.
// This function has O(1) complexity.
// It always returns true.
func (d Dynamic[T]) Unset(bitNumber uint) bool {
size := uint(unsafe.Sizeof(d[0])) * BitsInByte
byteIdx := bitNumber / size
val := d[byteIdx]
if val == 0 {
return true
}
bitIdx := uint8(bitNumber % size)
val = UnsetBit(val, bitIdx)
if val == 0 {
delete(d, byteIdx)
} else {
d[byteIdx] = val
}
return true
}