github.com/Finschia/finschia-sdk@v0.48.1/internal/conv/string_test.go (about)

     1  package conv
     2  
     3  import (
     4  	"runtime"
     5  	"strconv"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/stretchr/testify/suite"
    10  )
    11  
    12  func TestStringSuite(t *testing.T) {
    13  	suite.Run(t, new(StringSuite))
    14  }
    15  
    16  type StringSuite struct{ suite.Suite }
    17  
    18  func unsafeConvertStr() []byte {
    19  	return UnsafeStrToBytes("abc")
    20  }
    21  
    22  func (s *StringSuite) TestUnsafeStrToBytes() {
    23  	// we convert in other function to trigger GC. We want to check that
    24  	// the underlying array in []bytes is accessible after GC will finish swapping.
    25  	for i := 0; i < 5; i++ {
    26  		b := unsafeConvertStr()
    27  		runtime.GC()
    28  		<-time.NewTimer(2 * time.Millisecond).C
    29  		b2 := append(b, 'd')
    30  		s.Equal("abc", string(b))
    31  		s.Equal("abcd", string(b2))
    32  	}
    33  }
    34  
    35  func unsafeConvertBytes() string {
    36  	return UnsafeBytesToStr([]byte("abc"))
    37  }
    38  
    39  func (s *StringSuite) TestUnsafeBytesToStr() {
    40  	// we convert in other function to trigger GC. We want to check that
    41  	// the underlying array in []bytes is accessible after GC will finish swapping.
    42  	for i := 0; i < 5; i++ {
    43  		str := unsafeConvertBytes()
    44  		runtime.GC()
    45  		<-time.NewTimer(2 * time.Millisecond).C
    46  		s.Equal("abc", str)
    47  	}
    48  }
    49  
    50  func BenchmarkUnsafeStrToBytes(b *testing.B) {
    51  	for i := 0; i < b.N; i++ {
    52  		UnsafeStrToBytes(strconv.Itoa(i))
    53  	}
    54  }