minify_html/
lib.rs

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