From 94aa8b85660843a3c683cddbe206cf4df740e868 Mon Sep 17 00:00:00 2001 From: Etan Kissling Date: Sun, 25 Jul 2021 21:27:23 +0200 Subject: [PATCH] Ignore leading zeroes in hexToPaddedByteArray When converting hex strings into fixed size byte arrays, the function `hexToPaddedByteArray` is commonly used to deal with the input data being shorter than the target buffer. However, the opposite case of the input data having extra leading zeroes leads to an error. This patch allows leading zeroes in `hexToPaddedByteArray`, ignoring them when the input string is longer than the destination array. --- stew/byteutils.nim | 3 ++- tests/test_byteutils.nim | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/stew/byteutils.nim b/stew/byteutils.nim index 977362ae..3405fa7e 100644 --- a/stew/byteutils.nim +++ b/stew/byteutils.nim @@ -78,8 +78,9 @@ func hexToPaddedByteArray*[N: static[int]](hexStr: string): array[N, byte] ## Read a hex string and store it in a byte array `output`. ## The string may be shorter than the byte array. ## No "endianness" reordering is done. + var p = skip0xPrefix(hexStr) + while p < hexStr.len and hexStr[p] == '0': inc p # Skip leading zeroes. let - p = skip0xPrefix(hexStr) sz = hexStr.len - p maxStrSize = result.len * 2 var diff --git a/tests/test_byteutils.nim b/tests/test_byteutils.nim index ccad0764..87e1f35d 100644 --- a/tests/test_byteutils.nim +++ b/tests/test_byteutils.nim @@ -78,6 +78,18 @@ suite "Byte utils": block: let a = hexToPaddedByteArray[32]("0x68656c6c6f20776f726c64") check a.toHex == "00000000000000000000000000000000000000000068656c6c6f20776f726c64" + block: + let a = hexToPaddedByteArray[2]("0x01234") + check a.toHex == "1234" + block: + let a = hexToPaddedByteArray[2]("01234") + check a.toHex == "1234" + block: + let a = hexToPaddedByteArray[1]("") + check a.toHex == "00" + block: + let a = hexToPaddedByteArray[0]("") + check a.toHex == "" block: expect ValueError: discard hexToPaddedByteArray[2]("0x12345")