unsafe.go 1.0 KB

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