convert_s2b_old.go 544 B

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