github.com/pawelgaczynski/gain@v0.4.0-alpha.0.20230821120126-41f1e60a18da/pkg/pool/byteslice/byteslice_pool_test.go (about)

     1  // Copyright (c) 2023 Paweł Gaczyński
     2  // Copyright (c) 2021 Andy Pan
     3  //
     4  // Licensed under the Apache License, Version 2.0 (the "License");
     5  // you may not use this file except in compliance with the License.
     6  // You may obtain a copy of the License at
     7  //
     8  //     http://www.apache.org/licenses/LICENSE-2.0
     9  //
    10  // Unless required by applicable law or agreed to in writing, software
    11  // distributed under the License is distributed on an "AS IS" BASIS,
    12  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  // See the License for the specific language governing permissions and
    14  // limitations under the License.
    15  
    16  package byteslice
    17  
    18  import (
    19  	"runtime/debug"
    20  	"testing"
    21  
    22  	. "github.com/stretchr/testify/require"
    23  )
    24  
    25  func TestByteSlice(t *testing.T) {
    26  	buf := Get(8)
    27  	copy(buf, "ff")
    28  
    29  	if string(buf[:2]) != "ff" {
    30  		t.Fatal("expect copy result is ff, but not")
    31  	}
    32  
    33  	// Disable GC to test re-acquire the same data
    34  	gc := debug.SetGCPercent(-1)
    35  
    36  	Put(buf)
    37  
    38  	newBuf := Get(7)
    39  	if &newBuf[0] != &buf[0] {
    40  		t.Fatal("expect newBuf and buf to be the same array")
    41  	}
    42  
    43  	if string(newBuf[:2]) != "ff" {
    44  		t.Fatal("expect the newBuf is the buf, but not")
    45  	}
    46  
    47  	// Re-enable GC
    48  	debug.SetGCPercent(gc)
    49  }
    50  
    51  func BenchmarkByteSlice(b *testing.B) {
    52  	b.Run("Run.N", func(b *testing.B) {
    53  		b.ReportAllocs()
    54  		for i := 0; i < b.N; i++ {
    55  			bs := Get(1024)
    56  			Put(bs)
    57  		}
    58  	})
    59  	b.Run("Run.Parallel", func(b *testing.B) {
    60  		b.ReportAllocs()
    61  		b.RunParallel(func(pb *testing.PB) {
    62  			for pb.Next() {
    63  				bs := Get(1024)
    64  				Put(bs)
    65  			}
    66  		})
    67  	})
    68  }
    69  
    70  func TestByteSlicePool(t *testing.T) {
    71  	pool := NewByteSlicePool()
    72  
    73  	pool.Put(make([]byte, 0))
    74  
    75  	Nil(t, pool.Get(-1))
    76  	Nil(t, pool.Get(0))
    77  }