From 807facfa827a6346480359855543bf8b9924f1ce Mon Sep 17 00:00:00 2001 From: Maxim Vladimirskiy Date: Mon, 11 Mar 2024 14:38:06 +0300 Subject: [PATCH] Add unsafe byte to string and back conversion --- go.mod | 2 +- unsafe/unsafe.go | 20 ++++++++++++++++++++ unsafe/unsafe_test.go | 15 +++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 unsafe/unsafe.go create mode 100644 unsafe/unsafe_test.go diff --git a/go.mod b/go.mod index 7f538e1..4f3f6e9 100644 --- a/go.mod +++ b/go.mod @@ -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 diff --git a/unsafe/unsafe.go b/unsafe/unsafe.go new file mode 100644 index 0000000..82eb14b --- /dev/null +++ b/unsafe/unsafe.go @@ -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)) +} diff --git a/unsafe/unsafe_test.go b/unsafe/unsafe_test.go new file mode 100644 index 0000000..7497e1e --- /dev/null +++ b/unsafe/unsafe_test.go @@ -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")) +}