convert_s2b_old.go 526 B

123456789101112131415161718192021222324
  1. //go:build !go1.20
  2. package utils
  3. import (
  4. "reflect"
  5. "unsafe"
  6. )
  7. const MaxStringLen = 0x7fff0000 // Maximum string length for UnsafeBytes. (decimal: 2147418112)
  8. // UnsafeBytes returns a byte pointer without allocation.
  9. // String length shouldn't be more than 2147418112.
  10. //
  11. //nolint:gosec // unsafe is used for better performance here
  12. func UnsafeBytes(s string) []byte {
  13. if s == "" {
  14. return nil
  15. }
  16. return (*[MaxStringLen]byte)(unsafe.Pointer(
  17. (*reflect.StringHeader)(unsafe.Pointer(&s)).Data),
  18. )[:len(s):len(s)]
  19. }