Add array[N, byte].fromHex(string)

This commit is contained in:
Zahary Karadjov 2020-07-02 18:00:39 +03:00
parent c980d7592d
commit 61d5cfc376
No known key found for this signature in database
GPG Key ID: C8936F8A3073D609
2 changed files with 17 additions and 0 deletions

View File

@ -83,6 +83,11 @@ func hexToByteArray*[N: static[int]](hexStr: string): array[N, byte]
## Read an hex string and store it in a byte array. No "endianness" reordering is done.
hexToByteArray(hexStr, result)
func fromHex*[N](A: type array[N, byte], hexStr: string): A
{.raises: [ValueError, Defect], noInit, inline.}=
## Read an hex string and store it in a byte array. No "endianness" reordering is done.
hexToByteArray(hexStr, result)
func hexToPaddedByteArray*[N: static[int]](hexStr: string): array[N, byte]
{.raises: [ValueError, Defect].} =
## Read a hex string and store it in a byte array `output`.

View File

@ -36,6 +36,18 @@ suite "Byte utils":
expect(ValueError): discard hexToByteArray[1]("")
expect(ValueError): discard hexToByteArray[1]("1")
test "array.fromHex":
let
s = "0x12345678"
a2 = array[2, byte].fromHex(s)
a4 = array[4, byte].fromHex(s)
check:
a2.toHex == "1234"
a4.toHex == "12345678"
expect(ValueError): echo array[5, byte].fromHex(s)
test "toHex":
check simpleBArray.toHex == "12345678"
check hexToSeqByte("12345678") == simpleBArray