Skip to content

Instantly share code, notes, and snippets.

@abserari
Created November 12, 2020 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abserari/5af648f42dd45ac48e5745110c481940 to your computer and use it in GitHub Desktop.
Save abserari/5af648f42dd45ac48e5745110c481940 to your computer and use it in GitHub Desktop.
Zero-Copy, Fast Convert.
// 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