pub fn minify_css(code: &str) -> String {
let mut result = String::with_capacity(code.len());
let mut chars = code.chars().peekable();
let mut in_string = false;
let mut string_delim = '\0';
let mut in_comment = false;
while let Some(c) = chars.next() {
if in_comment {
if c == '*' && chars.peek() == Some(&'/') {
chars.next();
in_comment = false;
}
continue;
}
if !in_string && c == '/' && chars.peek() == Some(&'*') {
chars.next();
in_comment = true;
continue;
}
if in_string {
result.push(c);
if c == '\\' {
if let Some(next) = chars.next() {
result.push(next);
}
continue;
}
if c == string_delim {
in_string = false;
}
continue;
}
if c == '"' || c == '\'' {
in_string = true;
string_delim = c;
result.push(c);
continue;
}
match c {
'{' | '}' | ':' | ';' | ',' => {
while result.ends_with(' ') {
result.pop();
}
if c == '}' && result.ends_with(';') {
result.pop();
}
result.push(c);
}
c if c.is_whitespace() => {
if !result.ends_with(['{', '}', ':', ';', ',', ' ']) {
result.push(' ');
}
}
_ => result.push(c),
}
}
result.trim().to_string()
}
pub fn format_css(code: &str) -> String {
let mut result = String::new();
let mut chars = code.chars().peekable();
let mut indent_level = 0;
let indent = " ";
let mut in_string = false;
let mut string_delim = '\0';
let mut in_selector = true;
while let Some(c) = chars.next() {
if in_string {
result.push(c);
if c == '\\' {
if let Some(next) = chars.next() {
result.push(next);
}
continue;
}
if c == string_delim {
in_string = false;
}
continue;
}
if c == '"' || c == '\'' {
in_string = true;
string_delim = c;
result.push(c);
continue;
}
match c {
'{' => {
in_selector = false;
if !result.ends_with(' ') {
result.push(' ');
}
result.push_str("{\n");
indent_level += 1;
result.push_str(&indent.repeat(indent_level));
}
'}' => {
indent_level = indent_level.saturating_sub(1);
result.push('\n');
result.push_str(&indent.repeat(indent_level));
result.push('}');
result.push('\n');
result.push_str(&indent.repeat(indent_level));
in_selector = true;
}
';' => {
result.push_str(";\n");
result.push_str(&indent.repeat(indent_level));
}
',' => {
result.push_str(", ");
}
':' => {
if in_selector {
result.push(':');
} else {
result.push_str(": ");
}
}
c if c.is_whitespace() => {
if in_selector {
if !result.ends_with(' ') {
result.push(' ');
}
}
}
_ => result.push(c),
}
}
result.trim().to_string()
}