| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 |
- package pool
- import (
- "math/bits"
- "math/rand"
- "testing"
- )
- func TestGet(t *testing.T) {
- if Get(0) != nil {
- t.Fatal(0)
- return
- }
- if len(Get(1)) != 1 {
- t.Fatal(1)
- return
- }
- if len(Get(2)) != 2 {
- t.Fatal(2)
- return
- }
- if len(Get(3)) != 3 || cap(Get(3)) != 64 {
- t.Fatal(3)
- return
- }
- if len(Get(4)) != 4 {
- t.Fatal(4)
- return
- }
- if len(Get(1023)) != 1023 || cap(Get(1023)) != 1024 {
- t.Fatal(1023)
- return
- }
- if len(Get(1024)) != 1024 {
- t.Fatal(1024)
- return
- }
- if len(Get(65536)) != 65536 {
- t.Fatal(65536)
- return
- }
- }
- func TestPut(t *testing.T) {
- if err := Put(nil); err == nil {
- t.Fatal("put nil misbehavior")
- return
- }
- b := make([]byte, 3)
- if err := Put(b); err == nil {
- t.Fatal("put elem:3 []bytes misbehavior")
- return
- }
- b = make([]byte, 64)
- if err := Put(b); err != nil {
- t.Fatal("put elem:4 []bytes misbehavior")
- return
- }
- b = make([]byte, 1023, 1024)
- if err := Put(b); err != nil {
- t.Fatal("put elem:1024 []bytes misbehavior")
- return
- }
- b = make([]byte, 65536)
- if err := Put(b); err != nil {
- t.Fatal("put elem:65536 []bytes misbehavior")
- return
- }
- }
- func TestPutThenGet(t *testing.T) {
- data := Get(4)
- Put(data)
- newData := Get(4)
- if cap(data) != cap(newData) {
- t.Fatal("different cap while Get()")
- return
- }
- }
- func BenchmarkMSB(b *testing.B) {
- for b.Loop() {
- msb(rand.Int())
- }
- }
- func BenchmarkAlloc(b *testing.B) {
- for i := 0; b.Loop(); i++ {
- pbuf := Get(i % 65536)
- Put(pbuf)
- }
- }
- func TestDebrujin(t *testing.T) {
- for i := 1; i <= 65536; i++ {
- a := int(msb(i))
- b := bits.Len(uint(i))
- if a+1 != b {
- t.Fatal("debrujin")
- return
- }
- }
- }
- func TestPutSizeMismatch(t *testing.T) {
- data := Get(1024)
- if data == nil {
- t.Fatal("Get(1024) failed")
- }
- // simulate a slice operation that reduces capacity
- // e.g. data[1:]
- // cap becomes 1023
- sliced := (data)[1:]
- if err := Put(sliced); err == nil {
- t.Fatal("Put() should fail with mismatched capacity")
- }
- // simulate a slice operation that keeps capacity
- // e.g. data[:512]
- // cap remains 1024
- sliced = (data)[:512]
- if err := Put(sliced); err != nil {
- t.Fatal("Put() should succeed with matched capacity")
- }
- }
|