github.com/clubpay/ronykit/kit@v0.14.4-0.20240515065620-d0dace45cbc7/utils/unsafe.go (about) 1 //go:build !go1.19 && !go1.18 2 3 package utils 4 5 import "unsafe" 6 7 // ByteToStr converts byte slice to a string without memory allocation. 8 // Note it may break if string and/or slice header will change 9 // in the future go versions. 10 func ByteToStr(bts []byte) string { 11 if len(bts) == 0 { 12 return "" 13 } 14 15 return unsafe.String(unsafe.SliceData(bts), len(bts)) 16 } 17 18 // B2S is alias for ByteToStr. 19 func B2S(bts []byte) string { 20 return ByteToStr(bts) 21 } 22 23 // StrToByte converts string to a byte slice without memory allocation. 24 // Note it may break if string and/or slice header will change 25 // in the future go versions. 26 func StrToByte(str string) (b []byte) { 27 if len(str) == 0 { 28 return nil 29 } 30 31 return unsafe.Slice(unsafe.StringData(str), len(str)) 32 } 33 34 // S2B is alias for StrToByte. 35 func S2B(str string) []byte { 36 return StrToByte(str) 37 }