github.com/LagrangeDev/LagrangeGo@v0.0.0-20240512064304-ad4a85e10cb4/utils/binary/builder_test.go (about)

     1  package binary
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/rand"
     6  	"encoding/hex"
     7  	"testing"
     8  )
     9  
    10  func TestBuilder(t *testing.T) {
    11  	r := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9}
    12  	data := NewBuilder(nil).WriteLenBytes(r).ToBytes()
    13  	exp, err := hex.DecodeString("0009010203040506070809")
    14  	if err != nil {
    15  		t.Fatal(err)
    16  	}
    17  	if !bytes.Equal(data, exp) {
    18  		t.Fatal("expected", hex.EncodeToString(exp), "but got", hex.EncodeToString(data))
    19  	}
    20  }
    21  
    22  // from https://github.com/Mrs4s/MiraiGo/blob/master/binary/writer_test.go
    23  
    24  func BenchmarkNewBuilder128(b *testing.B) {
    25  	test := make([]byte, 128)
    26  	_, _ = rand.Read(test)
    27  	b.StartTimer()
    28  	b.RunParallel(func(pb *testing.PB) {
    29  		for pb.Next() {
    30  			_ = NewBuilder(nil).WriteBytes(test).ToBytes()
    31  		}
    32  	})
    33  }
    34  
    35  func BenchmarkNewBuilder128_3(b *testing.B) {
    36  	test := make([]byte, 128)
    37  	_, _ = rand.Read(test)
    38  	b.StartTimer()
    39  	b.RunParallel(func(pb *testing.PB) {
    40  		for pb.Next() {
    41  			_ = NewBuilder(nil).
    42  				WriteBytes(test).
    43  				WriteBytes(test).
    44  				WriteBytes(test).
    45  				ToBytes()
    46  		}
    47  	})
    48  }
    49  
    50  func BenchmarkNewBuilder128_5(b *testing.B) {
    51  	test := make([]byte, 128)
    52  	_, _ = rand.Read(test)
    53  	b.StartTimer()
    54  	b.RunParallel(func(pb *testing.PB) {
    55  		for pb.Next() {
    56  			_ = NewBuilder(nil).
    57  				WriteBytes(test).
    58  				WriteBytes(test).
    59  				WriteBytes(test).
    60  				WriteBytes(test).
    61  				WriteBytes(test).
    62  				ToBytes()
    63  		}
    64  	})
    65  }