Skip to content

CSS Minify & Beautify — Rust source

Minify CSS (strip comments and whitespace, shorten hexes and decimals) or beautify it back to readable one-declaration-per-line form. Strings stay intact. Runs locally with a shareable link.

This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! css-minify — CSS minifier & beautifier. Rust port (canonical TS:
//! `src/lib/css-minify.ts`; Go twin: `cli/css-minify`). No external crates:
//! the TS rules are regexes, so each runs here as a single-pass scanner with
//! the same leftmost, non-overlapping replace-all semantics. One scanner
//! masks string literals as "\x00n\x00" sentinels and drops /* */ comments;
//! minify — collapse whitespace, strip spaces around {} ; : , > (sibling +
//! and ~ combinators keep theirs), drop the last semicolon before },
//! lowercase hexes, shorten #aabbcc → #abc (never 8-digit alpha), strip
//! leading zeros (0.5 → .5) and trailing fraction zeros (1.50 → 1.5,
//! 1.00 → 1, .00 → 0). beautify — one selector per block, one declaration
//! per line at 2-space depth, each keeping its own semicolon. Errors travel
//! in `FormatResult.error` (`None` = success); empty input is a successful
//! empty output, never an error.

pub struct FormatResult {
    pub output: String,
    pub error: Option<String>,
}

fn is_ws(c: char) -> bool { matches!(c, ' ' | '\t' | '\n' | '\u{b}' | '\u{c}' | '\r') }
fn is_punct(c: char) -> bool { matches!(c, '{' | '}' | ';' | ':' | ',' | '>') }
fn is_digit(c: char) -> bool { c.is_ascii_digit() }
fn is_lower_hex(c: char) -> bool { is_digit(c) || ('a'..='f').contains(&c) }
fn is_hex_any(c: char) -> bool { is_lower_hex(c) || ('A'..='F').contains(&c) }
/// The TS numeric-context class [^A-Za-z0-9_.#$%-]: true when `c` may
/// directly precede a number being rewritten.
fn ctx_ok(c: char) -> bool {
    !(c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '#' | '$' | '%' | '-'))
}

/// Scan CSS into (masked, strings): every string literal becomes a
/// \x00n\x00 sentinel, every /* */ comment is dropped. A backslash escapes
/// the next character, so \' or \" never closes the literal.
fn mask(raw: &str) -> Result<(String, Vec<String>), String> {
    let ch: Vec<char> = raw.chars().collect();
    let n = ch.len();
    let mut out = String::new();
    let mut strings: Vec<String> = Vec::new();
    let mut i = 0;
    while i < n {
        let c = ch[i];
        if c == '"' || c == '\'' {
            let start = i;
            i += 1;
            while i < n && ch[i] != c {
                if ch[i] == '\\' && i + 1 < n { i += 1; } // escaped char
                i += 1;
            }
            if i >= n { return Err("Unterminated string".into()); }
            i += 1;
            strings.push(ch[start..i].iter().collect());
            out.push('\u{0}');
            out.push_str(&(strings.len() - 1).to_string());
            out.push('\u{0}');
        } else if c == '/' && i + 1 < n && ch[i + 1] == '*' {
            let mut j = i + 2;
            while j + 1 < n && !(ch[j] == '*' && ch[j + 1] == '/') { j += 1; }
            if j + 1 >= n { return Err("Unterminated comment".into()); }
            i = j + 2;
        } else {
            out.push(c);
            i += 1;
        }
    }
    Ok((out, strings))
}

/// Substitute the sentinels back with the original string literals.
fn unmask(text: &str, strings: &[String]) -> String {
    let ch: Vec<char> = text.chars().collect();
    let n = ch.len();
    let mut out = String::new();
    let mut i = 0;
    while i < n {
        if ch[i] == '\u{0}' {
            let mut j = i + 1;
            while j < n && is_digit(ch[j]) { j += 1; }
            if j < n && ch[j] == '\u{0}' && j > i + 1 {
                let idx: usize = ch[i + 1..j].iter().collect::<String>().parse().unwrap_or(usize::MAX);
                if idx < strings.len() {
                    out.push_str(&strings[idx]);
                    i = j + 1;
                    continue;
                }
            }
        }
        out.push(ch[i]);
        i += 1;
    }
    out
}

/// /\s+/g → " "
fn collapse_ws(s: &str) -> String {
    let ch: Vec<char> = s.chars().collect();
    let mut out = String::new();
    let mut i = 0;
    while i < ch.len() {
        if is_ws(ch[i]) {
            while i < ch.len() && is_ws(ch[i]) { i += 1; }
            out.push(' ');
        } else {
            out.push(ch[i]);
            i += 1;
        }
    }
    out
}

/// /\s*([{};:,>])\s*/g → "$1" (deliberately not + or ~: sibling combinators
/// keep their spaces).
fn strip_struct(s: &str) -> String {
    let ch: Vec<char> = s.chars().collect();
    let n = ch.len();
    let mut out = String::new();
    let mut i = 0;
    while i < n {
        let mut j = i;
        while j < n && is_ws(ch[j]) { j += 1; }
        if j < n && is_punct(ch[j]) {
            out.push(ch[j]);
            let mut k = j + 1;
            while k < n && is_ws(ch[k]) { k += 1; }
            i = k;
        } else {
            out.push(ch[i]);
            i += 1;
        }
    }
    out
}

/// /;+}/g → "}"
fn drop_trailing_semis(s: &str) -> String {
    let ch: Vec<char> = s.chars().collect();
    let n = ch.len();
    let mut out = String::new();
    let mut i = 0;
    while i < n {
        if ch[i] == ';' {
            let mut j = i;
            while j < n && ch[j] == ';' { j += 1; }
            if j < n && ch[j] == '}' {
                out.push('}');
                i = j + 1;
                continue;
            }
        }
        out.push(ch[i]);
        i += 1;
    }
    out
}

/// /#[0-9a-fA-F]{3,8}/g → lowercase
fn lower_hex(s: &str) -> String {
    let ch: Vec<char> = s.chars().collect();
    let n = ch.len();
    let mut out = String::new();
    let mut i = 0;
    while i < n {
        if ch[i] == '#' {
            let mut j = i + 1;
            while j < n && j - i - 1 < 8 && is_hex_any(ch[j]) { j += 1; }
            if j - i - 1 >= 3 {
                for c in &ch[i + 1..j] { out.extend(c.to_lowercase()); }
                i = j;
                continue;
            }
        }
        out.push(ch[i]);
        i += 1;
    }
    out
}

/// The TS backreference rule #([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3([^0-9a-f]|$)
/// → "#$1$2$3$4": shorten #aabbcc to #abc only when both digits of each pair
/// match and no 7th hex digit follows (8-digit #rrggbbaa alpha is never touched).
fn shorten_hex_pair(s: &str) -> String {
    let ch: Vec<char> = s.chars().collect();
    let n = ch.len();
    let mut out = String::new();
    let mut i = 0;
    while i < n {
        if ch[i] == '#' && i + 6 < n && (0..6).all(|k| is_lower_hex(ch[i + 1 + k]))
            && (i + 7 >= n || !is_lower_hex(ch[i + 7]))
        {
            if ch[i + 1] == ch[i + 2] && ch[i + 3] == ch[i + 4] && ch[i + 5] == ch[i + 6] {
                out.push('#');
                out.push(ch[i + 1]);
                out.push(ch[i + 3]);
                out.push(ch[i + 5]);
            } else {
                out.extend(&ch[i..i + 7]);
            }
            if i + 7 < n {
                out.push(ch[i + 7]); // the one non-hex context char, re-emitted
                i += 8;
            } else {
                i += 7;
            }
            continue;
        }
        out.push(ch[i]);
        i += 1;
    }
    out
}

/// /(^|[^A-Za-z0-9_.#$%-])0+(\.[0-9]+)/g → "$1$2" (0.5 → .5)
fn strip_leading_zero(s: &str) -> String {
    let ch: Vec<char> = s.chars().collect();
    let n = ch.len();
    let mut out = String::new();
    let mut i = 0;
    while i < n {
        let z = if i == 0 { Some(0) } else if ctx_ok(ch[i]) { Some(i + 1) } else { None };
        if let Some(z) = z {
            let mut j = z;
            while j < n && ch[j] == '0' { j += 1; }
            if j > z && j + 1 < n && ch[j] == '.' && is_digit(ch[j + 1]) {
                if i > 0 { out.push(ch[i]); }
                let mut k = j + 2;
                while k < n && is_digit(ch[k]) { k += 1; }
                out.extend(&ch[j..k]);
                i = k;
                continue;
            }
        }
        out.push(ch[i]);
        i += 1;
    }
    out
}

/// /(\.[0-9]*[1-9])0+([^0-9]|$)/g → "$1$2" (1.50 → 1.5)
fn strip_fraction_zeros(s: &str) -> String {
    let ch: Vec<char> = s.chars().collect();
    let n = ch.len();
    let mut out = String::new();
    let mut i = 0;
    while i < n {
        if ch[i] == '.' {
            let mut d = i + 1;
            while d < n && is_digit(ch[d]) { d += 1; }
            // the group must end on a non-zero digit, with ≥ 1 zero after it
            if d > i + 1 {
                if let Some(last_nz) = (i + 1..d).rev().find(|&k| ch[k] != '0') {
                    if d - 1 > last_nz {
                        out.extend(&ch[i..=last_nz]);
                        if d < n { out.push(ch[d]); i = d + 1; } else { i = d; }
                        continue;
                    }
                }
            }
        }
        out.push(ch[i]);
        i += 1;
    }
    out
}

/// /(^|[^A-Za-z0-9_.#$%-])([0-9]+)\.0+([^0-9]|$)/g → "$1$2$3" (1.00 → 1)
fn strip_integral_zeros(s: &str) -> String {
    let ch: Vec<char> = s.chars().collect();
    let n = ch.len();
    let mut out = String::new();
    let mut i = 0;
    while i < n {
        let z = if i == 0 { Some(0) } else if ctx_ok(ch[i]) { Some(i + 1) } else { None };
        if let Some(z) = z {
            let mut d = z;
            while d < n && is_digit(ch[d]) { d += 1; }
            if d > z && d < n && ch[d] == '.' {
                let mut zz = d + 1;
                while zz < n && ch[zz] == '0' { zz += 1; }
                if zz > d + 1 && (zz >= n || !is_digit(ch[zz])) {
                    if i > 0 { out.push(ch[i]); }
                    out.extend(&ch[z..d]);
                    if zz < n { out.push(ch[zz]); i = zz + 1; } else { i = zz; }
                    continue;
                }
            }
        }
        out.push(ch[i]);
        i += 1;
    }
    out
}

/// /(^|[^A-Za-z0-9_.#$%-])\.0+([^0-9]|$)/g → "${1}0$2" (.00 → 0)
fn dot_zeros(s: &str) -> String {
    let ch: Vec<char> = s.chars().collect();
    let n = ch.len();
    let mut out = String::new();
    let mut i = 0;
    while i < n {
        let z = if i == 0 { Some(0) } else if ctx_ok(ch[i]) { Some(i + 1) } else { None };
        if let Some(z) = z {
            if z < n && ch[z] == '.' {
                let mut zz = z + 1;
                while zz < n && ch[zz] == '0' { zz += 1; }
                if zz > z + 1 && (zz >= n || !is_digit(ch[zz])) {
                    if i > 0 { out.push(ch[i]); }
                    out.push('0');
                    if zz < n { out.push(ch[zz]); i = zz + 1; } else { i = zz; }
                    continue;
                }
            }
        }
        out.push(ch[i]);
        i += 1;
    }
    out
}

/// One declaration-flush of the beautifier: whitespace is already collapsed,
/// so only trimming remains; empty declarations (;;, dangling ;) are skipped.
fn flush(out: &mut String, buf: &mut String, depth: usize, semi: bool) {
    let decl = buf.trim();
    if !decl.is_empty() {
        out.push_str(&"  ".repeat(depth));
        out.push_str(decl);
        if semi { out.push(';'); }
        out.push('\n');
    }
    buf.clear();
}

/// Conservative minification — see the header for the exact rule list.
pub fn minify_css(raw: &str) -> FormatResult {
    let text = raw.trim();
    if text.is_empty() {
        return FormatResult { output: String::new(), error: None };
    }
    let (masked, strings) = match mask(text) {
        Ok(v) => v,
        Err(e) => return FormatResult { output: String::new(), error: Some(e) },
    };
    let css = collapse_ws(&masked);
    let css = strip_struct(&css);
    let css = drop_trailing_semis(&css);
    let css = css.trim();
    let css = lower_hex(css);
    let css = shorten_hex_pair(&css);
    let css = strip_leading_zero(&css);
    let css = strip_fraction_zeros(&css);
    let css = strip_integral_zeros(&css);
    let css = dot_zeros(&css);
    FormatResult { output: unmask(&css, &strings), error: None }
}

/// Structural beautifier — 2-space indentation, declarations one per line.
pub fn beautify_css(raw: &str) -> FormatResult {
    let text = raw.trim();
    if text.is_empty() {
        return FormatResult { output: String::new(), error: None };
    }
    let (masked, strings) = match mask(text) {
        Ok(v) => v,
        Err(e) => return FormatResult { output: String::new(), error: Some(e) },
    };
    let css: Vec<char> = collapse_ws(&masked).chars().collect();
    let mut out = String::new();
    let mut buf = String::new();
    let mut depth: i64 = 0;
    for i in 0..css.len() {
        match css[i] {
            '{' => {
                let sel = buf.trim().to_string();
                buf.clear();
                if sel.is_empty() {
                    return FormatResult { output: String::new(), error: Some("Block without a selector".into()) };
                }
                out.push_str(&"  ".repeat(depth as usize));
                out.push_str(&sel);
                out.push_str(" {\n");
                depth += 1;
            }
            '}' => {
                flush(&mut out, &mut buf, depth.max(0) as usize, false);
                depth -= 1;
                if depth < 0 {
                    return FormatResult { output: String::new(), error: Some("Unbalanced }".into()) };
                }
                out.push_str(&"  ".repeat(depth as usize));
                out.push_str("}\n");
            }
            ';' => flush(&mut out, &mut buf, depth.max(0) as usize, true),
            c => buf.push(c),
        }
    }
    if depth != 0 {
        return FormatResult { output: String::new(), error: Some("Unclosed block".into()) };
    }
    flush(&mut out, &mut buf, depth as usize, false);
    FormatResult { output: unmask(&out, &strings), error: None }
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →