miden-crypto/src/utils/mod.rs
src/utils/mod.rsRaw
1use super::{utils::string::String, Word};
2use core::fmt::{self, Display, Write};
3
4#[cfg(not(feature = "std"))]
5pub use alloc::{format, vec};
6
7#[cfg(feature = "std")]
8pub use std::{format, vec};
9
10mod diff;
11mod kv_map;
12
13// RE-EXPORTS
14// ================================================================================================
15pub use winter_utils::{
16 string, uninit_vector, Box, ByteReader, ByteWriter, Deserializable, DeserializationError,
17 Serializable, SliceReader,
18};
19
20pub mod collections {
21 pub use super::diff::*;
22 pub use super::kv_map::*;
23 pub use winter_utils::collections::*;
24}
25
26// UTILITY FUNCTIONS
27// ================================================================================================
28
29/// Converts a [Word] into hex.
30pub fn word_to_hex(w: &Word) -> Result<String, fmt::Error> {
31 let mut s = String::new();
32
33 for byte in w.iter().flat_map(|e| e.to_bytes()) {
34 write!(s, "{byte:02x}")?;
35 }
36
37 Ok(s)
38}
39
40/// Renders an array of bytes as hex into a String.
41pub fn bytes_to_hex_string<const N: usize>(data: [u8; N]) -> String {
42 let mut s = String::with_capacity(N + 2);
43
44 s.push_str("0x");
45 for byte in data.iter() {
46 write!(s, "{byte:02x}").expect("formatting hex failed");
47 }
48
49 s
50}
51
52#[derive(Debug)]
53pub enum HexParseError {
54 InvalidLength { expected: usize, got: usize },
55 MissingPrefix,
56 InvalidChar,
57 OutOfRange,
58}
59
60impl Display for HexParseError {
61 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
62 match self {
63 HexParseError::InvalidLength { expected, got } => {
64 write!(f, "Hex encoded RpoDigest must have length 66, including the 0x prefix. expected {expected} got {got}")
65 }
66 HexParseError::MissingPrefix => {
67 write!(f, "Hex encoded RpoDigest must start with 0x prefix")
68 }
69 HexParseError::InvalidChar => {
70 write!(f, "Hex encoded RpoDigest must contain characters [a-zA-Z0-9]")
71 }
72 HexParseError::OutOfRange => {
73 write!(f, "Hex encoded values of an RpoDigest must be inside the field modulus")
74 }
75 }
76 }
77}
78
79#[cfg(feature = "std")]
80impl std::error::Error for HexParseError {}
81
82/// Parses a hex string into an array of bytes of known size.
83pub fn hex_to_bytes<const N: usize>(value: &str) -> Result<[u8; N], HexParseError> {
84 let expected: usize = (N * 2) + 2;
85 if value.len() != expected {
86 return Err(HexParseError::InvalidLength {
87 expected,
88 got: value.len(),
89 });
90 }
91
92 if !value.starts_with("0x") {
93 return Err(HexParseError::MissingPrefix);
94 }
95
96 let mut data = value.bytes().skip(2).map(|v| match v {
97 b'0'..=b'9' => Ok(v - b'0'),
98 b'a'..=b'f' => Ok(v - b'a' + 10),
99 b'A'..=b'F' => Ok(v - b'A' + 10),
100 _ => Err(HexParseError::InvalidChar),
101 });
102
103 let mut decoded = [0u8; N];
104 #[allow(clippy::needless_range_loop)]
105 for pos in 0..N {
106 // These `unwrap` calls are okay because the length was checked above
107 let high: u8 = data.next().unwrap()?;
108 let low: u8 = data.next().unwrap()?;
109 decoded[pos] = (high << 4) + low;
110 }
111
112 Ok(decoded)
113}