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