internal: create package for unsafe bytes convertion (#8733)
Co-authored-by: Alessio Treglia <alessio@tendermint.com>
This commit is contained in:
co-authored by
Alessio Treglia
parent
0792db78b8
commit
5f2b90c3c7
@@ -0,0 +1,23 @@
|
||||
package conv
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// UnsafeStrToBytes uses unsafe to convert string into byte array. Returned bytes
|
||||
// must not be altered after this function is called as it will cause a segmentation fault.
|
||||
func UnsafeStrToBytes(s string) []byte {
|
||||
var buf = *(*[]byte)(unsafe.Pointer(&s))
|
||||
(*reflect.SliceHeader)(unsafe.Pointer(&buf)).Cap = len(s)
|
||||
return buf
|
||||
}
|
||||
|
||||
// UnsafeBytesToStr is meant to make a zero allocation conversion
|
||||
// from []byte -> string to speed up operations, it is not meant
|
||||
// to be used generally, but for a specific pattern to delete keys
|
||||
// from a map.
|
||||
func UnsafeBytesToStr(b []byte) string {
|
||||
hdr := (*reflect.StringHeader)(unsafe.Pointer(&b))
|
||||
return *(*string)(unsafe.Pointer(hdr))
|
||||
}
|
||||
Reference in New Issue
Block a user