OSDN Git Service

Tx validate mining (#237)
[bytom/vapor.git] / common / bit_map.go
1 package common
2
3 import (
4         "errors"
5 )
6
7 const bitLen = 32
8
9 var (
10         errIndexOutOfBounds = errors.New("index out of bounds error")
11 )
12
13 type BitMap struct {
14         size uint32
15         arr []int32
16 }
17
18 func NewBitMap(size uint32) *BitMap {
19         obj := &BitMap{size: size}
20         num := (size + bitLen - 1) / bitLen
21         arr := make([]int32, num)
22         obj.arr = arr
23         return obj
24 }
25
26 func (b *BitMap) Set(index uint32) error {
27         if index >= b.size {
28                 return errIndexOutOfBounds
29         }
30
31         arrIndex, bitIndex := index / bitLen, index % bitLen
32         b.arr[arrIndex] |= (1 << bitIndex)
33         return nil
34 }
35
36 func (b *BitMap) Clean(index uint32) error {
37         if index >= b.size {
38                 return errIndexOutOfBounds
39         }
40
41         arrIndex, bitIndex := index / bitLen, index % bitLen
42         b.arr[arrIndex] &= (^(1 << bitIndex))
43         return nil
44 }
45
46 func (b *BitMap) Test(index uint32) (bool, error) {
47         if index >= b.size {
48                 return false, errIndexOutOfBounds
49         }
50
51         arrIndex, bitIndex := index / bitLen, index % bitLen
52         return b.arr[arrIndex] & (1 << bitIndex) != 0, nil
53 }