strconv.go 669 B

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