From 577730da0bb262f46cc877a65f377880dbeb3531 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Do=C4=9Fan=20Can=20Bak=C4=B1r?= Date: Tue, 9 Jan 2024 16:25:02 +0300 Subject: [PATCH] add conversion pkg --- conversion/conversion.go | 14 ++++++++++++ conversion/conversion_test.go | 40 +++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 conversion/conversion.go create mode 100644 conversion/conversion_test.go 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) + } + } +}