Signed-off-by: wyrapeseed <wyrapeseed@outlook.com> Co-authored-by: Alex | Cosmos Labs <alex@cosmoslabs.io>
59 lines
1.2 KiB
Go
59 lines
1.2 KiB
Go
package conv
|
|
|
|
import (
|
|
"runtime"
|
|
"strconv"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/stretchr/testify/suite"
|
|
)
|
|
|
|
func TestStringSuite(t *testing.T) {
|
|
suite.Run(t, new(StringSuite))
|
|
}
|
|
|
|
type StringSuite struct{ suite.Suite }
|
|
|
|
func unsafeConvertStr() []byte {
|
|
return UnsafeStrToBytes("abc")
|
|
}
|
|
|
|
func (s *StringSuite) TestUnsafeStrToBytes() {
|
|
// we convert in another function to trigger GC. We want to check that
|
|
// the underlying array in []bytes is accessible after GC will finish swapping.
|
|
for range 5 {
|
|
b := unsafeConvertStr()
|
|
runtime.GC()
|
|
timer := time.NewTimer(2 * time.Millisecond)
|
|
<-timer.C
|
|
timer.Stop()
|
|
b2 := append(b, 'd')
|
|
s.Equal("abc", string(b))
|
|
s.Equal("abcd", string(b2))
|
|
}
|
|
}
|
|
|
|
func unsafeConvertBytes() string {
|
|
return UnsafeBytesToStr([]byte("abc"))
|
|
}
|
|
|
|
func (s *StringSuite) TestUnsafeBytesToStr() {
|
|
// we convert in another function to trigger GC. We want to check that
|
|
// the underlying array in []bytes is accessible after GC will finish swapping.
|
|
for range 5 {
|
|
str := unsafeConvertBytes()
|
|
runtime.GC()
|
|
timer := time.NewTimer(2 * time.Millisecond)
|
|
<-timer.C
|
|
timer.Stop()
|
|
s.Equal("abc", str)
|
|
}
|
|
}
|
|
|
|
func BenchmarkUnsafeStrToBytes(b *testing.B) {
|
|
for i := 0; b.Loop(); i++ {
|
|
UnsafeStrToBytes(strconv.Itoa(i))
|
|
}
|
|
}
|