-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathseqid.go
51 lines (41 loc) · 875 Bytes
/
seqid.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
package main
import (
"sync"
"sync/atomic"
)
type SeqIdAllocator struct {
nextId int32
}
func NewSeqIdAllocator() *SeqIdAllocator {
return &SeqIdAllocator{nextId: 0}
}
func (s *SeqIdAllocator) AllocId() int {
return int(atomic.AddInt32(&s.nextId, 1))
}
type SeqIdMapper struct {
sync.Mutex
// map from newSeqId to oldSeqId
idMapper map[int]int
}
func NewSeqIdMapper() *SeqIdMapper {
return &SeqIdMapper{idMapper: make(map[int]int)}
}
func (s *SeqIdMapper) MapTo(oldSeqId int, newSeqId int) {
s.Lock()
defer s.Unlock()
s.idMapper[newSeqId] = oldSeqId
}
func (s *SeqIdMapper) RemoveMap(newSeqId int) (int, bool) {
s.Lock()
defer s.Unlock()
if oldSeqId, ok := s.idMapper[newSeqId]; ok {
delete(s.idMapper, newSeqId)
return oldSeqId, true
}
return 0, false
}
func (s *SeqIdMapper) Size() int {
s.Lock()
defer s.Unlock()
return len(s.idMapper)
}