-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgobitarray.go
118 lines (88 loc) · 2.42 KB
/
gobitarray.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
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
112
113
114
115
116
117
118
package gobitarray
import (
"fmt"
"sync"
)
// BitArray : Holds the bit array data and metadata
type BitArray struct {
size int
data []byte
mux sync.RWMutex
}
// IndexError : Represents an index out of range error
type IndexError struct {
position int
arraySize int
}
func (err *IndexError) Error() string {
return fmt.Sprintf("Provided position %d is out of range. Maximum allowed index is %d.", err.position, err.arraySize-1)
}
// New : Create a new bit array of a specified size
func New(size int) BitArray {
return BitArray{size: size, data: make([]byte, size/8+1)}
}
// Set : set a specific position's bit. Returns an error if unsuccessful
// if the position provided is invalid
func (arr *BitArray) Set(position int) error {
arr.mux.Lock()
defer arr.mux.Unlock()
err := ensurePosition(position, arr.size)
if err != nil {
return err
}
arr.data[position/8] = arr.data[position/8] | (1 << (position % 8))
return nil
}
// Unset : unset a specific position's bit. Returns an error if unsuccessful
// if the position provided is invalid
func (arr *BitArray) Unset(position int) error {
arr.mux.Lock()
defer arr.mux.Unlock()
err := ensurePosition(position, arr.size)
if err != nil {
return err
}
arr.data[position/8] = arr.data[position/8] & ^(1 << (position % 8))
return nil
}
// Get : Get the value of a bit. Returns the value of the bit and an error
// if the position provided is invalid
func (arr *BitArray) Get(position int) (int, error) {
arr.mux.Lock()
defer arr.mux.Unlock()
err := ensurePosition(position, arr.size)
if err != nil {
return -1, err
}
return arr.getBit(position), nil
}
// Toggle : Toggles the value of a bit. Returns the new value of the bit and an error
// if the position provided is invalid
func (arr *BitArray) Toggle(position int) (int, error) {
arr.mux.Lock()
defer arr.mux.Unlock()
err := ensurePosition(position, arr.size)
if err != nil {
return -1, err
}
arr.data[position/8] = arr.data[position/8] ^ (1 << (position % 8))
return arr.getBit(position), nil
}
// Reset : Unsets all the bits of the array
func (arr *BitArray) Reset() {
arr.mux.Lock()
defer arr.mux.Unlock()
arr.data = make([]byte, arr.size/8+1)
}
func (arr *BitArray) getBit(position int) int {
if arr.data[position/8]&(1<<(position%8)) > 0 {
return 1
}
return 0
}
func ensurePosition(position int, size int) error {
if position >= size {
return &IndexError{position, size}
}
return nil
}