-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add bytesconv pkg for converting strings and slices efficiently
- Loading branch information
1 parent
a799d57
commit 7b4ad88
Showing
1 changed file
with
19 additions
and
0 deletions.
There are no files selected for viewing
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
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)) | ||
} |