Created
July 28, 2020 00:07
-
-
Save yakuter/c0df0f4253ea639529f3589e99dc940b to your computer and use it in GitHub Desktop.
String Byte Conversion Without Memory Allocation
This file contains hidden or 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
| // b2s converts byte slice to a string without memory allocation. | |
| // See https://groups.google.com/forum/#!msg/Golang-Nuts/ENgbUzYvCuU/90yGx7GUAgAJ . | |
| // | |
| // Note it may break if string and/or slice header will change | |
| // in the future go versions. | |
| func b2s(b []byte) string { | |
| /* #nosec G103 */ | |
| return *(*string)(unsafe.Pointer(&b)) | |
| } | |
| // s2b converts string to a byte slice without memory allocation. | |
| // | |
| // Note it may break if string and/or slice header will change | |
| // in the future go versions. | |
| func s2b(s string) (b []byte) { | |
| /* #nosec G103 */ | |
| bh := (*reflect.SliceHeader)(unsafe.Pointer(&b)) | |
| /* #nosec G103 */ | |
| sh := *(*reflect.StringHeader)(unsafe.Pointer(&s)) | |
| bh.Data = sh.Data | |
| bh.Len = sh.Len | |
| bh.Cap = sh.Len | |
| return b | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment