blob: d96acfbbe38c58ef69883daecfc47135bdf702c9 (
plain)
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
|
package utils
import (
"reflect"
"unsafe"
)
// AsBytes returns a slice that refers to the data backing the string s.
func AsBytes(s string) []byte {
// get the pointer to the data of the string
p := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&s)).Data)
var b []byte
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&b))
hdr.Data = uintptr(p)
// we need to set the cap and len for the string to byte convert
// because string is shorter than []bytes
hdr.Cap = len(s)
hdr.Len = len(s)
// checker to check mutable access to the data
SetChecker(b)
return b
}
// AsString returns a string that refers to the data backing the slice s.
func AsString(b []byte) string {
p := unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&b)).Data)
var s string
hdr := (*reflect.StringHeader)(unsafe.Pointer(&s))
hdr.Data = uintptr(p)
hdr.Len = len(b)
// checker to check mutable access to the data
SetChecker(b)
return s
}
|