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