-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpool.go
51 lines (45 loc) · 771 Bytes
/
pool.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 random
import (
"bytes"
"io"
"sync"
)
var (
randPool = &sync.Pool{New: newReader}
)
type pool struct {
pos int
mu *sync.Mutex
pool []byte
}
func (p *pool) Int64() int64 {
p.mu.Lock()
defer p.mu.Unlock()
if p.pos+8 > poolSize {
if _, err := io.ReadFull(reader, p.pool[:]); err != nil {
panic(err)
}
p.pos = 0
}
buffer := bytes.NewBuffer(p.pool[p.pos:])
p.pos += 8
var num int64
var b byte
for i := 0; i < 64; i += 8 {
b, _ = buffer.ReadByte()
num += int64(b) << i
}
return num
}
func newReader() interface{} {
return &pool{
pos: poolSize,
mu: new(sync.Mutex),
pool: make([]byte, poolSize, poolSize),
}
}
func randFromPool() int64 {
rand := randPool.Get().(*pool)
defer randPool.Put(rand)
return rand.Int64()
}