github.com/metacubex/mihomo@v1.18.5/common/pool/alloc_test.go (about)

     1  package pool
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/stretchr/testify/assert"
     7  	"github.com/zhangyunhao116/fastrand"
     8  )
     9  
    10  func TestAllocGet(t *testing.T) {
    11  	alloc := NewAllocator()
    12  	assert.Nil(t, alloc.Get(0))
    13  	assert.Equal(t, 1, len(alloc.Get(1)))
    14  	assert.Equal(t, 2, len(alloc.Get(2)))
    15  	assert.Equal(t, 3, len(alloc.Get(3)))
    16  	assert.Equal(t, 64, cap(alloc.Get(3)))
    17  	assert.Equal(t, 64, cap(alloc.Get(4)))
    18  	assert.Equal(t, 1023, len(alloc.Get(1023)))
    19  	assert.Equal(t, 1024, cap(alloc.Get(1023)))
    20  	assert.Equal(t, 1024, len(alloc.Get(1024)))
    21  	assert.Equal(t, 65536, len(alloc.Get(65536)))
    22  	assert.Equal(t, 65537, len(alloc.Get(65537)))
    23  }
    24  
    25  func TestAllocPut(t *testing.T) {
    26  	alloc := NewAllocator()
    27  	assert.Nil(t, alloc.Put(nil), "put nil misbehavior")
    28  	assert.NotNil(t, alloc.Put(make([]byte, 3)), "put elem:3 []bytes misbehavior")
    29  	assert.Nil(t, alloc.Put(make([]byte, 4)), "put elem:4 []bytes misbehavior")
    30  	assert.Nil(t, alloc.Put(make([]byte, 1023, 1024)), "put elem:1024 []bytes misbehavior")
    31  	assert.Nil(t, alloc.Put(make([]byte, 65536)), "put elem:65536 []bytes misbehavior")
    32  	assert.Nil(t, alloc.Put(make([]byte, 65537)), "put elem:65537 []bytes misbehavior")
    33  }
    34  
    35  func TestAllocPutThenGet(t *testing.T) {
    36  	alloc := NewAllocator()
    37  	data := alloc.Get(4)
    38  	alloc.Put(data)
    39  	newData := alloc.Get(4)
    40  
    41  	assert.Equal(t, cap(data), cap(newData), "different cap while alloc.Get()")
    42  }
    43  
    44  func BenchmarkMSB(b *testing.B) {
    45  	for i := 0; i < b.N; i++ {
    46  		msb(fastrand.Int())
    47  	}
    48  }