Created
March 26, 2021 06:59
-
-
Save giliao/f0f3576f0955cd71d7aac5dd5a68c4cb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// no copy to change slice to string | |
// use your own risk | |
func String(b []byte) (s string) { | |
pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b)) | |
pstring := (*reflect.StringHeader)(unsafe.Pointer(&s)) | |
pstring.Data = pbytes.Data | |
pstring.Len = pbytes.Len | |
return | |
} | |
// no copy to change string to slice | |
// use your own risk | |
func Slice(s string) (b []byte) { | |
pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b)) | |
pstring := (*reflect.StringHeader)(unsafe.Pointer(&s)) | |
pbytes.Data = pstring.Data | |
pbytes.Len = pstring.Len | |
pbytes.Cap = pstring.Len | |
return | |
} | |
func stringBytes(s string) []byte { | |
return *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{ | |
Data: (*reflect.StringHeader)(unsafe.Pointer(&s)).Data, | |
Len: len(s), | |
Cap: len(s), | |
})) | |
} | |
func bytesString(b []byte) string { | |
return *(*string)(unsafe.Pointer(&b)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment