mirror of
https://github.com/status-im/nim-stew.git
synced 2025-01-24 02:50:18 +00:00
Add array[N, byte].fromHex(string)
This commit is contained in:
parent
c980d7592d
commit
61d5cfc376
@ -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.
|
## Read an hex string and store it in a byte array. No "endianness" reordering is done.
|
||||||
hexToByteArray(hexStr, result)
|
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]
|
func hexToPaddedByteArray*[N: static[int]](hexStr: string): array[N, byte]
|
||||||
{.raises: [ValueError, Defect].} =
|
{.raises: [ValueError, Defect].} =
|
||||||
## Read a hex string and store it in a byte array `output`.
|
## Read a hex string and store it in a byte array `output`.
|
||||||
|
@ -36,6 +36,18 @@ suite "Byte utils":
|
|||||||
expect(ValueError): discard hexToByteArray[1]("")
|
expect(ValueError): discard hexToByteArray[1]("")
|
||||||
expect(ValueError): discard hexToByteArray[1]("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":
|
test "toHex":
|
||||||
check simpleBArray.toHex == "12345678"
|
check simpleBArray.toHex == "12345678"
|
||||||
check hexToSeqByte("12345678") == simpleBArray
|
check hexToSeqByte("12345678") == simpleBArray
|
||||||
|
Loading…
x
Reference in New Issue
Block a user