unsafe.go 621 B

123456789101112131415161718192021222324252627282930
  1. package sqltypes
  2. import (
  3. "reflect"
  4. "unsafe"
  5. )
  6. // BytesToString casts slice to string without copy
  7. func BytesToString(b []byte) (s string) {
  8. if len(b) == 0 {
  9. return ""
  10. }
  11. bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
  12. sh := reflect.StringHeader{Data: bh.Data, Len: bh.Len}
  13. return *(*string)(unsafe.Pointer(&sh))
  14. }
  15. // StringToBytes casts string to slice without copy
  16. func StringToBytes(s string) []byte {
  17. if len(s) == 0 {
  18. return []byte{}
  19. }
  20. sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
  21. bh := reflect.SliceHeader{Data: sh.Data, Len: sh.Len, Cap: sh.Len}
  22. return *(*[]byte)(unsafe.Pointer(&bh))
  23. }