From a53b8e2de62c50b0cf1afbb3a36d24acc9550ca0 Mon Sep 17 00:00:00 2001 From: Daniel Date: Fri, 17 Sep 2021 22:00:17 +0200 Subject: [PATCH] Add safe formatting function --- utils/safe.go | 21 +++++++++++++++++++++ utils/safe_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 utils/safe.go create mode 100644 utils/safe_test.go diff --git a/utils/safe.go b/utils/safe.go new file mode 100644 index 0000000..e3a55b8 --- /dev/null +++ b/utils/safe.go @@ -0,0 +1,21 @@ +package utils + +import ( + "encoding/hex" + "strings" +) + +func SafeFirst16Bytes(data []byte) string { + if len(data) == 0 { + return "" + } + + return strings.TrimPrefix( + strings.SplitN(hex.Dump(data), "\n", 2)[0], + "00000000 ", + ) +} + +func SafeFirst16Chars(s string) string { + return SafeFirst16Bytes([]byte(s)) +} diff --git a/utils/safe_test.go b/utils/safe_test.go new file mode 100644 index 0000000..d60d4c9 --- /dev/null +++ b/utils/safe_test.go @@ -0,0 +1,27 @@ +package utils + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestSafeFirst16(t *testing.T) { + assert.Equal(t, + "47 6f 20 69 73 20 61 6e 20 6f 70 65 6e 20 73 6f |Go is an open so|", + SafeFirst16Bytes([]byte("Go is an open source programming language.")), + ) + assert.Equal(t, + "47 6f 20 69 73 20 61 6e 20 6f 70 65 6e 20 73 6f |Go is an open so|", + SafeFirst16Chars("Go is an open source programming language."), + ) + + assert.Equal(t, + "", + SafeFirst16Bytes(nil), + ) + assert.Equal(t, + "", + SafeFirst16Chars(""), + ) +}