github.com/pingcap/br@v5.3.0-alpha.0.20220125034240-ec59c7b6ce30+incompatible/pkg/membuf/buffer_test.go (about) 1 // Copyright 2021 PingCAP, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package membuf 15 16 import ( 17 "crypto/rand" 18 "testing" 19 20 . "github.com/pingcap/check" 21 ) 22 23 func init() { 24 allocBufLen = 1024 25 } 26 27 type bufferSuite struct{} 28 29 var _ = Suite(&bufferSuite{}) 30 31 func Test(t *testing.T) { 32 TestingT(t) 33 } 34 35 type testAllocator struct { 36 allocs int 37 frees int 38 } 39 40 func (t *testAllocator) Alloc(n int) []byte { 41 t.allocs++ 42 return make([]byte, n) 43 } 44 45 func (t *testAllocator) Free(_ []byte) { 46 t.frees++ 47 } 48 49 func (*bufferSuite) TestBufferPool(c *C) { 50 allocator := &testAllocator{} 51 pool := NewPool(2, allocator) 52 53 bytesBuf := pool.NewBuffer() 54 bytesBuf.AllocBytes(256) 55 c.Assert(allocator.allocs, Equals, 1) 56 bytesBuf.AllocBytes(512) 57 c.Assert(allocator.allocs, Equals, 1) 58 bytesBuf.AllocBytes(257) 59 c.Assert(allocator.allocs, Equals, 2) 60 bytesBuf.AllocBytes(767) 61 c.Assert(allocator.allocs, Equals, 2) 62 63 c.Assert(allocator.frees, Equals, 0) 64 bytesBuf.Destroy() 65 c.Assert(allocator.frees, Equals, 0) 66 67 bytesBuf = pool.NewBuffer() 68 for i := 0; i < 6; i++ { 69 bytesBuf.AllocBytes(512) 70 } 71 bytesBuf.Destroy() 72 c.Assert(allocator.allocs, Equals, 3) 73 c.Assert(allocator.frees, Equals, 1) 74 } 75 76 func (*bufferSuite) TestBufferIsolation(c *C) { 77 bytesBuf := NewBuffer() 78 defer bytesBuf.Destroy() 79 80 b1 := bytesBuf.AllocBytes(16) 81 b2 := bytesBuf.AllocBytes(16) 82 c.Assert(cap(b1), Equals, len(b1)) 83 c.Assert(cap(b2), Equals, len(b2)) 84 85 _, err := rand.Read(b2) 86 c.Assert(err, IsNil) 87 b3 := append([]byte(nil), b2...) 88 b1 = append(b1, 0, 1, 2, 3) 89 c.Assert(b2, DeepEquals, b3) 90 }