unsafe.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. //go:build !purego && !appengine
  2. // +build !purego,!appengine
  3. package msgp
  4. import (
  5. "reflect"
  6. "unsafe"
  7. )
  8. // NOTE:
  9. // all of the definition in this file
  10. // should be repeated in appengine.go,
  11. // but without using unsafe
  12. const (
  13. // spec says int and uint are always
  14. // the same size, but that int/uint
  15. // size may not be machine word size
  16. smallint = unsafe.Sizeof(int(0)) == 4
  17. )
  18. // UnsafeString returns the byte slice as a volatile string
  19. // THIS SHOULD ONLY BE USED BY THE CODE GENERATOR.
  20. // THIS IS EVIL CODE.
  21. // YOU HAVE BEEN WARNED.
  22. func UnsafeString(b []byte) string {
  23. sh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
  24. return *(*string)(unsafe.Pointer(&reflect.StringHeader{Data: sh.Data, Len: sh.Len}))
  25. }
  26. // UnsafeBytes returns the string as a byte slice
  27. // THIS SHOULD ONLY BE USED BY THE CODE GENERATOR.
  28. // THIS IS EVIL CODE.
  29. // YOU HAVE BEEN WARNED.
  30. func UnsafeBytes(s string) []byte {
  31. return *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
  32. Len: len(s),
  33. Cap: len(s),
  34. Data: (*(*reflect.StringHeader)(unsafe.Pointer(&s))).Data,
  35. }))
  36. }