Skip to main content

quickjs_jit_stdlib/llrt/llrt_zlib/
lib.rs

1// Vendored from LLRT d9fd873e793c (modules/llrt_zlib/src/lib.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py, with local patches.
3// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0
5use crate::utils::module::{export_default, ModuleInfo};
6use rquickjs::{
7    function::Func,
8    module::{Declarations, Exports, ModuleDef},
9    Ctx, Result,
10};
11
12mod brotli;
13mod zlib;
14#[cfg(feature = "zlib-zstd")]
15mod zstd;
16
17use std::io::Read;
18
19use crate::utils::object::ObjectExt;
20use rquickjs::{prelude::Opt, Exception, Value};
21
22/// Reads the `maxOutputLength` option, which `node:zlib` uses to cap the output
23/// of the convenience methods.
24pub(crate) fn max_output_length<'js>(options: &Opt<Value<'js>>) -> Result<Option<usize>> {
25    match options.0.as_ref() {
26        Some(options) => options.get_optional::<_, usize>("maxOutputLength"),
27        None => Ok(None),
28    }
29}
30
31/// Drains `reader` into a buffer, rejecting output longer than `limit` bytes
32/// with the same `RangeError` Node.js raises for `maxOutputLength`.
33///
34/// Reading stops one byte past the limit, so an over-long result is detected
35/// without decompressing (or allocating) the rest of the payload.
36pub(crate) fn read_to_end_limited<R: Read>(
37    ctx: &Ctx<'_>,
38    reader: R,
39    limit: Option<usize>,
40    capacity: usize,
41) -> Result<Vec<u8>> {
42    let Some(limit) = limit else {
43        let mut dst = Vec::with_capacity(capacity);
44        let mut reader = reader;
45        reader.read_to_end(&mut dst)?;
46        return Ok(dst);
47    };
48
49    let cutoff = limit.saturating_add(1);
50    let mut dst = Vec::with_capacity(capacity.min(cutoff));
51    reader.take(cutoff as u64).read_to_end(&mut dst)?;
52
53    if dst.len() > limit {
54        return Err(Exception::throw_range(
55            ctx,
56            &[
57                "Cannot create a Buffer larger than ",
58                &limit.to_string(),
59                " bytes",
60            ]
61            .concat(),
62        ));
63    }
64
65    Ok(dst)
66}
67
68use self::brotli::{br_comp, br_comp_sync, br_decomp, br_decomp_sync};
69use self::zlib::{
70    deflate, deflate_raw, deflate_raw_sync, deflate_sync, gunzip, gunzip_sync, gzip, gzip_sync,
71    inflate, inflate_raw, inflate_raw_sync, inflate_sync,
72};
73#[cfg(feature = "zlib-zstd")]
74use self::zstd::{zstd_comp, zstd_comp_sync, zstd_decomp, zstd_decomp_sync};
75
76#[macro_export]
77macro_rules! define_sync_function {
78    ($fn_name:ident, $converter:expr, $command:expr) => {
79        pub(crate) fn $fn_name<'js>(
80            ctx: Ctx<'js>,
81            value: ObjectBytes<'js>,
82            options: Opt<Value<'js>>,
83        ) -> Result<Value<'js>> {
84            $converter(ctx.clone(), value, options, $command)
85        }
86    };
87}
88
89#[macro_export]
90macro_rules! define_cb_function {
91    ($fn_name:ident, $converter:expr, $command:expr) => {
92        pub(crate) fn $fn_name<'js>(
93            ctx: Ctx<'js>,
94            value: ObjectBytes<'js>,
95            args: Rest<Value<'js>>,
96        ) -> Result<()> {
97            let mut args_iter = args.0.into_iter().rev();
98            let cb: Function = args_iter
99                .next()
100                .and_then(|v| v.into_function())
101                .or_throw_msg(&ctx, "Callback parameter is not a function")?;
102            let options = match args_iter.next() {
103                Some(v) => Opt(Some(v)),
104                None => Opt(None),
105            };
106
107            ctx.clone().spawn_exit(async move {
108                match $converter(ctx.clone(), value, options, $command) {
109                    Ok(obj) => {
110                        () = cb.call((Null.into_js(&ctx), obj))?;
111                        Ok::<_, Error>(())
112                    }
113                    Err(err) => {
114                        // `Error::Exception` is only a marker; the thrown value
115                        // (and therefore the real message) lives in ctx.catch().
116                        let err = if matches!(err, Error::Exception) {
117                            ctx.catch()
118                        } else {
119                            Exception::from_message(ctx.clone(), &err.to_string())?.into_value()
120                        };
121                        () = cb.call((err,))?;
122                        Ok(())
123                    }
124                }
125            })?;
126            Ok(())
127        }
128    };
129}
130pub struct ZlibModule;
131
132impl ModuleDef for ZlibModule {
133    fn declare(declare: &Declarations) -> Result<()> {
134        declare.declare("deflate")?;
135        declare.declare("deflateSync")?;
136
137        declare.declare("deflateRaw")?;
138        declare.declare("deflateRawSync")?;
139
140        declare.declare("gzip")?;
141        declare.declare("gzipSync")?;
142
143        declare.declare("inflate")?;
144        declare.declare("inflateSync")?;
145
146        declare.declare("inflateRaw")?;
147        declare.declare("inflateRawSync")?;
148
149        declare.declare("gunzip")?;
150        declare.declare("gunzipSync")?;
151
152        declare.declare("brotliCompress")?;
153        declare.declare("brotliCompressSync")?;
154
155        declare.declare("brotliDecompress")?;
156        declare.declare("brotliDecompressSync")?;
157
158        #[cfg(feature = "zlib-zstd")]
159        {
160            declare.declare("zstdCompress")?;
161            declare.declare("zstdCompressSync")?;
162            declare.declare("zstdDecompress")?;
163            declare.declare("zstdDecompressSync")?;
164        }
165
166        declare.declare("default")?;
167        Ok(())
168    }
169
170    fn evaluate<'js>(ctx: &Ctx<'js>, exports: &Exports<'js>) -> Result<()> {
171        export_default(ctx, exports, |default| {
172            default.set("deflate", Func::from(deflate))?;
173            default.set("deflateSync", Func::from(deflate_sync))?;
174
175            default.set("deflateRaw", Func::from(deflate_raw))?;
176            default.set("deflateRawSync", Func::from(deflate_raw_sync))?;
177
178            default.set("gzip", Func::from(gzip))?;
179            default.set("gzipSync", Func::from(gzip_sync))?;
180
181            default.set("inflate", Func::from(inflate))?;
182            default.set("inflateSync", Func::from(inflate_sync))?;
183
184            default.set("inflateRaw", Func::from(inflate_raw))?;
185            default.set("inflateRawSync", Func::from(inflate_raw_sync))?;
186
187            default.set("gunzip", Func::from(gunzip))?;
188            default.set("gunzipSync", Func::from(gunzip_sync))?;
189
190            default.set("brotliCompress", Func::from(br_comp))?;
191            default.set("brotliCompressSync", Func::from(br_comp_sync))?;
192
193            default.set("brotliDecompress", Func::from(br_decomp))?;
194            default.set("brotliDecompressSync", Func::from(br_decomp_sync))?;
195
196            #[cfg(feature = "zlib-zstd")]
197            {
198                default.set("zstdCompress", Func::from(zstd_comp))?;
199                default.set("zstdCompressSync", Func::from(zstd_comp_sync))?;
200                default.set("zstdDecompress", Func::from(zstd_decomp))?;
201                default.set("zstdDecompressSync", Func::from(zstd_decomp_sync))?;
202            }
203
204            Ok(())
205        })
206    }
207}
208
209impl From<ZlibModule> for ModuleInfo<ZlibModule> {
210    fn from(val: ZlibModule) -> Self {
211        ModuleInfo {
212            name: "zlib",
213            module: val,
214        }
215    }
216}
217
218// Exported macros live at the package root.
219#[allow(unused_imports)]
220pub use crate::{define_cb_function, define_sync_function};