synta 0.1.4

ASN.1 parser, decoder, and encoder library with DER/BER support and C FFI
Documentation
//! Hexadecimal encoding and decoding utilities.

#[cfg(not(feature = "std"))]
use alloc::{string::String, vec::Vec};

/// Encode bytes as a lowercase hexadecimal string.
pub fn bytes_to_hex(bytes: &[u8]) -> String {
    use core::fmt::Write;
    let mut s = String::with_capacity(bytes.len() * 2);
    for &b in bytes {
        let _ = write!(s, "{:02x}", b);
    }
    s
}

/// Decode a hexadecimal string into bytes.
///
/// Returns `Err` if the string has odd length or contains a non-hex character.
pub fn hex_to_bytes(s: &str) -> Result<Vec<u8>, &'static str> {
    if !s.len().is_multiple_of(2) {
        return Err("hex string must have even length");
    }
    let mut bytes = Vec::with_capacity(s.len() / 2);
    for i in (0..s.len()).step_by(2) {
        let byte = u8::from_str_radix(&s[i..i + 2], 16).map_err(|_| "invalid hex character")?;
        bytes.push(byte);
    }
    Ok(bytes)
}