f-office-fonts 0.3.0

Font database, metrics and outlines.
Documentation
//! The text form of a target's font environment: sections that each start with a line `[[kind]]`,
//! followed by `key = value` lines. A line that starts with `#` is a comment. A value is a whole
//! number or a text in double quotes, a strict subset of TOML's basic strings: a backslash
//! stands before each backslash and each double quote of the text, and the text holds no
//! control character. The reader refuses what it does not decode, which is every other
//! backslash, a bare double quote and a control character, so that it reads the values that a
//! TOML reader reads; the writer refuses a text with a control character.

use std::collections::BTreeSet;

/// One section of a file: its kind and its `key = value` pairs, as written.
pub(crate) type Section<'a> = (&'a str, Vec<(String, String)>);

/// The sections of `text`, whose kinds are among `kinds`, in their order; or the first line that
/// is neither empty, a comment, the start of such a section nor a `key = value` line in one.
pub(crate) fn sections<'a>(text: &'a str, kinds: &[&str]) -> Result<Vec<Section<'a>>, String> {
    let mut sections: Vec<Section<'a>> = Vec::new();
    for line in text.lines().map(str::trim) {
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let kind = line.strip_prefix("[[").and_then(|s| s.strip_suffix("]]"));
        if let Some(kind) = kind.filter(|kind| kinds.contains(kind)) {
            sections.push((kind, Vec::new()));
            continue;
        }
        let pair = line
            .split_once('=')
            .map(|(key, value)| (key.trim().to_owned(), value.trim().to_owned()));
        match (pair, sections.last_mut()) {
            (Some(pair), Some((_, section))) => section.push(pair),
            _ => return Err(line.to_owned()),
        }
    }
    Ok(sections)
}

/// The first key that a section holds twice, if any.
pub(crate) fn repeated_key(section: &[(String, String)]) -> Option<&str> {
    let mut seen = BTreeSet::new();
    section
        .iter()
        .map(|(key, _)| key.as_str())
        .find(|key| !seen.insert(*key))
}

/// A text in the form: in double quotes, with a backslash before each backslash and each double
/// quote, the form's only escapes, as a TOML basic string writes them. `None` when the text
/// holds a control character, which the form cannot hold.
pub(crate) fn quoted(text: &str) -> Option<String> {
    if text.chars().any(char::is_control) {
        return None;
    }
    let mut out = String::with_capacity(text.len() + 2);
    out.push('"');
    for c in text.chars() {
        if matches!(c, '\\' | '"') {
            out.push('\\');
        }
        out.push(c);
    }
    out.push('"');
    Some(out)
}

/// The text of a value in the form, as [`quoted`] writes it. `None` when the value is not in
/// double quotes, or holds a control character, a bare double quote or a backslash that is not
/// one of the two escapes: the form refuses what it does not decode.
fn unquoted(value: &str) -> Option<String> {
    let inner = value.strip_prefix('"')?.strip_suffix('"')?;
    let mut text = String::with_capacity(inner.len());
    let mut chars = inner.chars();
    while let Some(c) = chars.next() {
        match c {
            '\\' => match chars.next()? {
                escaped @ ('\\' | '"') => text.push(escaped),
                _ => return None,
            },
            '"' => return None,
            c if c.is_control() => return None,
            c => text.push(c),
        }
    }
    Some(text)
}

/// The value of `key` in one section, as written.
pub(crate) fn value_of<'a>(section: &'a [(String, String)], key: &str) -> Option<&'a str> {
    section
        .iter()
        .find(|(k, _)| k == key)
        .map(|(_, v)| v.as_str())
}

/// The text of `key` in one section, as [`unquoted`] reads it: `Ok(None)` when the section lacks
/// the key, and the error of `wrong` when its value is not a text in the form.
pub(crate) fn text_of<E>(
    section: &[(String, String)],
    key: &str,
    wrong: impl FnOnce() -> E,
) -> Result<Option<String>, E> {
    value_of(section, key)
        .map(|value| unquoted(value).ok_or_else(wrong))
        .transpose()
}

#[cfg(test)]
mod tests;