1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
package stringsx
import (
"fmt"
"reflect"
"runtime"
"testing"
"unsafe"
)
func checkSame(t *testing.T, s1, s2 string, shouldBeSame bool) {
t.Helper()
// Just to be sure:
if s1 != s2 {
t.Errorf("Excected match")
}
hdr1 := (*reflect.StringHeader)(unsafe.Pointer(&s1))
hdr2 := (*reflect.StringHeader)(unsafe.Pointer(&s2))
if shouldBeSame {
if hdr1.Data != hdr2.Data {
t.Errorf("Expected to be same")
}
} else {
if hdr1.Data == hdr2.Data {
t.Errorf("Expected to not be the same")
}
}
runtime.KeepAlive(s1)
runtime.KeepAlive(s2)
}
func TestPool(t *testing.T) {
// // Test the compiler
checkSame(t, "abc", "abc", true)
checkSame(t, "", "", true)
x := int64(827364536372)
s1 := fmt.Sprint(x)
s2 := fmt.Sprint(x)
checkSame(t, s1, s1, true) // This is just to test checkSame
checkSame(t, s1, s2, false)
pool := NewPool()
s1i := pool.Interned(s1)
checkSame(t, s1, s1i, true)
s2i := pool.Interned(s2)
checkSame(t, s2, s2i, false) // This will be false: pool will return s1
checkSame(t, s1, s2i, true)
se := ""
sei := pool.Interned(se)
checkSame(t, se, sei, true)
}
|