mirror of
https://github.com/safing/portbase
synced 2025-09-06 20:50:07 +00:00
Add safe formatting function
This commit is contained in:
parent
adedde1310
commit
a53b8e2de6
2 changed files with 48 additions and 0 deletions
21
utils/safe.go
Normal file
21
utils/safe.go
Normal file
|
@ -0,0 +1,21 @@
|
||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/hex"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func SafeFirst16Bytes(data []byte) string {
|
||||||
|
if len(data) == 0 {
|
||||||
|
return "<empty>"
|
||||||
|
}
|
||||||
|
|
||||||
|
return strings.TrimPrefix(
|
||||||
|
strings.SplitN(hex.Dump(data), "\n", 2)[0],
|
||||||
|
"00000000 ",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func SafeFirst16Chars(s string) string {
|
||||||
|
return SafeFirst16Bytes([]byte(s))
|
||||||
|
}
|
27
utils/safe_test.go
Normal file
27
utils/safe_test.go
Normal file
|
@ -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,
|
||||||
|
"<empty>",
|
||||||
|
SafeFirst16Bytes(nil),
|
||||||
|
)
|
||||||
|
assert.Equal(t,
|
||||||
|
"<empty>",
|
||||||
|
SafeFirst16Chars(""),
|
||||||
|
)
|
||||||
|
}
|
Loading…
Add table
Reference in a new issue