Files
tidb/br/pkg/membuf/buffer_test.go

88 lines
1.9 KiB
Go

// Copyright 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package membuf
import (
"crypto/rand"
"testing"
"github.com/stretchr/testify/require"
)
func init() {
allocBufLen = 1024
}
type testAllocator struct {
allocs int
frees int
}
func (t *testAllocator) Alloc(n int) []byte {
t.allocs++
return make([]byte, n)
}
func (t *testAllocator) Free(_ []byte) {
t.frees++
}
func TestBufferPool(t *testing.T) {
t.Parallel()
allocator := &testAllocator{}
pool := NewPool(2, allocator)
bytesBuf := pool.NewBuffer()
bytesBuf.AllocBytes(256)
require.Equal(t, 1, allocator.allocs)
bytesBuf.AllocBytes(512)
require.Equal(t, 1, allocator.allocs)
bytesBuf.AllocBytes(257)
require.Equal(t, 2, allocator.allocs)
bytesBuf.AllocBytes(767)
require.Equal(t, 2, allocator.allocs)
require.Equal(t, 0, allocator.frees)
bytesBuf.Destroy()
require.Equal(t, 0, allocator.frees)
bytesBuf = pool.NewBuffer()
for i := 0; i < 6; i++ {
bytesBuf.AllocBytes(512)
}
bytesBuf.Destroy()
require.Equal(t, 3, allocator.allocs)
require.Equal(t, 1, allocator.frees)
}
func TestBufferIsolation(t *testing.T) {
t.Parallel()
bytesBuf := NewBuffer()
defer bytesBuf.Destroy()
b1 := bytesBuf.AllocBytes(16)
b2 := bytesBuf.AllocBytes(16)
require.Equal(t, len(b1), cap(b1))
require.Equal(t, len(b2), cap(b2))
_, err := rand.Read(b2)
require.NoError(t, err)
b3 := append([]byte(nil), b2...)
b1 = append(b1, 0, 1, 2, 3)
require.Equal(t, b3, b2)
}