diff --git a/hack/hack.go b/hack/hack.go new file mode 100644 index 0000000..74ee83c --- /dev/null +++ b/hack/hack.go @@ -0,0 +1,27 @@ +package hack + +import ( + "reflect" + "unsafe" +) + +// no copy to change slice to string +// use your own risk +func String(b []byte) (s string) { + pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b)) + pstring := (*reflect.StringHeader)(unsafe.Pointer(&s)) + pstring.Data = pbytes.Data + pstring.Len = pbytes.Len + return +} + +// no copy to change string to slice +// use your own risk +func Slice(s string) (b []byte) { + pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b)) + pstring := (*reflect.StringHeader)(unsafe.Pointer(&s)) + pbytes.Data = pstring.Data + pbytes.Len = pstring.Len + pbytes.Cap = pstring.Len + return +} diff --git a/hack/hack_test.go b/hack/hack_test.go new file mode 100644 index 0000000..7b11b0b --- /dev/null +++ b/hack/hack_test.go @@ -0,0 +1,36 @@ +package hack + +import ( + "bytes" + "testing" +) + +func TestString(t *testing.T) { + b := []byte("hello world") + a := String(b) + + if a != "hello world" { + t.Fatal(a) + } + + b[0] = 'a' + + if a != "aello world" { + t.Fatal(a) + } + + b = append(b, "abc"...) + if a != "aello world" { + t.Fatal(a) + } +} + +func TestByte(t *testing.T) { + a := "hello world" + + b := Slice(a) + + if !bytes.Equal(b, []byte("hello world")) { + t.Fatal(string(b)) + } +}