github.com/clubpay/ronykit/kit@v0.14.4-0.20240515065620-d0dace45cbc7/utils/unsafe_go119.go (about) 1 //go:build go1.19 || go1.18 2 3 package utils 4 5 import ( 6 "unsafe" 7 8 "github.com/goccy/go-reflect" 9 ) 10 11 // ByteToStr converts byte slice to a string without memory allocation. 12 // Note it may break if string and/or slice header will change 13 // in the future go versions. 14 func ByteToStr(bts []byte) string { 15 bh := (*reflect.SliceHeader)(unsafe.Pointer(&bts)) 16 17 var s string 18 sh := (*reflect.StringHeader)(unsafe.Pointer(&s)) 19 sh.Data = bh.Data 20 sh.Len = bh.Len 21 22 return s 23 } 24 25 // B2S is alias for ByteToStr. 26 func B2S(bts []byte) string { 27 return ByteToStr(bts) 28 } 29 30 // StrToByte converts string to a byte slice without memory allocation. 31 // Note it may break if string and/or slice header will change 32 // in the future go versions. 33 func StrToByte(str string) (b []byte) { 34 bh := (*reflect.SliceHeader)(unsafe.Pointer(&b)) 35 sh := (*reflect.StringHeader)(unsafe.Pointer(&str)) 36 bh.Data = sh.Data 37 bh.Len = sh.Len 38 bh.Cap = sh.Len 39 40 return b 41 } 42 43 // S2B is alias for StrToByte. 44 func S2B(str string) []byte { 45 return StrToByte(str) 46 }