Add util package with a DeHex function

This commit is contained in:
2025-05-20 17:07:43 +02:00
parent 7b8df3b046
commit 1ca7d572f9
2 changed files with 38 additions and 0 deletions

13
util/util.go Normal file
View File

@ -0,0 +1,13 @@
// package util provides small utility functions that make it easier to express common things
package util
import "encoding/hex"
// DeHex decodes a hexadecimal string into a byte slice. Panics if the string is invalid.
func DeHex(s string) []byte {
decoded, err := hex.DecodeString(s)
if err != nil {
panic("invalid hex string")
}
return decoded
}

25
util/util_test.go Normal file
View File

@ -0,0 +1,25 @@
package util_test
import (
"testing"
"git.omicron.one/playground/cryptography/util"
"github.com/stretchr/testify/assert"
)
func TestDeHex(t *testing.T) {
b := util.DeHex("")
assert.NotNil(t, b)
assert.Len(t, b, 0)
b = util.DeHex("deadbeef")
assert.NotNil(t, b)
assert.Equal(t, []byte("\xde\xad\xbe\xef"), b)
assert.PanicsWithValue(t, "invalid hex string", func() {
util.DeHex("dead serious this is not a hex string")
})
assert.PanicsWithValue(t, "invalid hex string", func() {
util.DeHex("deada55")
})
}