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