Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PIP-2858: Add unsafe byte to string and back conversion #187

Merged
merged 2 commits into from
Mar 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ jobs:
strategy:
matrix:
go-version:
- 1.19.x # a minimum supported version(from go.mod)
- 1.20.x
- 1.20.x # a minimum supported version(from go.mod)
- 1.21.x
- 1.22.x
os: [ ubuntu-latest ]
Expand Down
2 changes: 1 addition & 1 deletion go.mod
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
Expand Down
20 changes: 20 additions & 0 deletions unsafe/unsafe.go
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))
}
15 changes: 15 additions & 0 deletions unsafe/unsafe_test.go
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"))
}
Loading