github.com/songzhibin97/gkit@v1.2.13/tools/bind/internal/bytesconv/bytesconv_test.go (about)

     1  // Copyright 2020 Gin Core Team. All rights reserved.
     2  // Use of this source code is governed by a MIT style
     3  // license that can be found in the LICENSE file.
     4  
     5  package bytesconv
     6  
     7  import (
     8  	"bytes"
     9  	"github.com/songzhibin97/gkit/tools/rand_string"
    10  	"math/rand"
    11  	"testing"
    12  )
    13  
    14  var (
    15  	testString = "Albert Einstein: Logic will get you from A to B. Imagination will take you everywhere."
    16  	testBytes  = []byte(testString)
    17  )
    18  
    19  func rawBytesToStr(b []byte) string {
    20  	return string(b)
    21  }
    22  
    23  func rawStrToBytes(s string) []byte {
    24  	return []byte(s)
    25  }
    26  
    27  // go test -v
    28  
    29  func TestBytesToString(t *testing.T) {
    30  	data := make([]byte, 1024)
    31  	for i := 0; i < 100; i++ {
    32  		rand.Read(data)
    33  		if rawBytesToStr(data) != BytesToString(data) {
    34  			t.Fatal("don't match")
    35  		}
    36  	}
    37  }
    38  
    39  func TestStringToBytes(t *testing.T) {
    40  	for i := 0; i < 100; i++ {
    41  		s := rand_string.RandomLetter(64)
    42  		if !bytes.Equal(rawStrToBytes(s), StringToBytes(s)) {
    43  			t.Fatal("don't match")
    44  		}
    45  	}
    46  }
    47  
    48  // go test -v -run=none -bench=^BenchmarkBytesConv -benchmem=true
    49  
    50  func BenchmarkBytesConvBytesToStrRaw(b *testing.B) {
    51  	for i := 0; i < b.N; i++ {
    52  		rawBytesToStr(testBytes)
    53  	}
    54  }
    55  
    56  func BenchmarkBytesConvBytesToStr(b *testing.B) {
    57  	for i := 0; i < b.N; i++ {
    58  		BytesToString(testBytes)
    59  	}
    60  }
    61  
    62  func BenchmarkBytesConvStrToBytesRaw(b *testing.B) {
    63  	for i := 0; i < b.N; i++ {
    64  		rawStrToBytes(testString)
    65  	}
    66  }
    67  
    68  func BenchmarkBytesConvStrToBytes(b *testing.B) {
    69  	for i := 0; i < b.N; i++ {
    70  		StringToBytes(testString)
    71  	}
    72  }