-
Notifications
You must be signed in to change notification settings - Fork 0
/
bs.go
29 lines (25 loc) · 834 Bytes
/
bs.go
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
// https://github.com/panjf2000/gnet/blob/dev/internal/bs/bs.go
package aerrors
import (
"reflect"
"unsafe"
)
// BytesToString converts byte slice to a string without memory allocation.
//
// Note it may break if the implementation of string or slice header changes in the future go versions.
func BytesToString(b []byte) string {
/* #nosec G103 */
return *(*string)(unsafe.Pointer(&b))
}
// StringToBytes converts string to a byte slice without memory allocation.
//
// Note it may break if the implementation of string or slice header changes in the future go versions.
// nolint
func StringToBytes(s string) (b []byte) {
/* #nosec G103 */
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
/* #nosec G103 */
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
bh.Data, bh.Len, bh.Cap = sh.Data, sh.Len, sh.Len
return b
}