-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbitmap.go
82 lines (71 loc) · 1.39 KB
/
bitmap.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
package smux
import (
"errors"
"math"
"sync"
)
type idBitmap struct {
bits []byte
next uint16
length int
lock sync.Mutex
}
func NewIDBitmap() *idBitmap {
return &idBitmap{bits: make([]byte, 65536/8)}
}
// NewBitmap return [0, 65535]
func (this *idBitmap) Get() (uint16, error) {
this.lock.Lock()
defer this.lock.Unlock()
if this.length == 65536 {
return 0, errors.New("id use up. ")
}
for {
idx, bit := this.next/8, this.next%8
if (this.bits[idx] & (1 << bit)) == 0 {
this.bits[idx] |= 1 << bit
this.length++
id := this.next
this.next++
return id, nil
}
if this.next == math.MaxUint16 {
this.next = 0
} else {
this.next++
}
}
}
func (this *idBitmap) Set(num uint16) bool {
this.lock.Lock()
defer this.lock.Unlock()
idx, bit := num/8, num%8
if (this.bits[idx] & (1 << bit)) == 0 {
this.bits[idx] |= 1 << bit
this.length++
return true
}
return false
}
func (this *idBitmap) Put(num uint16) bool {
this.lock.Lock()
defer this.lock.Unlock()
idx, bit := num/8, num%8
if (this.bits[idx] & (1 << bit)) != 0 {
this.bits[idx] &^= 1 << bit
this.length--
return true
}
return false
}
func (this *idBitmap) Has(num uint16) bool {
this.lock.Lock()
defer this.lock.Unlock()
idx, bit := num/8, num%8
return (this.bits[idx] & (1 << bit)) != 0
}
func (this *idBitmap) Len() int {
this.lock.Lock()
defer this.lock.Unlock()
return this.length
}