add hack for nocopy for string <-> slice

This commit is contained in:
siddontang 2014-04-11 14:21:50 +08:00
parent ec6187efd9
commit e02d4a31aa
2 changed files with 63 additions and 0 deletions

27
hack/hack.go Normal file
View File

@ -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
}

36
hack/hack_test.go Normal file
View File

@ -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))
}
}