github.com/fmstephe/unsafeutil@v1.0.0/convert.go (about)

     1  package unsafeutil
     2  
     3  import (
     4  	"unsafe"
     5  )
     6  
     7  // stringHeader is the runtime representation of a string.
     8  // It should be identical to reflect.StringHeader
     9  type stringHeader struct {
    10  	data      unsafe.Pointer
    11  	stringLen int
    12  }
    13  
    14  // sliceHeader is the runtime representation of a slice.
    15  // It should be identical to reflect.sliceHeader
    16  type sliceHeader struct {
    17  	data     unsafe.Pointer
    18  	sliceLen int
    19  	sliceCap int
    20  }
    21  
    22  // Unsafely converts s into a byte slice.
    23  // If you modify b, then s will also be modified. This violates the
    24  // property that strings are immutable.
    25  func StringToBytes(s string) (b []byte) {
    26  	stringHeader := (*stringHeader)(unsafe.Pointer(&s))
    27  	sliceHeader := (*sliceHeader)(unsafe.Pointer(&b))
    28  	sliceHeader.data = stringHeader.data
    29  	sliceHeader.sliceLen = len(s)
    30  	sliceHeader.sliceCap = len(s)
    31  	return b
    32  }
    33  
    34  // Unsafely converts b into a string.
    35  // If you modify b, then s will also be modified. This violates the
    36  // property that strings are immutable.
    37  func BytesToString(b []byte) (s string) {
    38  	sliceHeader := (*sliceHeader)(unsafe.Pointer(&b))
    39  	stringHeader := (*stringHeader)(unsafe.Pointer(&s))
    40  	stringHeader.data = sliceHeader.data
    41  	stringHeader.stringLen = len(b)
    42  	return s
    43  }