github.com/fumiama/go-registry@v0.2.7/helper.go (about)

     1  package registry
     2  
     3  import "unsafe"
     4  
     5  // slice is the runtime representation of a slice.
     6  // It cannot be used safely or portably and its representation may
     7  // change in a later release.
     8  //
     9  // Unlike reflect.SliceHeader, its Data field is sufficient to guarantee the
    10  // data it references will not be garbage collected.
    11  type slice struct {
    12  	data unsafe.Pointer
    13  	len  int
    14  	cap  int
    15  }
    16  
    17  // BytesToString 没有内存开销的转换
    18  func BytesToString(b []byte) string {
    19  	return *(*string)(unsafe.Pointer(&b))
    20  }
    21  
    22  // StringToBytes 没有内存开销的转换
    23  func StringToBytes(s string) (b []byte) {
    24  	bh := (*slice)(unsafe.Pointer(&b))
    25  	sh := (*slice)(unsafe.Pointer(&s))
    26  	bh.data = sh.data
    27  	bh.len = sh.len
    28  	bh.cap = sh.len
    29  	return b
    30  }