resumark 0.1.1

ATS-safe resume typesetting from Markdown — extraction order as a verified contract
Documentation
//! Inline markdown: `**bold**`, `*italic*`, `[text](url)`, and bare URLs.
//!
//! The dialect matches the reference renderer: emphasis may nest inside link
//! text, single-star italic content may not contain `*`, and unmatched
//! markers fall through as literal text.

/// A styled run of text. Runs are the atoms the layout engine wraps and the
/// PDF backend emits; a run never spans a style or link boundary.
#[derive(Clone, Debug, PartialEq)]
pub struct Run {
    pub text: String,
    pub bold: bool,
    pub italic: bool,
    pub link: Option<String>,
}

/// Parse one line of inline markdown into runs.
pub fn parse_inline(text: &str) -> Vec<Run> {
    let mut runs = Vec::new();
    for (span, link) in split_links(text) {
        emphasis(&span, false, false, link.as_deref(), &mut runs);
    }
    merge(runs)
}

/// Plain-text version: markdown stripped, link targets dropped.
pub fn plain(text: &str) -> String {
    parse_inline(text)
        .into_iter()
        .map(|r| r.text)
        .collect::<String>()
        .trim()
        .to_string()
}

fn split_links(text: &str) -> Vec<(String, Option<String>)> {
    let chars: Vec<char> = text.chars().collect();
    let mut out: Vec<(String, Option<String>)> = Vec::new();
    let mut buf = String::new();
    let mut i = 0;
    while i < chars.len() {
        // [text](url)
        if chars[i] == '['
            && let Some(close) = find_from(&chars, i + 1, ']')
            && chars.get(close + 1) == Some(&'(')
            && let Some(end) = find_from(&chars, close + 2, ')')
        {
            let inner: String = chars[i + 1..close].iter().collect();
            let url: String = chars[close + 2..end].iter().collect();
            if !inner.is_empty() && !url.is_empty() {
                flush(&mut out, &mut buf);
                out.push((inner, Some(url)));
                i = end + 1;
                continue;
            }
        }
        // bare URL: runs until whitespace, '<', or ')'
        if starts_with_at(&chars, i, "https://") || starts_with_at(&chars, i, "http://") {
            let mut j = i;
            while j < chars.len() && !chars[j].is_whitespace() && chars[j] != '<' && chars[j] != ')'
            {
                j += 1;
            }
            let url: String = chars[i..j].iter().collect();
            flush(&mut out, &mut buf);
            out.push((url.clone(), Some(url)));
            i = j;
            continue;
        }
        buf.push(chars[i]);
        i += 1;
    }
    flush(&mut out, &mut buf);
    out
}

fn emphasis(text: &str, bold: bool, italic: bool, link: Option<&str>, out: &mut Vec<Run>) {
    let chars: Vec<char> = text.chars().collect();
    let mut buf = String::new();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '*' {
            if chars.get(i + 1) == Some(&'*') {
                if let Some(close) = find_double_star(&chars, i + 2) {
                    let inner: String = chars[i + 2..close].iter().collect();
                    if !inner.is_empty() {
                        push_run(out, &mut buf, bold, italic, link);
                        emphasis(&inner, true, italic, link, out);
                        i = close + 2;
                        continue;
                    }
                }
                // fall through: unmatched ** is literal
            } else if let Some(close) = find_from(&chars, i + 1, '*') {
                // single-star italic: content may not contain '*', and the
                // closing star may not be doubled
                let followed = chars.get(close + 1) == Some(&'*');
                let inner: String = chars[i + 1..close].iter().collect();
                if !followed && !inner.is_empty() {
                    push_run(out, &mut buf, bold, italic, link);
                    out.push(Run {
                        text: inner,
                        bold,
                        italic: true,
                        link: link.map(str::to_string),
                    });
                    i = close + 1;
                    continue;
                }
            }
        }
        buf.push(chars[i]);
        i += 1;
    }
    push_run(out, &mut buf, bold, italic, link);
}

fn push_run(out: &mut Vec<Run>, buf: &mut String, bold: bool, italic: bool, link: Option<&str>) {
    if !buf.is_empty() {
        out.push(Run {
            text: std::mem::take(buf),
            bold,
            italic,
            link: link.map(str::to_string),
        });
    }
}

fn flush(out: &mut Vec<(String, Option<String>)>, buf: &mut String) {
    if !buf.is_empty() {
        out.push((std::mem::take(buf), None));
    }
}

fn merge(runs: Vec<Run>) -> Vec<Run> {
    let mut out: Vec<Run> = Vec::new();
    for r in runs {
        if let Some(last) = out.last_mut()
            && last.bold == r.bold
            && last.italic == r.italic
            && last.link == r.link
        {
            last.text.push_str(&r.text);
            continue;
        }
        out.push(r);
    }
    out
}

fn find_from(chars: &[char], from: usize, needle: char) -> Option<usize> {
    (from..chars.len()).find(|&i| chars[i] == needle)
}

fn find_double_star(chars: &[char], from: usize) -> Option<usize> {
    (from..chars.len().saturating_sub(1)).find(|&i| chars[i] == '*' && chars[i + 1] == '*')
}

fn starts_with_at(chars: &[char], at: usize, prefix: &str) -> bool {
    let p: Vec<char> = prefix.chars().collect();
    chars.len() >= at + p.len() && chars[at..at + p.len()] == p[..]
}

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

    #[test]
    fn bold_and_italic() {
        let runs = parse_inline("a **b** *c* d");
        assert_eq!(runs.len(), 5);
        assert!(runs[1].bold && !runs[1].italic);
        assert!(runs[3].italic && !runs[3].bold);
        assert_eq!(plain("a **b** *c* d"), "a b c d");
    }

    #[test]
    fn links() {
        let runs = parse_inline("see [docs](https://x.dev) or https://y.dev now");
        assert_eq!(runs[1].link.as_deref(), Some("https://x.dev"));
        assert_eq!(runs[1].text, "docs");
        assert_eq!(runs[3].link.as_deref(), Some("https://y.dev"));
        assert_eq!(runs[3].text, "https://y.dev");
    }

    #[test]
    fn bold_inside_link() {
        let runs = parse_inline("[**bold** name](https://x.dev)");
        assert!(runs[0].bold);
        assert_eq!(runs[0].link.as_deref(), Some("https://x.dev"));
    }

    #[test]
    fn unmatched_stars_are_literal() {
        assert_eq!(plain("2 * 3 = 6"), "2 * 3 = 6");
    }
}