1use crate::host::with_host;
23use flate2::read::{DeflateDecoder, GzDecoder, ZlibDecoder};
24use flate2::write::{DeflateEncoder, GzEncoder, ZlibEncoder};
25use flate2::Compression;
26use fusevm::Value;
27use std::io::{Read, Write};
28
29use super::buffer;
30
31pub const MODULE_METHODS: &[&str] = &[
33 "gzipSync",
35 "gunzipSync",
36 "deflateSync",
37 "inflateSync",
38 "deflateRawSync",
39 "inflateRawSync",
40 "unzipSync",
41 "brotliCompressSync",
42 "brotliDecompressSync",
43 "zstdCompressSync",
44 "zstdDecompressSync",
45 "gzip",
47 "gunzip",
48 "deflate",
49 "inflate",
50 "deflateRaw",
51 "inflateRaw",
52 "unzip",
53 "brotliCompress",
54 "brotliDecompress",
55 "zstdCompress",
56 "zstdDecompress",
57 "crc32",
59 "createDeflate",
61 "createInflate",
62 "createGzip",
63 "createGunzip",
64 "createDeflateRaw",
65 "createInflateRaw",
66 "createUnzip",
67 "createBrotliCompress",
68 "createBrotliDecompress",
69 "createZstdCompress",
70 "createZstdDecompress",
71];
72
73pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
74 if method.starts_with("create") {
76 return Some(Err(crate::host::type_error(&format!(
77 "zlib.{method} is not supported in node-js (no streaming backend)"
78 ))));
79 }
80
81 if method == "crc32" {
83 let data = input_bytes(args);
84 let init = {
85 let n = super::arg_num(args, 1);
86 if n.is_nan() {
87 0
88 } else {
89 n as i64 as u32
90 }
91 };
92 return Some(Ok(Value::Float(crc32(&data, init) as f64)));
93 }
94
95 if is_async(method) {
97 return Some(run_async(method, args));
98 }
99
100 let base = method.strip_suffix("Sync")?;
104 let out = oneshot(base, &input_bytes(args));
105 Some(out.map(|bytes| buffer::pooled(&bytes)))
107}
108
109fn is_async(method: &str) -> bool {
111 matches!(
112 method,
113 "gzip"
114 | "gunzip"
115 | "deflate"
116 | "inflate"
117 | "deflateRaw"
118 | "inflateRaw"
119 | "unzip"
120 | "brotliCompress"
121 | "brotliDecompress"
122 | "zstdCompress"
123 | "zstdDecompress"
124 )
125}
126
127fn run_async(op: &str, args: &[Value]) -> Result<Value, String> {
129 let Some(cb) = args.last().cloned() else {
130 return Ok(Value::Undef);
131 };
132 let input = input_bytes(args);
133 let (err, buf) = match oneshot(op, &input) {
134 Ok(bytes) => (with_host(|h| h.null()), buffer::pooled(&bytes)),
135 Err(e) => (
143 with_host(|h| {
144 h.exc
145 .take()
146 .unwrap_or_else(|| crate::builtins::synth_error(h, &e))
147 }),
148 Value::Undef,
149 ),
150 };
151 with_host(|h| h.queue_io_callback(cb, vec![err, buf]));
152 Ok(Value::Undef)
153}
154
155fn oneshot(op: &str, input: &[u8]) -> Result<Vec<u8>, String> {
157 match op {
158 "gzip" => gzip(input),
159 "gunzip" => gunzip(input),
160 "deflate" => deflate(input),
161 "inflate" => inflate(input),
162 "deflateRaw" => deflate_raw(input),
163 "inflateRaw" => inflate_raw(input),
164 "unzip" => unzip(input),
165 "brotliCompress" => brotli_compress(input),
166 "brotliDecompress" => brotli_decompress(input),
167 "zstdCompress" => zstd_compress(input),
168 "zstdDecompress" => zstd_decompress(input),
169 _ => Err(format!("Error: unknown zlib op '{op}'")),
170 }
171}
172
173fn input_bytes(args: &[Value]) -> Vec<u8> {
176 let v = args.first().cloned().unwrap_or(Value::Undef);
177 match super::buffer::view_bytes(&v) {
181 Some(b) => b,
182 None => with_host(|h| h.str_of(&v)).into_bytes(),
183 }
184}
185
186fn io_err(e: std::io::Error) -> String {
188 format!("Error: {e}")
189}
190
191fn decode_err(truncated: bool) -> String {
200 let (code, errno, msg) = if truncated {
201 ("Z_BUF_ERROR", -5, "unexpected end of file")
202 } else {
203 ("Z_DATA_ERROR", -3, "incorrect header check")
204 };
205 let e = crate::builtins::make_error_pub("Error", msg);
206 for (k, v) in [
207 ("errno", Value::Float(errno as f64)),
208 ("code", with_host(|h| h.new_str(code.to_string()))),
209 ] {
210 let _ = crate::builtins::set_property_pub(&e, k, v);
211 }
212 with_host(|h| h.exc = Some(e));
213 format!("Error: {msg}")
214}
215
216fn header_ok(kind: &str, input: &[u8]) -> bool {
219 match kind {
220 "gzip" => input.len() >= 2 && input[0] == 0x1f && input[1] == 0x8b,
221 "zlib" => {
223 input.len() >= 2
224 && input[0] & 0x0f == 8
225 && (u16::from(input[0]) * 256 + u16::from(input[1])) % 31 == 0
226 }
227 _ => true,
229 }
230}
231
232fn gzip(input: &[u8]) -> Result<Vec<u8>, String> {
233 let mut enc = GzEncoder::new(Vec::new(), Compression::default());
234 enc.write_all(input).map_err(io_err)?;
235 enc.finish().map_err(io_err)
236}
237
238fn gunzip(input: &[u8]) -> Result<Vec<u8>, String> {
239 let mut out = Vec::new();
240 GzDecoder::new(input)
241 .read_to_end(&mut out)
242 .map_err(|_| decode_err(header_ok("gzip", input)))?;
243 Ok(out)
244}
245
246fn deflate(input: &[u8]) -> Result<Vec<u8>, String> {
247 let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
248 enc.write_all(input).map_err(io_err)?;
249 enc.finish().map_err(io_err)
250}
251
252fn inflate(input: &[u8]) -> Result<Vec<u8>, String> {
253 let mut out = Vec::new();
254 ZlibDecoder::new(input)
255 .read_to_end(&mut out)
256 .map_err(|_| decode_err(header_ok("zlib", input)))?;
257 Ok(out)
258}
259
260fn deflate_raw(input: &[u8]) -> Result<Vec<u8>, String> {
261 let mut enc = DeflateEncoder::new(Vec::new(), Compression::default());
262 enc.write_all(input).map_err(io_err)?;
263 enc.finish().map_err(io_err)
264}
265
266fn inflate_raw(input: &[u8]) -> Result<Vec<u8>, String> {
267 let mut out = Vec::new();
268 DeflateDecoder::new(input)
269 .read_to_end(&mut out)
270 .map_err(io_err)?;
271 Ok(out)
272}
273
274fn unzip(input: &[u8]) -> Result<Vec<u8>, String> {
276 if input.starts_with(&[0x1f, 0x8b]) {
277 gunzip(input)
278 } else {
279 inflate(input)
280 }
281}
282
283fn brotli_compress(input: &[u8]) -> Result<Vec<u8>, String> {
284 let mut out = Vec::new();
285 {
286 let mut enc = brotli::CompressorWriter::new(&mut out, 4096, 11, 22);
288 enc.write_all(input).map_err(io_err)?;
289 }
291 Ok(out)
292}
293
294fn brotli_decompress(input: &[u8]) -> Result<Vec<u8>, String> {
295 let mut out = Vec::new();
296 brotli::Decompressor::new(input, 4096)
297 .read_to_end(&mut out)
298 .map_err(io_err)?;
299 Ok(out)
300}
301
302fn zstd_compress(input: &[u8]) -> Result<Vec<u8>, String> {
303 zstd::encode_all(input, 3).map_err(io_err)
305}
306
307fn zstd_decompress(input: &[u8]) -> Result<Vec<u8>, String> {
308 zstd::decode_all(input).map_err(io_err)
309}
310
311fn crc32(data: &[u8], init: u32) -> u32 {
313 let mut h = crc32fast::Hasher::new_with_initial(init);
314 h.update(data);
315 h.finalize()
316}