-
Notifications
You must be signed in to change notification settings - Fork 35
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #187 from mailgun/maxim/develop
PIP-2858: Add unsafe byte to string and back conversion
- Loading branch information
Showing
4 changed files
with
37 additions
and
3 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
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,6 +1,6 @@ | ||
module github.com/mailgun/holster/v4 | ||
|
||
go 1.19 | ||
go 1.20 | ||
|
||
require ( | ||
github.com/Shopify/toxiproxy v2.1.4+incompatible | ||
|
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,20 @@ | ||
package unsafe | ||
|
||
import ( | ||
"unsafe" | ||
) | ||
|
||
// BytesToString converts a byte slice to a string without allocation. The | ||
// returned string reuses the slice byte array. Since Go strings are immutable, | ||
// the bytes passed to BytesToString must not be modified afterwards. | ||
func BytesToString(b []byte) string { | ||
return unsafe.String(unsafe.SliceData(b), len(b)) | ||
} | ||
|
||
// StringToBytes converts a string to a byte slice without allocation. The | ||
// returned byte slice reuses the underlying string byte array. Since Go | ||
// strings are immutable, the bytes returned by StringToBytes must not be | ||
// modified. | ||
func StringToBytes(s string) []byte { | ||
return unsafe.Slice(unsafe.StringData(s), len(s)) | ||
} |
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,15 @@ | ||
package unsafe | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestBytesToString(t *testing.T) { | ||
assert.Equal(t, "hello", BytesToString([]byte("hello"))) | ||
} | ||
|
||
func TestStringToBytes(t *testing.T) { | ||
assert.Equal(t, []byte("hello"), StringToBytes("hello")) | ||
} |