bytetostr.go 1017 B

12345678910111213141516171819202122232425262728293031323334
  1. /*
  2. https://github.com/mailru/easyjson/blob/master/jlexer/bytestostr.go
  3. */
  4. package main
  5. import (
  6. "fmt"
  7. "reflect"
  8. "unsafe"
  9. )
  10. // bytesToStr сорздаёт строку, указывающую на слайс байт, чтобы избежать копирования.
  11. //
  12. // Warning: the string returned by the function should be used with care, as the whole input data
  13. // chunk may be either blocked from being freed by GC because of a single string or the buffer.Data
  14. // may be garbage-collected even when the string exists.
  15. func bytesToStr(data []byte) string {
  16. h := (*reflect.SliceHeader)(unsafe.Pointer(&data))
  17. fmt.Printf("type: %T, value: %+v\n", h, h)
  18. fmt.Printf("type: %T, value: %+v\n", h.Data, h.Data)
  19. shdr := reflect.StringHeader{Data: h.Data, Len: h.Len}
  20. fmt.Printf("type: %T, value: %+v\n", shdr, shdr)
  21. return *(*string)(unsafe.Pointer(&shdr))
  22. }
  23. func main() {
  24. data := []byte(`some test`)
  25. str := bytesToStr(data)
  26. // str := string(data)
  27. fmt.Printf("type: %T, value: %+v\n", str, str)
  28. }