github.com/gofiber/fiber/v2@v2.47.0/utils/convert_s2b_old.go (about)

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