github.com/abemedia/go-don@v0.2.2-0.20240329015135-be88e32bb73b/internal/byteconv/byteconv.go (about)

     1  // Package byteconv provides fast and efficient conversion functions for byte slices and strings.
     2  package byteconv
     3  
     4  import (
     5  	"reflect"
     6  	"unsafe"
     7  )
     8  
     9  // Btoa returns a string from a byte slice without memory allocation.
    10  func Btoa(b []byte) string {
    11  	return *(*string)(unsafe.Pointer(&b))
    12  }
    13  
    14  // Atob returns a byte slice from a string without memory allocation.
    15  func Atob(s string) []byte {
    16  	sp := unsafe.Pointer(&s)
    17  	b := *(*[]byte)(sp)
    18  	(*reflect.SliceHeader)(unsafe.Pointer(&b)).Cap = (*reflect.StringHeader)(sp).Len
    19  	return b
    20  }