Skip to content

Commit

Permalink
Add bytesconv pkg for converting strings and slices efficiently
Browse files Browse the repository at this point in the history
  • Loading branch information
KasonBraley committed Jun 9, 2023
1 parent a799d57 commit 7b4ad88
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions bytesconv/bytesconv.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//go:build go1.20

package bytesconv

import (
"unsafe"
)

// StringToBytes converts string to byte slice without a memory allocation.
// For more details, see https://github.com/golang/go/issues/53003#issuecomment-1140276077.
func StringToBytes(s string) []byte {
return unsafe.Slice(unsafe.StringData(s), len(s))
}

// BytesToString converts byte slice to string without a memory allocation.
// For more details, see https://github.com/golang/go/issues/53003#issuecomment-1140276077.
func BytesToString(b []byte) string {
return unsafe.String(unsafe.SliceData(b), len(b))
}

0 comments on commit 7b4ad88

Please sign in to comment.