dusk_bytes/parse.rs
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4//
5// Copyright (c) DUSK NETWORK. All rights reserved.
6
7use super::errors::{BadLength, InvalidChar};
8use super::serialize::Serializable;
9
10/// An optional trait used to parse a string slice for types that implements
11/// the [`Serializable`] trait.
12/// The default implementation makes use of [`Serializable`] trait to provide
13/// the necessary parsing functionality without additional code from the
14/// consumer.
15pub trait ParseHexStr<const N: usize>: Serializable<N> {
16 /// Parse a string slice as bytes hex representation and returns `
17 fn from_hex_str(s: &str) -> Result<Self, Self::Error>
18 where
19 Self: Sized,
20 Self::Error: BadLength + InvalidChar,
21 {
22 let expected = N * 2;
23 if s.len() < expected {
24 return Err(Self::Error::bad_length(s.len(), expected));
25 }
26
27 let mut bytes = [0u8; N];
28 let s = s.as_bytes();
29
30 for i in (0..expected).step_by(2) {
31 let n: u8 = match (val(s[i]), val(s[i + 1])) {
32 (Some(h), Some(l)) => (h << 4) + l,
33 (None, _) => {
34 return Err(Self::Error::invalid_char(s[i].into(), i));
35 }
36 (_, None) => {
37 return Err(Self::Error::invalid_char(
38 s[i + 1].into(),
39 i + 1,
40 ));
41 }
42 };
43 bytes[i / 2] = n;
44 }
45
46 Self::from_bytes(&bytes)
47 }
48}
49
50/// A constant funtion to parse a bytes string representing hexadecimals
51/// (e.g. `b"fe12c6"` ) into bytes (e.g `[0xfe, 0x12, 0xc6]`).
52/// If a smaller destination buffer is provided, the value will be truncated
53/// (e.g `[0xfe, 0x12]`); if a bigger destination buffer is provided, it will
54/// be padded with zeroes (e.g. `[0xfe, 0x12, 0xc6, 0x0, 0x0])
55///
56/// The input length must be even. At runtime, an odd length or an invalid
57/// character in the portion consumed to fill the destination causes a panic.
58/// When the function is evaluated in a constant context, the same panic is
59/// reported during compilation.
60///
61/// ```compile_fail
62/// use dusk_bytes::hex;
63///
64/// // Fails during const evaluation because the input length is odd.
65/// const ODD: [u8; 1] = hex::<3, 1>(b"abc");
66/// ```
67pub const fn hex<const N: usize, const M: usize>(bytes: &[u8; N]) -> [u8; M] {
68 if !N.is_multiple_of(2) {
69 panic!("hex(): input length must be even");
70 }
71
72 let mut buffer = [0u8; M];
73
74 let mut i = 0;
75 let mut j = 0;
76 while i < N && j < M {
77 let n = match (val(bytes[i]), val(bytes[i + 1])) {
78 (Some(h), Some(l)) => (h << 4) + l,
79 (_, _) => panic!("hex(): failed to parse the input as hex number"),
80 };
81
82 buffer[j] = n;
83 i += 2;
84 j += 1;
85 }
86 buffer
87}
88
89const fn val(c: u8) -> Option<u8> {
90 match c {
91 b'A'..=b'F' => Some(c - b'A' + 10),
92 b'a'..=b'f' => Some(c - b'a' + 10),
93 b'0'..=b'9' => Some(c - b'0'),
94 _ => None,
95 }
96}
97
98// Auto trait [`ParseHexStr`] for any type that implements [`Serializable`]
99impl<T, const N: usize> ParseHexStr<N> for T where T: Serializable<N> {}