generated from sv-tools/go-repo-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool_test.go
76 lines (62 loc) · 2 KB
/
pool_test.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
package bufferspool_test
import (
"io"
"testing"
"unsafe"
"github.com/stretchr/testify/require"
bufferspool "github.com/sv-tools/buffers-pool"
)
func TestGlobalPool(t *testing.T) {
b1 := bufferspool.Get()
b2 := bufferspool.Get()
require.NotEqual(t, unsafe.Pointer(b1), unsafe.Pointer(b2)) //nolint: gosec
b1.WriteString("foo")
bufferspool.Put(b1)
b2 = bufferspool.Get()
require.Zero(t, b2.Len())
}
func TestCustomPool(t *testing.T) {
p := bufferspool.New()
b1 := p.Get()
b2 := p.Get()
require.NotEqual(t, unsafe.Pointer(b1), unsafe.Pointer(b2)) //nolint: gosec
b1.WriteString("foo")
p.Put(b1)
b2 = p.Get()
require.Zero(t, b2.Len())
}
func TestSafety(t *testing.T) {
p := bufferspool.New()
b1 := p.Get()
b1.WriteString("foo42")
b1AsString := b1.String()
b1AsBytes := b1.Bytes()
b1Data, err := io.ReadAll(b1)
require.NoError(t, err)
require.Equal(t, "foo42", b1AsString)
require.Equal(t, []byte("foo42"), b1AsBytes, string(b1AsBytes))
require.Equal(t, []byte("foo42"), b1Data, string(b1Data))
// put the same buffer to the poll several times to increase the chance that the same object will be returned
// this is the only way to test the Pools if we need already used object
for i := 0; i < 10; i++ {
p.Put(b1)
}
b2 := p.Get()
defer p.Put(b2)
require.Equal(t, unsafe.Pointer(b1), unsafe.Pointer(b2)) //nolint: gosec
require.Empty(t, b2.Bytes())
b2.WriteString("bar")
b2AsString := b2.String()
b2AsBytes := b2.Bytes()
b2Data, err := io.ReadAll(b2)
require.NoError(t, err)
require.Equal(t, "bar", b2AsString)
require.Equal(t, []byte("bar"), b2AsBytes, string(b2AsBytes))
require.Equal(t, []byte("bar"), b2Data, string(b2Data))
// usage of string is safe and should not be changed
require.Equal(t, "foo42", b1AsString)
// usage of bytes is unsafe, the b1AsBytes must contain `bar42` instead of `foo42` or `bar`
require.Equal(t, []byte("bar42"), b1AsBytes, string(b1AsBytes))
// usage of Reader is safe and should not be changed
require.Equal(t, []byte("foo42"), b1Data, string(b1Data))
}