reflect: add Convert() for string -> []byte and []byte -> string

This commit is contained in:
Damian Gryski
2023-03-10 23:00:12 -08:00
committed by Ayke
parent 72c7adf94a
commit 0b6bb12e9e
3 changed files with 82 additions and 0 deletions
+16
View File
@@ -77,6 +77,16 @@ func stringFromBytes(x struct {
return _string{ptr: (*byte)(buf), length: x.len}
}
func stringFromBytesTyped(x []byte) string {
slice := *(*struct {
ptr *byte
len uintptr
cap uintptr
})(unsafe.Pointer(&x))
s := stringFromBytes(slice)
return *(*string)(unsafe.Pointer(&s))
}
// Convert a string to a []byte slice.
func stringToBytes(x _string) (slice struct {
ptr *byte
@@ -91,6 +101,12 @@ func stringToBytes(x _string) (slice struct {
return
}
func stringToBytesTyped(x string) []byte {
s := *(*_string)(unsafe.Pointer(&x))
slice := stringToBytes(s)
return *(*[]byte)(unsafe.Pointer(&slice))
}
// Convert a []rune slice to a string.
func stringFromRunes(runeSlice []rune) (s _string) {
// Count the number of characters that will be in the string.