Skip to main content

sark_http/payload/compress/
mod.rs

1use std::num;
2
3use miniz_oxide::deflate::core::{
4    CompressorOxide, TDEFLFlush, TDEFLStatus, compress, create_comp_flags_from_zip_params,
5};
6use o3::{
7    alloc,
8    buffer::pool::{self, owners, state},
9};
10
11use crate::payload::crc32::Hasher;
12
13#[doc(hidden)]
14pub mod dynamic;
15pub mod inflate;
16
17/// Fixed gzip member framing: a 10-byte header and an 8-byte trailer.
18const HEADER: usize = 10;
19const TRAILER: usize = 8;
20const FRAMING: usize = HEADER + TRAILER;
21const MAX_INPUT: usize = {
22    let mut len = Gzip::CAPACITY.get();
23    while HEADER + len + (len >> 12) + (len >> 14) + (len >> 25) + 13 + TRAILER
24        > Gzip::CAPACITY.get()
25    {
26        len -= 1;
27    }
28    len
29};
30
31/// Compression level handed to deflate within its closed 1..=10 range.
32const LEVEL: i32 = 3;
33
34/// Compression storage selected when constructing a protocol connection.
35pub trait Compression: Sized {
36    fn try_new() -> Result<Self, alloc::Error>;
37
38    /// Returns a smaller gzip body or keeps the original bytes unchanged.
39    fn encode(&mut self, bytes: &[u8]) -> Output;
40
41    fn try_encode(&mut self, bytes: &[u8]) -> Result<Frozen, Error>;
42}
43
44#[doc(hidden)]
45pub type Frozen = pool::Span<
46    owners::Plain<pool::Fixed<{ Gzip::SLOTS.get() }, { Gzip::CAPACITY.get() }>>,
47    pool::Owned,
48    pool::Frozen,
49>;
50
51pub enum Output {
52    Plain,
53    Compressed(Frozen),
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum Error {
58    Unavailable,
59    Input {
60        actual: usize,
61        limit: usize,
62    },
63    Exhausted,
64    Deflate {
65        status: TDEFLStatus,
66        read: usize,
67        wrote: usize,
68    },
69    Extent {
70        wrote: usize,
71        capacity: usize,
72        maximum: usize,
73    },
74}
75
76pub struct Gzip {
77    compressor: Box<CompressorOxide>,
78    checksum: Hasher,
79    pool: pool::Pool<
80        state::Initialized,
81        owners::Plain<pool::Fixed<{ Gzip::SLOTS.get() }, { Gzip::CAPACITY.get() }>>,
82    >,
83}
84
85impl Gzip {
86    pub const SLOTS: num::NonZero<usize> = num::NonZero::<usize>::MIN.saturating_add(31);
87    pub const CAPACITY: num::NonZero<usize> =
88        num::NonZero::<usize>::MIN.saturating_add(256 * 1024 - 1);
89
90    fn try_compress(&mut self, src: &[u8], maximum: usize) -> Result<Frozen, Error> {
91        let mut lease = self.pool.acquire().ok_or(Error::Exhausted)?;
92        let mut output = lease.output();
93        let capacity = output.len();
94        let bytes = output.as_mut_slice();
95        let room = capacity.checked_sub(FRAMING).ok_or(Error::Extent {
96            wrote: 0,
97            capacity,
98            maximum,
99        })?;
100        self.compressor.reset();
101        let (status, read, wrote) = compress(
102            &mut self.compressor,
103            src,
104            &mut bytes[HEADER..HEADER + room],
105            TDEFLFlush::Finish,
106        );
107        if status != TDEFLStatus::Done || read != src.len() {
108            return Err(Error::Deflate {
109                status,
110                read,
111                wrote,
112            });
113        }
114        let written = wrote
115            .checked_add(FRAMING)
116            .filter(|written| *written <= capacity && *written <= maximum)
117            .and_then(num::NonZero::new)
118            .ok_or(Error::Extent {
119                wrote,
120                capacity,
121                maximum,
122            })?;
123        bytes[..HEADER].copy_from_slice(&[0x1f, 0x8b, 0x08, 0, 0, 0, 0, 0, 0, 0xff]);
124        let end = written.get() - TRAILER;
125        let mut checksum = self.checksum.clone();
126        checksum.update(src);
127        bytes[end..end + 4].copy_from_slice(&checksum.finalize().to_le_bytes());
128        // SAFETY: written bounds this unchanged output and includes the eight-byte trailer.
129        unsafe { bytes.get_unchecked_mut(end + 4..written.get()) }
130            .copy_from_slice(&(src.len() as u32).to_le_bytes());
131        // SAFETY: deflate reported a complete stream and the exact nonzero extent
132        // was bounded above while this output stayed borrowed by its owner.
133        unsafe { output.complete(written) };
134        Ok(lease.freeze())
135    }
136}
137
138impl Compression for Gzip {
139    fn try_new() -> Result<Self, alloc::Error> {
140        let flags = create_comp_flags_from_zip_params(LEVEL, 0, 0);
141        let compressor = alloc::BoxExt::try_new(CompressorOxide::new(flags))?;
142        let checksum = Hasher::new();
143        let pool = pool::Pool::try_from(pool::Fixed::new())?;
144        Ok(Self {
145            compressor,
146            checksum,
147            pool,
148        })
149    }
150
151    fn encode(&mut self, src: &[u8]) -> Output {
152        if !(FRAMING + 1..=MAX_INPUT).contains(&src.len()) {
153            return Output::Plain;
154        }
155        match self.try_compress(src, src.len() - 1) {
156            Ok(frozen) => Output::Compressed(frozen),
157            Err(_) => Output::Plain,
158        }
159    }
160
161    fn try_encode(&mut self, src: &[u8]) -> Result<Frozen, Error> {
162        if src.len() > MAX_INPUT {
163            return Err(Error::Input {
164                actual: src.len(),
165                limit: MAX_INPUT,
166            });
167        }
168        self.try_compress(src, Self::CAPACITY.get())
169    }
170}
171
172impl Compression for () {
173    fn try_new() -> Result<Self, alloc::Error> {
174        Ok(())
175    }
176
177    fn encode(&mut self, _: &[u8]) -> Output {
178        Output::Plain
179    }
180
181    fn try_encode(&mut self, _: &[u8]) -> Result<Frozen, Error> {
182        Err(Error::Unavailable)
183    }
184}