/
ring.go
88 lines (78 loc) · 1.56 KB
/
ring.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
83
84
85
86
87
88
package comet
import (
log "github.com/golang/glog"
"github.com/nanpingli/qqqg/api/protocol"
"github.com/nanpingli/qqqg/internal/comet/conf"
"github.com/nanpingli/qqqg/internal/comet/errors"
)
// Ring ring proto buffer.
type Ring struct {
// read
rp uint64
num uint64
mask uint64
// TODO split cacheline, many cpu cache line size is 64
// pad [40]byte
// write
wp uint64
data []protocol.Proto
}
// NewRing new a ring buffer.
func NewRing(num int) *Ring {
r := new(Ring)
r.init(uint64(num))
return r
}
// Init init ring.
func (r *Ring) Init(num int) {
r.init(uint64(num))
}
func (r *Ring) init(num uint64) {
// 2^N
if num&(num-1) != 0 {
for num&(num-1) != 0 {
num &= num - 1
}
num <<= 1
}
r.data = make([]protocol.Proto, num)
r.num = num
r.mask = r.num - 1
}
// Get get a proto from ring.
func (r *Ring) Get() (proto *protocol.Proto, err error) {
if r.rp == r.wp {
return nil, errors.ErrRingEmpty
}
proto = &r.data[r.rp&r.mask]
return
}
// GetAdv incr read index.
func (r *Ring) GetAdv() {
r.rp++
if conf.Conf.Debug {
log.Infof("ring rp: %d, idx: %d", r.rp, r.rp&r.mask)
}
}
// Set get a proto to write.
func (r *Ring) Set() (proto *protocol.Proto, err error) {
if r.wp-r.rp >= r.num {
return nil, errors.ErrRingFull
}
proto = &r.data[r.wp&r.mask]
return
}
// SetAdv incr write index.
func (r *Ring) SetAdv() {
r.wp++
if conf.Conf.Debug {
log.Infof("ring wp: %d, idx: %d", r.wp, r.wp&r.mask)
}
}
// Reset reset ring.
func (r *Ring) Reset() {
r.rp = 0
r.wp = 0
// prevent pad compiler optimization
// r.pad = [40]byte{}
}