forked from fl00r/go-iproto
-
Notifications
You must be signed in to change notification settings - Fork 2
/
generator.go
71 lines (62 loc) · 1.12 KB
/
generator.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
package iproto
import (
"sync"
"github.com/funny-falcon/go-iproto/marshal"
)
const rrsize = 32
type generators chan *RGenerator
type RGenerator struct {
req *[rrsize]Request
res *[rrsize]Response
w marshal.Writer
g generators
m sync.Mutex
i int32
}
func (gen *RGenerator) Request(id uint32, msg RequestType, val interface{}) (req *Request) {
var res *Response
if gen.req == nil {
gen.req = &[rrsize]Request{}
gen.res = &[rrsize]Response{}
}
req = &gen.req[gen.i]
res = &gen.res[gen.i]
req.Response = res
if gen.i++; gen.i == rrsize {
gen.i = 0
gen.req = nil
gen.res = nil
}
req.Id = id
req.Msg = msg
var ok bool
if req.Body, ok = val.(Body); !ok {
gen.w.Write(val)
req.Body = gen.w.Written()
}
return
}
func (gen *RGenerator) Release() {
gen.m.Lock()
if gen != nil && gen.g != nil {
g := gen.g
gen.g = nil
select {
case g <- gen:
default:
}
}
gen.m.Unlock()
}
func (g generators) Get() (gen *RGenerator) {
select {
case gen = <-g:
default:
gen = &RGenerator{g: g}
}
return
}
var gencache = make(generators, 128)
func GetGenerator() *RGenerator {
return gencache.Get()
}