Skip to content
Snippets Groups Projects
Commit 6b71eb1e authored by Wolfgang Welz's avatar Wolfgang Welz
Browse files

Use optimized version to convert bytes and string

parent 8044edd0
No related branches found
No related tags found
No related merge requests found
package typeutils package typeutils
import ( import (
"reflect"
"unsafe" "unsafe"
) )
func BytesToString(b []byte) string { // Checks whether an interface is nil or has the value nil.
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
return *(*string)(unsafe.Pointer(&reflect.StringHeader{Data: bh.Data, Len: bh.Len}))
}
func StringToBytes(str string) []byte {
hdr := (*reflect.StringHeader)(unsafe.Pointer(&str))
return *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{Data: hdr.Data, Len: hdr.Len, Cap: hdr.Len}))
}
func IsInterfaceNil(param interface{}) bool { func IsInterfaceNil(param interface{}) bool {
return param == nil || (*[2]uintptr)(unsafe.Pointer(&param))[1] == 0 return param == nil || (*[2]uintptr)(unsafe.Pointer(&param))[1] == 0
} }
package typeutils
import (
"reflect"
"runtime"
"unsafe"
)
// Converts a slice of bytes into a string without performing a copy.
// NOTE: This is an unsafe operation and may lead to problems if the bytes
// passed as argument are changed while the string is used. No checking whether
// bytes are valid UTF-8 data is performed.
func BytesToString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
// Converts a string into a slice of bytes without performing a copy.
// NOTE: This is an unsafe operation and may lead to problems if the bytes are changed.
func StringToBytes(s string) []byte {
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
b := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
Data: sh.Data,
Len: sh.Len,
Cap: sh.Len,
}))
// ensure the underlying string doesn't get GC'ed before the assignment happens
runtime.KeepAlive(&s)
return b
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment