bytes_unsafe.go 1.2 KB

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