github.com/GoWebProd/gip@v0.0.0-20230623090727-b60d41d5d320/allocator/alloc_test.go (about)

     1  package allocator
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  )
    10  
    11  func TestAlloc(t *testing.T) {
    12  	data := Alloc(128)
    13  
    14  	if len(data) != 128 {
    15  		t.Fatalf("bad data length: %d", len(data))
    16  	}
    17  
    18  	if cap(data) != 128 {
    19  		t.Fatalf("bad data capacity: %d", cap(data))
    20  	}
    21  
    22  	template := []byte("test template")
    23  
    24  	n := copy(data, template)
    25  
    26  	if !bytes.Equal(data[:n], template) {
    27  		t.Fatal("copied string not equal to source")
    28  	}
    29  
    30  	Free(data)
    31  }
    32  
    33  func TestReallocEmpty(t *testing.T) {
    34  	var data []byte
    35  
    36  	data = nil
    37  
    38  	Realloc(&data, 1024)
    39  
    40  	if len(data) != 0 || cap(data) != 1024 {
    41  		t.Fatalf("bad reallocated slice %d:%d", len(data), cap(data))
    42  	}
    43  }
    44  
    45  func TestRealloc(t *testing.T) {
    46  	data := Alloc(128)
    47  
    48  	Realloc(&data, 1024)
    49  
    50  	if len(data) != 128 || cap(data) != 1024 {
    51  		t.Fatalf("bad reallocated slice %d:%d", len(data), cap(data))
    52  	}
    53  }
    54  
    55  func TestAllocObject(t *testing.T) {
    56  	type testStruct struct {
    57  		A int  `json:"a"`
    58  		B bool `json:"b"`
    59  	}
    60  
    61  	obj := AllocObject[testStruct]()
    62  
    63  	obj.A = 5
    64  	obj.B = true
    65  
    66  	data, err := json.Marshal(obj)
    67  	if err != nil {
    68  		t.Fatalf("json error: %v", err)
    69  	}
    70  
    71  	if !bytes.Equal(data, []byte(`{"a":5,"b":true}`)) {
    72  		t.Fatalf("bad json: %s", data)
    73  	}
    74  
    75  	FreeObject(obj)
    76  }
    77  
    78  func BenchmarkJemalloc(b *testing.B) {
    79  	assert := assert.New(b)
    80  
    81  	for i := 0; i < b.N; i++ {
    82  		a := AllocObject[testStruct]()
    83  
    84  		assert.NotNil(a)
    85  
    86  		FreeObject(a)
    87  	}
    88  }
    89  func BenchmarkNew(b *testing.B) {
    90  	assert := assert.New(b)
    91  
    92  	for i := 0; i < b.N; i++ {
    93  		a := new(testStruct)
    94  
    95  		assert.NotNil(a)
    96  	}
    97  }
    98  
    99  type testStruct struct {
   100  	A int  `json:"a"`
   101  	B bool `json:"b"`
   102  }