laminapdf-model 0.9.0

Typed views of a PDF document in Rust: pages, outline, document info, page labels, name trees and the structure tree, read tolerantly.
Documentation
//! The rules for a field's fully qualified name (ISO 32000-2 ยง12.7.4.2): partial names joined
//! by periods, so a partial name holds no period and none is empty.

/// Why a fully qualified name is not one a field may have.
///
/// Added in 0.7.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum NameFault {
    /// The name is empty.
    Empty,
    /// A partial name is empty: the name starts or ends with a period, or has two in a row.
    EmptyPartial,
    /// The name holds a control character.
    Control,
}

impl NameFault {
    /// What is wrong, in a few words.
    ///
    /// Added in 0.7.0.
    #[must_use]
    pub const fn reason(self) -> &'static str {
        match self {
            Self::Empty => "the name is empty",
            Self::EmptyPartial => "a partial name between periods is empty",
            Self::Control => "the name holds a control character",
        }
    }
}

/// The partial names of the fully qualified name `name`, outermost first.
///
/// # Errors
/// [`NameFault`] when the name is empty, has an empty partial name or holds a control
/// character.
///
/// Added in 0.7.0.
pub fn partial_names(name: &str) -> Result<Vec<&str>, NameFault> {
    if name.is_empty() {
        return Err(NameFault::Empty);
    }
    if name.chars().any(char::is_control) {
        return Err(NameFault::Control);
    }
    let parts: Vec<&str> = name.split('.').collect();
    if parts.iter().any(|p| p.is_empty()) {
        return Err(NameFault::EmptyPartial);
    }
    Ok(parts)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn partial_names_should_split_at_periods() {
        assert_eq!(partial_names("a.b.c"), Ok(vec!["a", "b", "c"]));
    }

    #[test]
    fn partial_names_should_refuse_an_empty_name_or_partial() {
        assert_eq!(
            ["", ".a", "a.", "a..b"].map(partial_names),
            [
                Err(NameFault::Empty),
                Err(NameFault::EmptyPartial),
                Err(NameFault::EmptyPartial),
                Err(NameFault::EmptyPartial)
            ]
        );
    }

    #[test]
    fn partial_names_should_refuse_control_characters() {
        assert_eq!(partial_names("a\nb"), Err(NameFault::Control));
    }
}