forked from influxdata/influxdb-comparisons
/
unsafe.go
35 lines (32 loc) · 869 Bytes
/
unsafe.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
30
31
32
33
34
35
package main
import (
"reflect"
"unsafe"
)
// unsafeBytesToString converts a []byte to a string without a heap allocation.
//
// It is unsafe, and is intended to prepare input to short-lived functions
// that require strings.
func unsafeBytesToString(in []byte) string {
src := *(*reflect.SliceHeader)(unsafe.Pointer(&in))
dst := reflect.StringHeader{
Data: src.Data,
Len: src.Len,
}
s := *(*string)(unsafe.Pointer(&dst))
return s
}
// unsafeStringToBytes converts a string to a []byte without a heap allocation.
//
// It is unsafe, and is intended to prepare input to short-lived functions
// that require byte slices.
func unsafeStringToBytes(in string) []byte {
src := *(*reflect.StringHeader)(unsafe.Pointer(&in))
dst := reflect.SliceHeader{
Data: src.Data,
Len: src.Len,
Cap: src.Len,
}
s := *(*[]byte)(unsafe.Pointer(&dst))
return s
}