simple_minify_html/
lib.rs

1#![deny(unsafe_code)]
2
3use std::io::Write;
4
5pub use crate::cfg::Cfg;
6use crate::{
7    ast::c14n::c14n_serialise_ast,
8    minify::content::minify_content,
9    parse::{Code, content::parse_content},
10    spec::tag::{EMPTY_SLICE, ns::Namespace},
11};
12
13mod ast;
14mod cfg;
15mod code_gen;
16mod entity;
17mod minify;
18mod parse;
19mod pattern;
20mod spec;
21mod tag;
22#[cfg(test)]
23mod tests;
24mod whitespace;
25
26/// Minifies UTF-8 HTML code, represented as an array of bytes.
27///
28/// # Arguments
29///
30/// * `code` - A slice of bytes representing the source code to minify.
31/// * `cfg` - Configuration object to adjust minification approach.
32///
33/// # Examples
34///
35/// ```
36/// use simple_minify_html::{Cfg, minify};
37///
38/// let mut code: &[u8] = b"<p>  Hello, world!  </p>";
39/// let mut cfg = Cfg::new();
40/// cfg.keep_comments = true;
41/// let minified = minify(&code, Some(cfg));
42/// assert_eq!(minified, b"<p>Hello, world!".to_vec());
43/// ```
44#[must_use]
45pub fn minify(src: &[u8], cfg: Option<Cfg>) -> Vec<u8> {
46    let mut code = Code::new_with_opts(src);
47    let parsed = parse_content(&mut code, Namespace::Html, EMPTY_SLICE, EMPTY_SLICE);
48    let mut out = Vec::with_capacity(src.len());
49    let cfg = cfg.unwrap_or_default();
50    minify_content(
51        &cfg,
52        &mut out,
53        Namespace::Html,
54        false,
55        EMPTY_SLICE,
56        parsed.children,
57    );
58    out.shrink_to_fit();
59    out
60}
61
62pub fn canonicalize<T: Write>(out: &mut T, src: &[u8]) -> std::io::Result<()> {
63    let mut code = Code::new(src);
64    let parsed = parse_content(&mut code, Namespace::Html, EMPTY_SLICE, EMPTY_SLICE);
65    for c in parsed.children {
66        c14n_serialise_ast(out, &c)?;
67    }
68    Ok(())
69}