f-office-fonts 0.3.0

Font database, metrics and outlines.
Documentation
//! Font family names and the one way to compare them.

use std::borrow::Cow;
use std::cmp::Ordering;
use std::hash::{Hash, Hasher};

/// A font family name as a document, a font file or a target's font listing writes it.
///
/// Two names name the same family when they differ at most in the case of ASCII letters. Word
/// finds an installed font, a stand-in, a family that the target lacks, a symbol font and a font
/// table entry whose name differs from the run's font name so, and it does not fold any other
/// letter, such as the full-width Latin capitals of `MS ゴシック`. `Eq`, `Hash` and
/// [`FamilyName::cmp_name`] follow that comparison, and F-Office compares family names
/// exclusively through `FamilyName`. The name
/// keeps its own case for warnings and output.
#[derive(Clone, Debug)]
pub struct FamilyName(Cow<'static, str>);

impl FamilyName {
    /// The family name `name`, as written.
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self(Cow::Owned(name.into()))
    }

    /// The family name `name` of a table of the code, as written.
    #[must_use]
    pub const fn from_static(name: &'static str) -> Self {
        Self(Cow::Borrowed(name))
    }

    /// The name as written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Whether `name` names this family.
    #[must_use]
    pub fn is(&self, name: &str) -> bool {
        self.0.eq_ignore_ascii_case(name)
    }

    /// How this family sorts against the family that `name` names: by the bytes of the names
    /// with ASCII letters in lower case, so that a list sorted by it can be searched for a name
    /// as written.
    #[must_use]
    pub fn cmp_name(&self, name: &str) -> Ordering {
        folded(&self.0).cmp(folded(name))
    }
}

/// The bytes of a name with ASCII letters in lower case, which `Hash` and
/// [`FamilyName::cmp_name`] read.
fn folded(name: &str) -> impl Iterator<Item = u8> + '_ {
    name.bytes().map(|byte| byte.to_ascii_lowercase())
}

impl PartialEq for FamilyName {
    fn eq(&self, other: &Self) -> bool {
        self.is(&other.0)
    }
}

impl Eq for FamilyName {}

impl Hash for FamilyName {
    fn hash<H: Hasher>(&self, state: &mut H) {
        for byte in folded(&self.0) {
            state.write_u8(byte);
        }
        // A byte that UTF-8 never holds ends the name, as `str` ends its own hash.
        state.write_u8(0xff);
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;

    use super::FamilyName;

    #[test]
    fn names_one_family_in_any_case_of_ascii_letters() {
        let courier = FamilyName::from_static("Courier New");
        for other in ["courier new", "COURIER NEW", "cOURIER nEW"] {
            assert_eq!(courier, FamilyName::new(other), "{other}");
            assert!(courier.is(other), "{other}");
        }
    }

    #[test]
    fn names_no_family_whose_name_differs_in_more_than_case() {
        let courier = FamilyName::from_static("Courier New");
        assert_ne!(courier, FamilyName::new("Courier"));
        assert_ne!(courier, FamilyName::new("Courier New "));
        assert!(FamilyName::new("Times New Roman").is("times new roman"));
        assert!(!FamilyName::new("Arial").is("Arial Narrow"));
        assert!(!FamilyName::new("Arial").is("Arail"));
    }

    #[test]
    fn folds_no_letter_outside_ascii() {
        // Word draws `ms ゴシック` with another font than `MS ゴシック` (MS Gothic).
        let gothic = FamilyName::from_static("MS ゴシック");
        assert!(!gothic.is("ms ゴシック"));
        assert_ne!(gothic, FamilyName::new("ms ゴシック"));
        assert!(!FamilyName::new("ÉCOLE").is("école"));
        assert!(FamilyName::new("ÉCOLE").is("École"));
    }

    #[test]
    fn hashes_and_orders_as_it_compares() {
        let names: HashSet<FamilyName> = ["Arial", "arial", "ARIAL", "Arial Narrow"]
            .into_iter()
            .map(FamilyName::new)
            .collect();
        assert_eq!(names.len(), 2);
        let mut sorted: Vec<FamilyName> = ["b", "A", "a", "C"]
            .into_iter()
            .map(FamilyName::new)
            .collect();
        sorted.sort_by(|a, b| a.cmp_name(b.as_str()));
        sorted.dedup();
        let written: Vec<&str> = sorted.iter().map(FamilyName::as_str).collect();
        assert_eq!(written, ["A", "b", "C"]);
        assert!(sorted.binary_search_by(|probe| probe.cmp_name("B")).is_ok());
        assert!(
            sorted
                .binary_search_by(|probe| probe.cmp_name("d"))
                .is_err()
        );
    }

    #[test]
    fn keeps_the_name_as_written() {
        let name = FamilyName::new("arial");
        assert_eq!(name.as_str(), "arial");
        assert_eq!(name, FamilyName::from_static("Arial"));
    }
}