/
agent.go
78 lines (66 loc) · 1.24 KB
/
agent.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
package bigblob
import (
"sync"
"github.com/brendoncarroll/go-state/cadata"
lru "github.com/hashicorp/golang-lru"
)
type Option func(*Agent)
func WithCacheSize(n int) Option {
return func(ag *Agent) {
ag.cacheSize = n
}
}
// WithBlockSize sets the block size used when writing files.
// If n < 0 then WithBlockSize panics
// If n == 0 then the stores MaxBlobSize will be used as a default.
func WithBlockSize(n int) Option {
if n < 0 {
panic(n)
}
return func(ag *Agent) {
ag.blockSize = n
}
}
type Agent struct {
cacheSize int
blockSize int
cache *lru.Cache
bufPool sync.Pool
}
func NewAgent(opts ...Option) *Agent {
o := Agent{
cacheSize: 64,
bufPool: sync.Pool{
New: func() interface{} {
buf := []byte(nil)
return &buf
},
},
}
for _, opt := range opts {
opt(&o)
}
o.cache = newCache(o.cacheSize)
return &o
}
func (ag *Agent) acquireBuffer(n int) *[]byte {
x := ag.bufPool.Get().(*[]byte)
if len(*x) < n {
*x = append(*x, make([]byte, n-len(*x))...)
}
return x
}
func (ag *Agent) releaseBuffer(x *[]byte) {
ag.bufPool.Put(x)
}
func newCache(size int) *lru.Cache {
cache, err := lru.New(size)
if err != nil {
panic(err)
}
return cache
}
type AddExister interface {
cadata.Adder
cadata.Exister
}