-
Notifications
You must be signed in to change notification settings - Fork 831
/
block.go
102 lines (80 loc) · 2.21 KB
/
block.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
/*
Copyright 2014 Workiva, LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package bitarray
import (
"fmt"
"unsafe"
)
// block defines how we split apart the bit array. This also determines the size
// of s. This can be changed to any unsigned integer type: uint8, uint16,
// uint32, and so on.
type block uint64
// s denotes the size of any element in the block array.
// For a block of uint64, s will be equal to 64
// For a block of uint32, s will be equal to 32
// and so on...
const s = uint64(unsafe.Sizeof(block(0)) * 8)
// maximumBlock represents a block of all 1s and is used in the constructors.
const maximumBlock = block(0) | ^block(0)
func (b block) toNums(offset uint64, nums *[]uint64) {
for i := uint64(0); i < s; i++ {
if b&block(1<<i) > 0 {
*nums = append(*nums, i+offset)
}
}
}
func (b block) findLeftPosition() uint64 {
for i := s - 1; i < s; i-- {
test := block(1 << i)
if b&test == test {
return i
}
}
return s
}
func (b block) findRightPosition() uint64 {
for i := uint64(0); i < s; i++ {
test := block(1 << i)
if b&test == test {
return i
}
}
return s
}
func (b block) insert(position uint64) block {
return b | block(1<<position)
}
func (b block) remove(position uint64) block {
return b & ^block(1<<position)
}
func (b block) or(other block) block {
return b | other
}
func (b block) and(other block) block {
return b & other
}
func (b block) nand(other block) block {
return b &^ other
}
func (b block) get(position uint64) bool {
return b&block(1<<position) != 0
}
func (b block) equals(other block) bool {
return b == other
}
func (b block) intersects(other block) bool {
return b&other == other
}
func (b block) String() string {
return fmt.Sprintf(fmt.Sprintf("%%0%db", s), uint64(b))
}