bytes_unsafe.go

 1// +build !appengine,!appenginevm
 2
 3package jsonparser
 4
 5import (
 6	"reflect"
 7	"strconv"
 8	"unsafe"
 9	"runtime"
10)
11
12//
13// The reason for using *[]byte rather than []byte in parameters is an optimization. As of Go 1.6,
14// the compiler cannot perfectly inline the function when using a non-pointer slice. That is,
15// the non-pointer []byte parameter version is slower than if its function body is manually
16// inlined, whereas the pointer []byte version is equally fast to the manually inlined
17// version. Instruction count in assembly taken from "go tool compile" confirms this difference.
18//
19// TODO: Remove hack after Go 1.7 release
20//
21func equalStr(b *[]byte, s string) bool {
22	return *(*string)(unsafe.Pointer(b)) == s
23}
24
25func parseFloat(b *[]byte) (float64, error) {
26	return strconv.ParseFloat(*(*string)(unsafe.Pointer(b)), 64)
27}
28
29// A hack until issue golang/go#2632 is fixed.
30// See: https://github.com/golang/go/issues/2632
31func bytesToString(b *[]byte) string {
32	return *(*string)(unsafe.Pointer(b))
33}
34
35func StringToBytes(s string) []byte {
36	b := make([]byte, 0, 0)
37	bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
38	sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
39	bh.Data = sh.Data
40	bh.Cap = sh.Len
41	bh.Len = sh.Len
42	runtime.KeepAlive(s)
43	return b
44}