-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
23 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 |
---|---|---|
@@ -1,3 +1,5 @@ | ||
//go:build !go1.20 | ||
|
||
package unsafeext | ||
|
||
import ( | ||
|
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,21 @@ | ||
//go:build go1.20 | ||
|
||
package unsafeext | ||
|
||
import ( | ||
"unsafe" | ||
) | ||
|
||
// BytesToString converts an array of bytes into a string without allocating. | ||
// The byte slice passed to this function is not to be used after this call as it's unsafe; you have been warned. | ||
func BytesToString(b []byte) string { | ||
return unsafe.String(unsafe.SliceData(b), len(b)) | ||
} | ||
|
||
// StringToBytes converts an existing string into an []byte without allocating. | ||
// The string passed to these functions is not to be used again after this call as it's unsafe; you have been warned. | ||
func StringToBytes(s string) (b []byte) { | ||
d := unsafe.StringData(s) | ||
b = unsafe.Slice(d, len(s)) | ||
return | ||
} |