Skip to content

Commit

Permalink
Add unsafe byte to string and back conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
horkhe committed Mar 11, 2024
1 parent ba99650 commit 807facf
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
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))

Check failure on line 11 in unsafe/unsafe.go

View workflow job for this annotation

GitHub Actions / test (1.19.x, ubuntu-latest)

undefined: unsafe.String

Check failure on line 11 in unsafe/unsafe.go

View workflow job for this annotation

GitHub Actions / test (1.19.x, ubuntu-latest)

undefined: unsafe.SliceData
}

// 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))

Check failure on line 19 in unsafe/unsafe.go

View workflow job for this annotation

GitHub Actions / test (1.19.x, ubuntu-latest)

undefined: unsafe.StringData
}
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"))
}

0 comments on commit 807facf

Please sign in to comment.