Skip to content

Commit

Permalink
Merge pull request #187 from mailgun/maxim/develop
Browse files Browse the repository at this point in the history
PIP-2858: Add unsafe byte to string and back conversion
  • Loading branch information
horkhe authored Mar 12, 2024
2 parents ba99650 + 0a6be82 commit a2fabf4
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 3 deletions.
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"))
}

0 comments on commit a2fabf4

Please sign in to comment.