strconv.go 631 B

1234567891011121314151617181920212223242526
  1. package strconv
  2. import (
  3. "reflect"
  4. "unsafe"
  5. )
  6. // B2S converts byte slice to a string without memory allocation.
  7. // See https://groups.google.com/forum/#!msg/Golang-Nuts/ENgbUzYvCuU/90yGx7GUAgAJ .
  8. func B2S(b []byte) string {
  9. return *(*string)(unsafe.Pointer(&b))
  10. }
  11. // S2B converts string to a byte slice without memory allocation.
  12. //
  13. // Note it may break if string and/or slice header will change
  14. // in the future go versions.
  15. func S2B(s string) (b []byte) {
  16. sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
  17. bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
  18. bh.Data = sh.Data
  19. bh.Cap = sh.Len
  20. bh.Len = sh.Len
  21. return b
  22. }