github.com/Azareal/Gosora@v0.0.0-20210729070923-553e66b59003/uutils/utils.go (about)

     1  package uutils
     2  
     3  import (
     4  	"reflect"
     5  	"runtime"
     6  	"unsafe"
     7  )
     8  
     9  // TODO: Add a safe build mode for things like Google Appengine
    10  
    11  func StringToBytes(s string) (bytes []byte) {
    12  	str := (*reflect.StringHeader)(unsafe.Pointer(&s))
    13  	slice := (*reflect.SliceHeader)(unsafe.Pointer(&bytes))
    14  	slice.Data = str.Data
    15  	slice.Len = str.Len
    16  	slice.Cap = str.Len
    17  	runtime.KeepAlive(&s)
    18  	return bytes
    19  }
    20  
    21  func BytesToString(bytes []byte) (s string) {
    22  	slice := (*reflect.SliceHeader)(unsafe.Pointer(&bytes))
    23  	str := (*reflect.StringHeader)(unsafe.Pointer(&s))
    24  	str.Data = slice.Data
    25  	str.Len = slice.Len
    26  	runtime.KeepAlive(&bytes)
    27  	return s
    28  }
    29  
    30  //go:noescape
    31  //go:linkname nanotime runtime.nanotime
    32  func nanotime() int64
    33  
    34  func Nanotime() int64 {
    35  	return nanotime()
    36  }