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(""), + ) +}