From 61d5cfc37677f2b434d43c06d06695b00e56613b Mon Sep 17 00:00:00 2001 From: Zahary Karadjov Date: Thu, 2 Jul 2020 18:00:39 +0300 Subject: [PATCH] Add array[N, byte].fromHex(string) --- stew/byteutils.nim | 5 +++++ tests/test_byteutils.nim | 12 ++++++++++++ 2 files changed, 17 insertions(+) diff --git a/stew/byteutils.nim b/stew/byteutils.nim index 9f035e3..81911a7 100644 --- a/stew/byteutils.nim +++ b/stew/byteutils.nim @@ -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`. diff --git a/tests/test_byteutils.nim b/tests/test_byteutils.nim index c27b729..cf171d1 100644 --- a/tests/test_byteutils.nim +++ b/tests/test_byteutils.nim @@ -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