wdxtools 0.4.2

Everyday formatting tools for the command line
Documentation
//! Output templating for `diffh` batch mode.

/// Maximum input fields addressable from a template (`$1`..`$16`).
pub const MAX_FIELDS: usize = 16;

/// Splits `s` on spaces and tabs into `dst`, returning the field count.
pub fn split_fields<'a>(s: &'a str, dst: &mut [&'a str; MAX_FIELDS]) -> usize {
    let b = s.as_bytes();
    let mut n = 0;
    let mut i = 0;
    while i < b.len() && n < dst.len() {
        while i < b.len() && (b[i] == b' ' || b[i] == b'\t') {
            i += 1;
        }
        if i >= b.len() {
            break;
        }
        let start = i;
        while i < b.len() && b[i] != b' ' && b[i] != b'\t' {
            i += 1;
        }
        dst[n] = &s[start..i];
        n += 1;
    }
    n
}

/// Expands `$d` to the formatted diff and `$1`..`$N` to input fields.
/// Unknown `$` sequences are kept as-is.
pub fn expand(out: &mut String, tpl: &str, fields: &[&str], diff: &str) {
    let b = tpl.as_bytes();
    // Literal runs are copied as slices so multi-byte characters survive intact.
    let mut lit = 0;
    let mut i = 0;
    while i < b.len() {
        if b[i] != b'$' || i + 1 >= b.len() {
            i += 1;
            continue;
        }
        if b[i + 1] == b'd' {
            out.push_str(&tpl[lit..i]);
            out.push_str(diff);
            i += 2;
            lit = i;
            continue;
        }
        let mut j = i + 1;
        while j < b.len() && b[j].is_ascii_digit() {
            j += 1;
        }
        if j > i + 1 {
            out.push_str(&tpl[lit..i]);
            let n = b[i + 1..j]
                .iter()
                .fold(0usize, |acc, &c| acc * 10 + (c - b'0') as usize);
            if n >= 1 && n <= fields.len() {
                out.push_str(fields[n - 1]);
            }
            i = j;
            lit = i;
            continue;
        }
        // Unknown `$` sequence: leave it in the literal run.
        i += 1;
    }
    out.push_str(&tpl[lit..]);
}

/// Interprets the escape sequences the shell would otherwise swallow.
pub fn unescape(s: &str) -> String {
    s.replace("\\033", "\x1b")
        .replace("\\e", "\x1b")
        .replace("\\n", "\n")
        .replace("\\t", "\t")
}