minify_html/
lib.rs

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