redup-config 0.3.3

Типизированная конфигурация: чтение из YAML и окружения, строгость, проверка и выгрузка с комментариями.
Documentation
//! Массив байт в hex-записи: `DEADBEEF`.

use std::fmt;

use crate::node::{Node, Shape, Unbuilt, read_scalar, replaced, sampled};
use crate::path::Path;
use crate::problems::Problems;
use crate::raw::Raw;

/// Число цифр в записи одного байта.
const DIGITS_PER_BYTE: usize = 2;

/// Массив байт в hex-записи: `DEADBEEF`.
///
/// Пишется шестнадцатеричными цифрами в верхнем регистре, по две на байт. Читается в любом
/// регистре, с префиксом `0x` или без него; пустой текст — пустой массив.
///
/// ```
/// use redup_config::{Config, HexBytes, Source, load};
///
/// /// Настройки хранилища.
/// #[derive(Debug, Clone, Default, PartialEq, Config)]
/// struct BlobConfig {
///     /// Заголовок блоба.
///     header: HexBytes,
/// }
///
/// # fn main() -> Result<(), redup_config::Problems> {
/// let source = Source::directory("configs").environment([("Blob_Header", "0x504b03")]);
/// let loaded = load::<BlobConfig>(&source)?;
/// assert_eq!(loaded.value.header.as_bytes(), [0x50, 0x4B, 0x03]);
/// assert_eq!(loaded.value.header.to_string(), "504B03");
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct HexBytes(Vec<u8>);

impl HexBytes {
    /// Байты массива.
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }
}

impl From<Vec<u8>> for HexBytes {
    fn from(bytes: Vec<u8>) -> Self {
        Self(bytes)
    }
}

impl From<HexBytes> for Vec<u8> {
    fn from(value: HexBytes) -> Self {
        value.0
    }
}

/// Записывает байты шестнадцатеричными цифрами в верхнем регистре.
impl fmt::Display for HexBytes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for byte in &self.0 {
            write!(f, "{byte:02X}")?;
        }
        Ok(())
    }
}

/// Читает hex-запись массива: префикс `0x`, затем чётное число шестнадцатеричных цифр.
fn parse(text: &str) -> Result<HexBytes, &'static str> {
    let stripped = text.strip_prefix("0x").or_else(|| text.strip_prefix("0X"));
    let digits = stripped.unwrap_or(text);
    if digits.is_empty() && stripped.is_some() {
        return Err("hexadecimal digits are expected after the `0x` prefix");
    }
    if !digits.len().is_multiple_of(DIGITS_PER_BYTE) {
        return Err("an even number of hexadecimal digits is expected");
    }
    let mut chars = digits.chars();
    let mut bytes = Vec::with_capacity(digits.len() / DIGITS_PER_BYTE);
    while let Some(high) = chars.next() {
        let low = chars.next();
        let (Some(high), Some(low)) = (high.to_digit(16), low.and_then(|low| low.to_digit(16)))
        else {
            return Err("only hexadecimal digits are expected, optionally after the `0x` prefix");
        };
        let byte = high * 16 + low;
        bytes.push(u8::try_from(byte).map_err(|_| "a byte is out of range")?);
    }
    Ok(HexBytes(bytes))
}

/// Массив байт читается и пишется hex-записью.
impl Node for HexBytes {
    fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt> {
        read_scalar(raw, path, problems, "a byte array in hex", parse)
    }
    replaced!();
    sampled!(Some(HexBytes(vec![0xDE, 0xAD, 0xBE, 0xEF])));
    fn shape(&self) -> Shape<'_> {
        Shape::Scalar(self.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::HexBytes;
    use crate::node::Node;
    use crate::path::Path;
    use crate::problems::Problems;
    use crate::raw::Raw;

    /// Читает значение из текста скаляра; ошибку возвращает её текстом.
    fn read(text: &str) -> Result<HexBytes, String> {
        let raw = Raw::scalar(text, crate::mark::Mark::Model);
        let mut problems = Problems::new();
        match <HexBytes as Node>::read(&raw, &Path::new(), &mut problems) {
            Ok(value) => Ok(value),
            Err(_) => Err(problems.to_string()),
        }
    }

    #[test]
    fn reads_hex_digits_in_any_case() {
        let cases = [
            ("DEADBEEF", vec![0xDE, 0xAD, 0xBE, 0xEF]),
            ("deadbeef", vec![0xDE, 0xAD, 0xBE, 0xEF]),
            ("DeAdBeEf", vec![0xDE, 0xAD, 0xBE, 0xEF]),
            ("0x504b03", vec![0x50, 0x4B, 0x03]),
            ("0XFF", vec![0xFF]),
            ("", Vec::new()),
        ];
        for (text, bytes) in cases {
            assert_eq!(read(text), Ok(HexBytes(bytes)), "read {text:?}");
        }
    }

    #[test]
    fn rejects_odd_length_and_foreign_characters() {
        assert_eq!(
            read("ABC").unwrap_err(),
            "\"ABC\" is not a byte array in hex: an even number of hexadecimal digits is expected"
        );
        assert_eq!(
            read("0xDEADBEEG").unwrap_err(),
            "\"0xDEADBEEG\" is not a byte array in hex: only hexadecimal digits are expected, optionally after the `0x` prefix"
        );
        assert!(
            read("0x")
                .unwrap_err()
                .contains("digits are expected after the `0x` prefix")
        );
        for text in ["XX", "DE AD", "12-34", "де"] {
            let error = read(text).unwrap_err();
            assert!(
                error.contains("is not a byte array in hex"),
                "{text:?}: {error}"
            );
        }
    }

    #[test]
    fn writes_upper_case_and_round_trips() {
        let cases = [
            (vec![0xDE, 0xAD, 0xBE, 0xEF], "DEADBEEF"),
            (vec![0x50, 0x4B, 0x03], "504B03"),
            (vec![0x00, 0x01, 0x0F], "00010F"),
            (Vec::new(), ""),
        ];
        for (bytes, text) in cases {
            let value = HexBytes::from(bytes.clone());
            assert_eq!(value.to_string(), text);
            assert_eq!(
                match value.shape() {
                    crate::node::Shape::Scalar(text) => Some(text),
                    _ => None,
                },
                Some(text.to_owned())
            );
            if !text.is_empty() {
                assert_eq!(read(text).as_ref(), Ok(&value), "read back {text:?}");
            }
            assert_eq!(Vec::from(value), bytes);
        }
        assert_eq!(HexBytes::default(), HexBytes::from(Vec::new()));
        assert_eq!(
            <HexBytes as Node>::sample().map(|value| value.to_string()),
            Some("DEADBEEF".to_owned())
        );
    }
}