faststr.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. package base64x
  2. import (
  3. `reflect`
  4. `unsafe`
  5. )
  6. func mem2str(v []byte) (s string) {
  7. (*reflect.StringHeader)(unsafe.Pointer(&s)).Len = (*reflect.SliceHeader)(unsafe.Pointer(&v)).Len
  8. (*reflect.StringHeader)(unsafe.Pointer(&s)).Data = (*reflect.SliceHeader)(unsafe.Pointer(&v)).Data
  9. return
  10. }
  11. func str2mem(s string) (v []byte) {
  12. (*reflect.SliceHeader)(unsafe.Pointer(&v)).Cap = (*reflect.StringHeader)(unsafe.Pointer(&s)).Len
  13. (*reflect.SliceHeader)(unsafe.Pointer(&v)).Len = (*reflect.StringHeader)(unsafe.Pointer(&s)).Len
  14. (*reflect.SliceHeader)(unsafe.Pointer(&v)).Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data
  15. return
  16. }
  17. func mem2addr(v []byte) unsafe.Pointer {
  18. return *(*unsafe.Pointer)(unsafe.Pointer(&v))
  19. }
  20. // NoEscape hides a pointer from escape analysis. NoEscape is
  21. // the identity function but escape analysis doesn't think the
  22. // output depends on the input. NoEscape is inlined and currently
  23. // compiles down to zero instructions.
  24. // USE CAREFULLY!
  25. //go:nosplit
  26. //goland:noinspection GoVetUnsafePointer
  27. func noEscape(p unsafe.Pointer) unsafe.Pointer {
  28. x := uintptr(p)
  29. return unsafe.Pointer(x ^ 0)
  30. }