github.com/MetalBlockchain/metalgo@v1.11.9/utils/bytes_test.go (about) 1 // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. 2 // See the file LICENSE for licensing terms. 3 4 package utils 5 6 import ( 7 "math" 8 "math/rand" 9 "strconv" 10 "testing" 11 12 "github.com/stretchr/testify/require" 13 ) 14 15 // Verify that [intSize] is correctly set based on the word size. This test uses 16 // [math.MaxInt] to detect the word size. 17 func TestIntSize(t *testing.T) { 18 require := require.New(t) 19 20 require.Contains([]int{32, 64}, intSize) 21 if intSize == 32 { 22 require.Equal(math.MaxInt32, math.MaxInt) 23 } else { 24 require.Equal(math.MaxInt64, math.MaxInt) 25 } 26 } 27 28 func TestBytesPool(t *testing.T) { 29 require := require.New(t) 30 31 p := NewBytesPool() 32 for i := 0; i < 128; i++ { 33 bytes := p.Get(i) 34 require.NotNil(bytes) 35 require.Len(*bytes, i) 36 p.Put(bytes) 37 } 38 } 39 40 func BenchmarkBytesPool_Constant(b *testing.B) { 41 sizes := []int{ 42 0, 43 8, 44 16, 45 32, 46 64, 47 256, 48 2048, 49 } 50 for _, size := range sizes { 51 b.Run(strconv.Itoa(size), func(b *testing.B) { 52 p := NewBytesPool() 53 for i := 0; i < b.N; i++ { 54 p.Put(p.Get(size)) 55 } 56 }) 57 } 58 } 59 60 func BenchmarkBytesPool_Descending(b *testing.B) { 61 p := NewBytesPool() 62 for i := 0; i < b.N; i++ { 63 for size := 100_000; size > 0; size-- { 64 p.Put(p.Get(size)) 65 } 66 } 67 } 68 69 func BenchmarkBytesPool_Ascending(b *testing.B) { 70 p := NewBytesPool() 71 for i := 0; i < b.N; i++ { 72 for size := 0; size < 100_000; size++ { 73 p.Put(p.Get(size)) 74 } 75 } 76 } 77 78 func BenchmarkBytesPool_Random(b *testing.B) { 79 p := NewBytesPool() 80 sizes := make([]int, 1_000) 81 for i := range sizes { 82 sizes[i] = rand.Intn(100_000) //#nosec G404 83 } 84 85 b.ResetTimer() 86 for i := 0; i < b.N; i++ { 87 for _, size := range sizes { 88 p.Put(p.Get(size)) 89 } 90 } 91 }