-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpool_test.go
More file actions
98 lines (89 loc) · 1.84 KB
/
pool_test.go
File metadata and controls
98 lines (89 loc) · 1.84 KB
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
89
90
91
92
93
94
95
96
97
98
package orbyte
import (
"bytes"
"crypto/rand"
"encoding/hex"
"runtime"
"sync"
"testing"
)
func TestPool(t *testing.T) {
p := NewPool[[]byte](simplepooler{})
x := p.New(200)
x.ManualDestroy()
out, in := p.CountItems()
t.Log("out", out, "in", in)
if out != 0 || in != 1 {
t.Fatal("unexpected behavior")
}
for i := 0; i < 2000; i++ {
item := p.New(i)
out, in = p.CountItems()
if out != 1 || in != 0 {
t.Fatal("unexpected behavior")
}
item.ManualDestroy()
}
out, in = p.CountItems()
t.Log("out", out, "in", in)
if out != 0 {
t.Fatal("unexpected behavior")
}
item := p.New(4096)
item.V(func(b []byte) {
rand.Read(b)
})
exp := item.Copy().Trans()
wg := sync.WaitGroup{}
for i := 0; i < 4096; i++ {
item := p.New(i)
item.V(func(b []byte) {
copy(b, exp)
})
wg.Add(1)
go useranddes(item.Copy(), &wg)
wg.Add(1)
go userv(item.Trans(), &wg, exp[:i])
}
wg.Wait()
runtime.GC()
out, in = p.CountItems()
t.Log("out", out, "in", in)
if out != 0 {
t.Fatal("unexpected behavior")
}
}
func useranddes(item *Item[[]byte], wg *sync.WaitGroup) {
defer wg.Done()
item.V(func(b []byte) {
rand.Read(b)
})
item.ManualDestroy()
}
func userv(b []byte, wg *sync.WaitGroup, exp []byte) {
defer wg.Done()
if !bytes.Equal(b, exp) {
panic("expect " + hex.EncodeToString(exp) + " got " + hex.EncodeToString(b))
}
}
type simplepooler struct{}
func (simplepooler) New(config any, pooled []byte) []byte {
if cap(pooled) >= config.(int) {
return pooled[:config.(int)]
}
return make([]byte, config.(int))
}
func (simplepooler) Parse(obj any, pooled []byte) []byte {
src := obj.([]byte)
if cap(pooled) >= len(src) {
copy(pooled[:len(src)], src)
return pooled[:len(src)]
}
return obj.([]byte)
}
func (simplepooler) Reset(item *[]byte) {
*item = (*item)[:0]
}
func (simplepooler) Copy(dst, src *[]byte) {
copy(*dst, *src)
}