github.com/inaneverb/ekacore/ekaunsafe/v4@v4.0.0/string.go (about)

     1  // Copyright © 2020-2023. All rights reserved.
     2  // Author: Ilya Stroy.
     3  // Contacts: iyuryevich@pm.me, https://github.com/qioalice
     4  // License: https://opensource.org/licenses/MIT
     5  
     6  package ekaunsafe
     7  
     8  import (
     9  	"reflect"
    10  	"unsafe"
    11  )
    12  
    13  // BytesToString converts byte slice to a string without memory allocation.
    14  func BytesToString(b []byte) string {
    15  	return *(*string)(unsafe.Pointer(&b))
    16  }
    17  
    18  // StringToBytes converts string to a byte slice without memory allocation.
    19  //
    20  // WARNING! PANIC CAUTION!
    21  // It will lead to panic if you're going to modify a byte slice
    22  // that is received from the string literal. You should modify only strings
    23  // that are dynamically allocated (in heap), not in RO memory. Example:
    24  //
    25  //		var b = StringToBytes("string")
    26  //		b[0] = 0         // <-- panic here
    27  //	 b = append(b, 0) // but this will work, because of copy
    28  func StringToBytes(s string) (b []byte) {
    29  
    30  	var sh = (*reflect.StringHeader)(unsafe.Pointer(&s))
    31  	var bh = (*reflect.SliceHeader)(unsafe.Pointer(&b))
    32  
    33  	bh.Data = sh.Data
    34  	bh.Len = len(s) // We need to ensure s is still alive
    35  	bh.Cap = len(s) // We need to ensure s is still alive
    36  
    37  	// https://groups.google.com/g/golang-nuts/c/Zsfk-VMd_fU
    38  
    39  	return b
    40  }