Created
November 12, 2020 13:50
-
-
Save abserari/5af648f42dd45ac48e5745110c481940 to your computer and use it in GitHub Desktop.
Zero-Copy, Fast Convert.
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
// Copyright 2020 Gin Core Team. All rights reserved. | |
// Use of this source code is governed by a MIT style | |
// license that can be found in the LICENSE file. | |
package bytesconv | |
import ( | |
"reflect" | |
"unsafe" | |
) | |
// StringToBytes converts string to byte slice without a memory allocation. | |
func StringToBytes(s string) (b []byte) { | |
sh := *(*reflect.StringHeader)(unsafe.Pointer(&s)) | |
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b)) | |
bh.Data, bh.Len, bh.Cap = sh.Data, sh.Len, sh.Len | |
return b | |
} | |
// BytesToString converts byte slice to string without a memory allocation. | |
func BytesToString(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