termosaic 0.3.0

Semantic, structured output for human, machine-text, and opaque-byte destinations
Documentation
use std::fmt;

/// Sanitized text safe to pass through the human renderer.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HumanText(String);

impl HumanText {
    pub fn sanitize(value: impl AsRef<str>) -> Self {
        let mut sanitized = String::with_capacity(value.as_ref().len());
        for character in value.as_ref().chars() {
            if is_unsafe_human_character(character) {
                sanitized.push('\u{fffd}');
            } else {
                sanitized.push(character);
            }
        }
        Self(sanitized)
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for HumanText {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Validated UTF-8 machine-readable text.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MachineText(String);

impl MachineText {
    pub fn parse(value: impl Into<String>) -> Result<Self, TextSafetyError> {
        let value = value.into();
        for (byte_offset, character) in value.char_indices() {
            if is_disallowed_machine_character(character) {
                return Err(TextSafetyError::ControlCharacter {
                    byte_offset,
                    code_point: character as u32,
                });
            }
        }
        Ok(Self(value))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum TextSafetyError {
    #[error("machine text contains U+{code_point:04X} at byte {byte_offset}")]
    ControlCharacter { byte_offset: usize, code_point: u32 },
}

fn is_unsafe_human_character(character: char) -> bool {
    matches!(character as u32,
        0x0000..=0x001f
        | 0x007f..=0x009f
        | 0x202a..=0x202e
        | 0x2066..=0x2069)
}

fn is_disallowed_machine_character(character: char) -> bool {
    let code = character as u32;
    matches!(code, 0x0000..=0x0008 | 0x000b | 0x000c | 0x000e..=0x001f | 0x007f..=0x009f)
}