Skip to content

Commit

Permalink
feat: replace bitmap with bitset (#3023)
Browse files Browse the repository at this point in the history
Signed-off-by: dabfdj <jfh@outlook.hu>
  • Loading branch information
dabfdj authored Feb 26, 2024
1 parent 54d0048 commit bfe3091
Showing 1 changed file with 19 additions and 21 deletions.
40 changes: 19 additions & 21 deletions client/daemon/peer/peertask_bitmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,52 +17,50 @@
package peer

import (
"go.uber.org/atomic"
"sync"

"github.com/bits-and-blooms/bitset"
)

type Bitmap struct {
bits []byte
cap int32
settled atomic.Int32
bits *bitset.BitSet
mu sync.RWMutex
}

func NewBitmap() *Bitmap {
return &Bitmap{
bits: make([]byte, 8),
cap: 8 * 8,
bits: bitset.New(8),
}
}

func NewBitmapWithCap(c int32) *Bitmap {
return &Bitmap{
bits: make([]byte, c),
cap: c * 8,
bits: bitset.New(uint(c)),
}
}

func (b *Bitmap) IsSet(i int32) bool {
if i >= b.cap {
return false
}
return b.bits[i/8]&(1<<uint(7-i%8)) != 0
b.mu.RLock()
defer b.mu.RUnlock()
return b.bits.Test(uint(i))
}

func (b *Bitmap) Set(i int32) {
for i >= b.cap {
b.bits = append(b.bits, make([]byte, b.cap/8)...)
b.cap *= 2
}
b.settled.Inc()
b.bits[i/8] |= 1 << uint(7-i%8)
b.mu.Lock()
defer b.mu.Unlock()
b.bits.Set(uint(i))
}

func (b *Bitmap) Clean(i int32) {
b.settled.Dec()
b.bits[i/8] ^= 1 << uint(7-i%8)
b.mu.Lock()
defer b.mu.Unlock()
b.bits.Clear(uint(i))
}

func (b *Bitmap) Settled() int32 {
return b.settled.Load()
b.mu.RLock()
defer b.mu.RUnlock()
return int32(b.bits.Count())
}

func (b *Bitmap) Sets(xs ...int32) {
Expand Down

0 comments on commit bfe3091

Please sign in to comment.