github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/perf/bbp/pool_test.go (about)

     1  package bbp
     2  
     3  import (
     4  	"math/rand"
     5  	"testing"
     6  	"time"
     7  )
     8  
     9  func TestPoolCalibrate(t *testing.T) {
    10  	calls := defaultCalibrateCalls
    11  	for i := 0; i < poolSize*calls; i++ {
    12  		n := 1004
    13  		if i%15 == 0 {
    14  			n = rand.Intn(15234)
    15  		}
    16  		testGetPut(t, n)
    17  	}
    18  }
    19  
    20  func TestPoolVariousSizesSerial(t *testing.T) {
    21  	testPoolVariousSizes(t)
    22  }
    23  
    24  func TestPoolVariousSizesConcurrent(t *testing.T) {
    25  	concurrency := 5
    26  	ch := make(chan struct{}, 5)
    27  	for i := 0; i < concurrency; i++ {
    28  		go func() {
    29  			testPoolVariousSizes(t)
    30  			ch <- struct{}{}
    31  		}()
    32  	}
    33  	timeout := 10 * time.Second
    34  	for i := 0; i < concurrency; i++ {
    35  		select {
    36  		case <-ch:
    37  		case <-time.After(timeout):
    38  			t.Fatalf("%v timeout", timeout)
    39  		}
    40  	}
    41  }
    42  
    43  func testPoolVariousSizes(t *testing.T) {
    44  	for i := 0; i < poolSize-minPoolIdx; i++ {
    45  		n := sizedPools[i].size
    46  
    47  		testGetPut(t, n)
    48  		testGetPut(t, n+1)
    49  		testGetPut(t, n-1)
    50  	}
    51  }
    52  
    53  var testPool Pool
    54  
    55  func testGetPut(t *testing.T, n int) {
    56  	bb := testPool.Get()
    57  	if len(bb) > 0 {
    58  		t.Fatalf("non-empty byte buffer returned from Pool.Get")
    59  	}
    60  	bb = allocNBytes(bb, n)
    61  	testPool.Put(bb)
    62  }
    63  
    64  func allocNBytes(dst []byte, n int) []byte {
    65  	diff := n - cap(dst)
    66  	if diff <= 0 {
    67  		return dst[:n]
    68  	}
    69  	return append(dst[:cap(dst)], make([]byte, diff)...)
    70  }