Skip to content

Commit

Permalink
add hack module
Browse files Browse the repository at this point in the history
  • Loading branch information
siddontang committed Jul 15, 2014
1 parent 957a9ee commit e953887
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
27 changes: 27 additions & 0 deletions 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
}
37 changes: 37 additions & 0 deletions hack/hack_test.go
@@ -0,0 +1,37 @@
package hack

import (
"bytes"
"encoding/binary"
"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))
}
}

0 comments on commit e953887

Please sign in to comment.