quickjs_jit_stdlib/llrt/llrt_compression/
streaming.rs1use std::io::{self, Write};
7
8#[cfg(all(not(any()), feature = "zlib"))]
9use brotli as brotlic;
10
11pub enum StreamingDecoder {
13 #[cfg(any(any(), feature = "zlib"))]
14 Gzip(flate2::write::GzDecoder<Vec<u8>>),
15 #[cfg(any(any(), feature = "zlib"))]
16 Deflate(flate2::write::ZlibDecoder<Vec<u8>>),
17 #[cfg(any(any(), feature = "zlib-zstd"))]
18 Zstd(zstd::stream::write::Decoder<'static, Vec<u8>>),
19 #[cfg(any(any(), feature = "zlib"))]
20 Brotli(brotlic::DecompressorWriter<Vec<u8>>),
21 Identity,
22}
23
24impl StreamingDecoder {
25 pub fn new(encoding: &str) -> io::Result<Self> {
26 match encoding {
27 #[cfg(any(any(), feature = "zlib"))]
28 "gzip" => Ok(Self::Gzip(flate2::write::GzDecoder::new(Vec::new()))),
29 #[cfg(any(any(), feature = "zlib"))]
30 "deflate" => Ok(Self::Deflate(flate2::write::ZlibDecoder::new(Vec::new()))),
31 #[cfg(any(any(), feature = "zlib-zstd"))]
32 "zstd" => Ok(Self::Zstd(zstd::stream::write::Decoder::new(Vec::new())?)),
33 #[cfg(any())]
34 "br" => Ok(Self::Brotli(brotlic::DecompressorWriter::new(Vec::new()))),
35 #[cfg(all(not(any()), feature = "zlib"))]
36 "br" => Ok(Self::Brotli(brotlic::DecompressorWriter::new(
37 Vec::new(),
38 8_096,
39 ))),
40 "" | "identity" => Ok(Self::Identity),
41 _ => Err(io::Error::new(
42 io::ErrorKind::InvalidInput,
43 format!("unsupported encoding: {}", encoding),
44 )),
45 }
46 }
47
48 pub fn decompress_chunk(&mut self, input: &[u8]) -> io::Result<Vec<u8>> {
50 match self {
51 Self::Identity => Ok(input.to_vec()),
52 #[cfg(any(any(), feature = "zlib"))]
53 Self::Gzip(decoder) => {
54 decoder.write_all(input)?;
55 decoder.flush()?;
56 Ok(std::mem::take(decoder.get_mut()))
57 }
58 #[cfg(any(any(), feature = "zlib"))]
59 Self::Deflate(decoder) => {
60 decoder.write_all(input)?;
61 decoder.flush()?;
62 Ok(std::mem::take(decoder.get_mut()))
63 }
64 #[cfg(any(any(), feature = "zlib-zstd"))]
65 Self::Zstd(decoder) => {
66 decoder.write_all(input)?;
67 decoder.flush()?;
68 Ok(std::mem::take(decoder.get_mut()))
69 }
70 #[cfg(any(any(), feature = "zlib"))]
71 Self::Brotli(decoder) => {
72 decoder.write_all(input)?;
73 decoder.flush()?;
74 Ok(std::mem::take(decoder.get_mut()))
75 }
76 }
77 }
78
79 pub fn finish(self) -> io::Result<Vec<u8>> {
81 match self {
82 Self::Identity => Ok(Vec::new()),
83 #[cfg(any(any(), feature = "zlib"))]
84 Self::Gzip(decoder) => decoder.finish(),
85 #[cfg(any(any(), feature = "zlib"))]
86 Self::Deflate(decoder) => decoder.finish(),
87 #[cfg(any(any(), feature = "zlib-zstd"))]
88 Self::Zstd(decoder) => Ok(decoder.into_inner()),
89 #[cfg(any())]
90 Self::Brotli(decoder) => decoder
91 .into_inner()
92 .map_err(|e| io::Error::other(e.to_string())),
93 #[cfg(all(not(any()), feature = "zlib"))]
94 Self::Brotli(decoder) => decoder
95 .into_inner()
96 .map_err(|_| io::Error::other("brotli decompression failed")),
97 }
98 }
99}