docs_compiler/
compress.rs1use std::io;
17use std::path::{Path, PathBuf};
18use std::process::{Command, Stdio};
19
20#[derive(Debug, Clone, Copy, Default)]
22pub struct Tools {
23 pub gzip: bool,
25 pub brotli: bool,
27 pub zstd: bool,
29}
30
31impl Tools {
32 #[must_use]
34 pub fn detect() -> Self {
35 Self {
36 gzip: available("gzip", &["--version"]),
37 brotli: available("brotli", &["--version"]),
38 zstd: available("zstd", &["--version"]),
39 }
40 }
41
42 #[must_use]
44 pub fn any(self) -> bool {
45 self.gzip || self.brotli || self.zstd
46 }
47}
48
49fn available(tool: &str, args: &[&str]) -> bool {
50 Command::new(tool)
51 .args(args)
52 .stdin(Stdio::null())
53 .stdout(Stdio::null())
54 .stderr(Stdio::null())
55 .status()
56 .is_ok_and(|s| s.success())
57}
58
59pub fn sidecars(tools: &Tools, path: &Path) -> io::Result<Vec<&'static str>> {
63 let mut produced = Vec::new();
64 let jobs: [(&str, &str, &[&str]); 3] = [
65 ("gzip", "gz", &["-9", "-n", "-c"]),
66 ("brotli", "br", &["-q", "11", "-c"]),
67 ("zstd", "zst", &["-19", "-q", "-c"]),
68 ];
69 for (tool, ext, args) in jobs {
70 let allowed = match tool {
71 "gzip" => tools.gzip,
72 "brotli" => tools.brotli,
73 _ => tools.zstd,
74 };
75 if !allowed || spawn_to_file(tool, args, path, &sidecar_path(path, ext))? {
76 produced.push(ext_token(ext));
77 }
78 }
79 Ok(produced)
80}
81
82#[must_use]
84pub fn sidecar_path(path: &Path, ext: &str) -> PathBuf {
85 let mut name = path.as_os_str().to_owned();
86 name.push(".");
87 name.push(ext);
88 PathBuf::from(name)
89}
90
91#[must_use]
93pub fn ext_token(ext: &str) -> &'static str {
94 match ext {
95 "gz" => "gzip",
96 "br" => "br",
97 "zst" => "zstd",
98 "dcz" => "dcz",
99 _ => "identity",
100 }
101}
102
103fn spawn_to_file(tool: &str, args: &[&str], input: &Path, dest: &Path) -> io::Result<bool> {
107 let out_file = std::fs::File::create(dest)?;
108 let status = Command::new(tool)
109 .args(args)
110 .arg(input)
111 .stdin(Stdio::null())
112 .stdout(Stdio::from(out_file))
113 .stderr(Stdio::null())
114 .status()?;
115 if !status.success() {
116 let _ = std::fs::remove_file(dest);
117 return Ok(false);
118 }
119 Ok(std::fs::metadata(dest)
120 .map(|m| m.len() > 0)
121 .unwrap_or(false))
122}
123
124pub fn train_dictionary(tools: &Tools, samples: &[PathBuf], dest: &Path) -> io::Result<bool> {
129 if !tools.zstd || samples.len() < 8 {
130 return Ok(false);
131 }
132 let mut args: Vec<&str> = vec!["--train", "--maxdict=16384"];
133 let strs: Vec<String> = samples
134 .iter()
135 .map(|p| p.to_string_lossy().into_owned())
136 .collect();
137 for s in &strs {
138 args.push(s);
139 }
140 args.push("-o");
141 let dest_str = dest.to_string_lossy().into_owned();
142 args.push(&dest_str);
143 let status = Command::new("zstd")
144 .args(&args)
145 .stdin(Stdio::null())
146 .stdout(Stdio::null())
147 .stderr(Stdio::null())
148 .status()?;
149 Ok(status.success() && dest.is_file())
150}
151
152pub fn dcz_sidecar(tools: &Tools, dict: &Path, path: &Path) -> io::Result<bool> {
155 if !tools.zstd || !dict.is_file() {
156 return Ok(false);
157 }
158 let mut dest = path.as_os_str().to_owned();
159 dest.push(".dcz");
160 let status = Command::new("zstd")
161 .arg("-19")
162 .arg("-D")
163 .arg(dict)
164 .arg("-c")
165 .arg(path)
166 .stdin(Stdio::null())
167 .stdout(Stdio::from(std::fs::File::create(&dest)?))
168 .stderr(Stdio::null())
169 .status()?;
170 if !status.success() {
171 let _ = std::fs::remove_file(dest);
172 return Ok(false);
173 }
174 Ok(true)
175}
176
177#[must_use]
182pub fn pick_encoding(accept: &str, path: &Path) -> Option<(&'static str, PathBuf)> {
183 let accepted = |token: &str| {
184 accept.split(',').any(|part| {
185 part.split(';')
186 .next()
187 .unwrap_or("")
188 .trim()
189 .eq_ignore_ascii_case(token)
190 })
191 };
192 let candidates: [(&str, &str); 4] = [
193 ("dcz", "dcz"),
194 ("br", "br"),
195 ("zstd", "zst"),
196 ("gzip", "gz"),
197 ];
198 for (token, ext) in candidates {
199 if accepted(token) && sidecar_path(path, ext).is_file() {
200 return Some((ext_token(ext), sidecar_path(path, ext)));
201 }
202 }
203 None
204}