diff --git a/conversion/conversion.go b/conversion/conversion.go new file mode 100644 index 0000000..6d2587c --- /dev/null +++ b/conversion/conversion.go @@ -0,0 +1,14 @@ +package conversion + +import "unsafe" + +func Bytes(s string) []byte { + return unsafe.Slice(unsafe.StringData(s), len(s)) +} + +func String(b []byte) string { + if len(b) == 0 { + return "" + } + return unsafe.String(unsafe.SliceData(b), len(b)) +} diff --git a/conversion/conversion_test.go b/conversion/conversion_test.go new file mode 100644 index 0000000..c7a9c6f --- /dev/null +++ b/conversion/conversion_test.go @@ -0,0 +1,40 @@ +package conversion + +import ( + "bytes" + "testing" +) + +func TestBytes(t *testing.T) { + testCases := []struct { + input string + expected []byte + }{ + {"test", []byte("test")}, + {"", []byte("")}, + } + + for _, tc := range testCases { + result := Bytes(tc.input) + if !bytes.Equal(result, tc.expected) { + t.Errorf("Expected %v, but got %v", tc.expected, result) + } + } +} + +func TestString(t *testing.T) { + testCases := []struct { + input []byte + expected string + }{ + {[]byte("test"), "test"}, + {[]byte(""), ""}, + } + + for _, tc := range testCases { + result := String(tc.input) + if result != tc.expected { + t.Errorf("Expected %s, but got %s", tc.expected, result) + } + } +}