miden-crypto/src/utils/mod.rs
src/utils/mod.rsRaw
1//! Utilities used in this crate which can also be generally useful downstream.
2
3use super::{utils::string::String, Word};
4use core::fmt::{self, Display, Write};
5
6#[cfg(not(feature = "std"))]
7pub use alloc::{format, vec};
8
9#[cfg(feature = "std")]
10pub use std::{format, vec};
11
12mod kv_map;
13
14// RE-EXPORTS
15// ================================================================================================
16pub use winter_utils::{
17 string, uninit_vector, Box, ByteReader, ByteWriter, Deserializable, DeserializationError,
18 Serializable, SliceReader,
19};
20
21pub mod collections {
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/// Defines errors which can occur during parsing of hexadecimal strings.
53#[derive(Debug)]
54pub enum HexParseError {
55 InvalidLength { expected: usize, actual: usize },
56 MissingPrefix,
57 InvalidChar,
58 OutOfRange,
59}
60
61impl Display for HexParseError {
62 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
63 match self {
64 HexParseError::InvalidLength { expected, actual } => {
65 write!(f, "Hex encoded RpoDigest must have length 66, including the 0x prefix. expected {expected} got {actual}")
66 }
67 HexParseError::MissingPrefix => {
68 write!(f, "Hex encoded RpoDigest must start with 0x prefix")
69 }
70 HexParseError::InvalidChar => {
71 write!(f, "Hex encoded RpoDigest must contain characters [a-zA-Z0-9]")
72 }
73 HexParseError::OutOfRange => {
74 write!(f, "Hex encoded values of an RpoDigest must be inside the field modulus")
75 }
76 }
77 }
78}
79
80#[cfg(feature = "std")]
81impl std::error::Error for HexParseError {}
82
83/// Parses a hex string into an array of bytes of known size.
84pub fn hex_to_bytes<const N: usize>(value: &str) -> Result<[u8; N], HexParseError> {
85 let expected: usize = (N * 2) + 2;
86 if value.len() != expected {
87 return Err(HexParseError::InvalidLength { expected, actual: value.len() });
88 }
89
90 if !value.starts_with("0x") {
91 return Err(HexParseError::MissingPrefix);
92 }
93
94 let mut data = value.bytes().skip(2).map(|v| match v {
95 b'0'..=b'9' => Ok(v - b'0'),
96 b'a'..=b'f' => Ok(v - b'a' + 10),
97 b'A'..=b'F' => Ok(v - b'A' + 10),
98 _ => Err(HexParseError::InvalidChar),
99 });
100
101 let mut decoded = [0u8; N];
102 #[allow(clippy::needless_range_loop)]
103 for pos in 0..N {
104 // These `unwrap` calls are okay because the length was checked above
105 let high: u8 = data.next().unwrap()?;
106 let low: u8 = data.next().unwrap()?;
107 decoded[pos] = (high << 4) + low;
108 }
109
110 Ok(decoded)
111}