Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ignore leading zeroes in hexToPaddedByteArray #86

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion stew/byteutils.nim
Original file line number Diff line number Diff line change
Expand Up @@ -161,8 +161,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
Expand Down
12 changes: 12 additions & 0 deletions tests/test_byteutils.nim
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,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")
Expand Down