bytesconv.go 489 B

12345678910111213141516171819
  1. package binding
  2. import (
  3. "reflect"
  4. "unsafe"
  5. )
  6. // StringToBytes converts string to byte slice without a memory allocation.
  7. func StringToBytes(s string) (b []byte) {
  8. sh := *(*reflect.StringHeader)(unsafe.Pointer(&s))
  9. bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
  10. bh.Data, bh.Len, bh.Cap = sh.Data, sh.Len, sh.Len
  11. return b
  12. }
  13. // BytesToString converts byte slice to string without a memory allocation.
  14. func BytesToString(b []byte) string {
  15. return *(*string)(unsafe.Pointer(&b))
  16. }