Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
957a9ee
commit e953887
Showing
2 changed files
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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)) | ||
} | ||
} |