github.com/benz9527/xboot@v0.0.0-20240504061247-c23f15593274/lib/bits/bitmap.go (about) 1 package bits 2 3 import "bytes" 4 5 type Bitmap interface { 6 SetBit(offset uint64) bool 7 UnsetBit(offset uint64) bool 8 GetBit(offset uint64) bool 9 GetBits() []byte 10 EqualTo(bm Bitmap) bool 11 Purge() 12 } 13 14 const ( 15 maxBitMapSize = 1 << 32 16 ) 17 18 type x32Bitmap struct { 19 bits []byte 20 size uint64 21 } 22 23 func NewX32Bitmap(size uint64) Bitmap { 24 if size <= 0 || size > maxBitMapSize { 25 size = maxBitMapSize 26 } 27 if remainder := size & 0x07; remainder != 0 { 28 size = size + (8 - remainder) 29 } 30 return &x32Bitmap{ 31 bits: make([]byte, size>>3), 32 size: size - 1, 33 } 34 } 35 36 func (bm *x32Bitmap) SetBit(offset uint64) bool { 37 idx, pos := offset>>3, offset&0x07 38 if bm.size < offset { 39 return false 40 } 41 bm.bits[idx] |= 1 << pos 42 return true 43 } 44 45 func (bm *x32Bitmap) UnsetBit(offset uint64) bool { 46 idx, pos := offset>>3, offset&0x07 47 if bm.size < offset { 48 return false 49 } 50 bm.bits[idx] &= ^(1 << pos) // &^= 51 return true 52 } 53 54 func (bm *x32Bitmap) GetBit(offset uint64) bool { 55 idx, pos := offset>>3, offset&0x07 56 if bm.size < offset { 57 return false 58 } 59 return bm.bits[idx]>>pos != 0 60 } 61 62 func (bm *x32Bitmap) GetBits() []byte { 63 return bm.bits 64 } 65 66 func (bm *x32Bitmap) EqualTo(that Bitmap) bool { 67 return bytes.Compare(bm.GetBits(), that.GetBits()) == 0 68 } 69 70 func (bm *x32Bitmap) Purge() { 71 clear(bm.bits) 72 }