Skip to main content

fetchlet_web/compression/
decompressor.rs

1use super::codec::{Codec, Format};
2use crate::Result;
3
4/// A compression format of [`Decompressor`], as the Compression Standard
5/// names them.
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub enum CompressionFormat {
8    /// zlib (RFC 1950), the HTTP `deflate` coding.
9    Deflate,
10    /// Raw deflate (RFC 1951), which some servers send as `deflate`.
11    DeflateRaw,
12    /// gzip (RFC 1952).
13    Gzip,
14    /// Brotli (RFC 7932).
15    Brotli,
16}
17
18/// The streaming decompressor of `DecompressionStream`, for host code such
19/// as an HTTP client that decodes a `Content-Encoding`.
20///
21/// Write input, then read output until [`read`](Self::read) returns `None`
22/// before writing again; after [`finish`](Self::finish), reads return the
23/// rest and fail if the compressed stream ended early. Each read returns at
24/// most 64 KiB, so a small input never inflates into one large buffer, and
25/// the decompressed bytes in all count toward `limit`, failing with
26/// `LimitExceeded` past it. Data after the end of the stream, invalid data
27/// and a gzip checksum that does not match fail with `InvalidRequest`.
28pub struct Decompressor(Codec);
29
30impl Decompressor {
31    pub fn new(format: CompressionFormat, limit: Option<usize>) -> Self {
32        let format = match format {
33            CompressionFormat::Deflate => Format::Deflate,
34            CompressionFormat::DeflateRaw => Format::DeflateRaw,
35            CompressionFormat::Gzip => Format::Gzip,
36            CompressionFormat::Brotli => Format::Brotli,
37        };
38        Self(Codec::decompressor(format, limit))
39    }
40
41    /// Add compressed input. Fails while output of the previous write is
42    /// still to be read.
43    pub fn write(&mut self, bytes: &[u8]) -> Result<()> {
44        self.0.write(bytes)
45    }
46
47    /// Mark the end of the compressed input.
48    pub fn finish(&mut self) {
49        self.0.finish();
50    }
51
52    /// The next piece of output, or `None` until more input arrives, or,
53    /// after [`finish`](Self::finish), once the stream is complete.
54    pub fn read(&mut self) -> Result<Option<Vec<u8>>> {
55        self.0.read()
56    }
57}
58
59impl std::fmt::Debug for Decompressor {
60    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        formatter
62            .debug_struct("Decompressor")
63            .finish_non_exhaustive()
64    }
65}