laracards 0.1.0

Editorial social cards and blog covers for Laravel Rust: SVG templates rendered natively, measured text fitting and pluggable backgrounds.
Documentation
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// An SVG template plus its placeholder and section substitution.
pub struct Template {
    path: PathBuf,
}

impl Template {
    /// Open a template.
    ///
    /// # Errors
    ///
    /// Fails when there is no file at `path`.
    pub fn new(path: impl AsRef<Path>) -> laravel::Result<Self> {
        let path = path.as_ref();

        if !path.is_file() {
            return Err(laravel::Error::msg(format!(
                "Laracards: template not found at {}.",
                path.display()
            )));
        }

        Ok(Self {
            path: path.to_path_buf(),
        })
    }

    /// Resolves sections, then placeholders.
    ///
    /// Placeholders come in two forms: `{{key}}` for text, and `__KEY__` for values that are not
    /// XML-escapable content, such as data URIs.
    ///
    /// Sections are `{{#key}}...{{/key}}` and are dropped when the key has no value. They exist because
    /// an optional layer has to disappear entirely rather than render empty: an `<image>` with
    /// `href=""` makes a renderer abort, so "no background" cannot mean "background with no source".
    ///
    /// # Errors
    ///
    /// Fails when the template cannot be read.
    pub fn render<K: AsRef<str>, V: AsRef<str>>(
        &self,
        data: impl IntoIterator<Item = (K, V)>,
    ) -> laravel::Result<String> {
        let data: Vec<(String, String)> = data
            .into_iter()
            .map(|(key, value)| (key.as_ref().to_owned(), value.as_ref().to_owned()))
            .collect();
        let svg = std::fs::read_to_string(&self.path)?;

        Ok(Self::fill(&svg, &data))
    }

    /// The same as [`render`](Self::render), for a template that is already in memory.
    pub fn fill(svg: &str, data: &[(String, String)]) -> String {
        let values: HashMap<&str, &str> = data.iter().map(|(key, value)| (key.as_str(), value.as_str())).collect();
        let mut svg = Self::sections(svg, &values);

        for (key, value) in data {
            svg = svg
                .replace(&format!("{{{{{key}}}}}"), value)
                .replace(&format!("__{}__", key.to_ascii_uppercase()), value);
        }

        Self::strip_unfilled(&svg)
    }

    fn sections(svg: &str, values: &HashMap<&str, &str>) -> String {
        let mut out = String::with_capacity(svg.len());
        let mut at = 0;

        while let Some(found) = svg[at..].find("{{#") {
            let start = at + found;
            let key_start = start + 3;
            let key_end = key_start
                + Self::run(&svg.as_bytes()[key_start..], |byte| {
                    byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_'
                });

            if key_end == key_start || !svg[key_end..].starts_with("}}") {
                out.push_str(&svg[at..key_start]);
                at = key_start;

                continue;
            }

            let key = &svg[key_start..key_end];
            let body_start = key_end + 2;
            let closing = format!("{{{{/{key}}}}}");

            let Some(length) = svg[body_start..].find(&closing) else {
                out.push_str(&svg[at..body_start]);
                at = body_start;

                continue;
            };

            out.push_str(&svg[at..start]);

            if !values.get(key).copied().unwrap_or("").trim().is_empty() {
                out.push_str(&svg[body_start..body_start + length]);
            }

            at = body_start + length + closing.len();
        }

        out.push_str(&svg[at..]);

        out
    }

    /// Any placeholder left unfilled would render as literal text.
    fn strip_unfilled(svg: &str) -> String {
        let bytes = svg.as_bytes();
        let mut out = Vec::with_capacity(bytes.len());
        let mut at = 0;

        while at < bytes.len() {
            if let Some(end) = Self::braced(bytes, at).or_else(|| Self::dunder(bytes, at)) {
                at = end;

                continue;
            }

            out.push(bytes[at]);
            at += 1;
        }

        String::from_utf8(out).unwrap_or_default()
    }

    /// The end of `{{key}}`, `{{#key}}` or `{{/key}}` starting at `at`.
    fn braced(bytes: &[u8], at: usize) -> Option<usize> {
        if !bytes[at..].starts_with(b"{{") {
            return None;
        }

        let mut cursor = at + 2;

        if matches!(bytes.get(cursor), Some(b'#' | b'/')) {
            cursor += 1;
        }

        let length = Self::run(&bytes[cursor..], |byte| {
            byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_'
        });

        (length > 0 && bytes[cursor + length..].starts_with(b"}}")).then_some(cursor + length + 2)
    }

    /// The end of `__KEY__` starting at `at`, matching as much as the pattern can, like a greedy regex.
    fn dunder(bytes: &[u8], at: usize) -> Option<usize> {
        if !bytes[at..].starts_with(b"__") {
            return None;
        }

        let run = Self::run(&bytes[at + 2..], |byte| {
            byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_'
        });
        let limit = at + 2 + run;

        (at + 5..=limit).rev().find(|&end| &bytes[end - 2..end] == b"__")
    }

    fn run(bytes: &[u8], accept: impl Fn(u8) -> bool) -> usize {
        bytes.iter().take_while(|byte| accept(**byte)).count()
    }
}