Skip to main content

sark_http/payload/compress/
mod.rs

1use std::{num, ops::Deref};
2
3use o3::{
4    alloc,
5    buffer::{
6        self,
7        pool::{self, owners, state},
8    },
9};
10
11#[doc(hidden)]
12pub mod dynamic;
13mod ffi;
14pub mod inflate;
15
16type Backing = owners::Plain<pool::Fixed<{ Gzip::SLOTS.get() }, { Gzip::CAPACITY.get() }>>;
17
18/// Compression storage selected when constructing a protocol connection.
19pub trait Compression: Sized {
20    fn try_new() -> Result<Self, alloc::Error>;
21
22    /// Returns a smaller gzip body or keeps the original bytes unchanged.
23    fn encode(&mut self, bytes: &[u8]) -> Option<Frozen>;
24
25    fn try_encode(&mut self, bytes: &[u8]) -> Result<Frozen, Error>;
26}
27
28/// A completed gzip member retaining its original output slot.
29pub struct Frozen(pool::Span<Backing, pool::Owned, pool::Frozen>);
30
31impl Deref for Frozen {
32    type Target = [u8];
33
34    fn deref(&self) -> &[u8] {
35        self.0.as_ref()
36    }
37}
38
39impl buffer::Residency for Frozen {
40    fn resident(&self) -> usize {
41        self.0.resident()
42    }
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum Error {
47    Unavailable,
48    Input { actual: usize, limit: usize },
49    Exhausted,
50    Output { capacity: usize },
51}
52
53pub struct Gzip {
54    pool: pool::Pool<state::Initialized, Backing>,
55    codec: ffi::Codec,
56}
57
58impl Gzip {
59    pub const SLOTS: num::NonZero<usize> = num::NonZero::<usize>::MIN.saturating_add(31);
60    pub const CAPACITY: num::NonZero<usize> =
61        num::NonZero::<usize>::MIN.saturating_add(256 * 1024 - 1);
62}
63
64/// Level 1 closes nonfinal blocks at 65,535 bytes or 8,192 matches of at least four bytes.
65/// At most eight blocks and three extra stored chunks fit with framing in one slot.
66const MAX_INPUT: usize = 262_035;
67/// libdeflate 1.27 at level 1 emits stored blocks through 51 bytes.
68const MIN_COMPRESSIBLE: usize = 52;
69
70impl Compression for Gzip {
71    fn try_new() -> Result<Self, alloc::Error> {
72        Ok(Self {
73            pool: pool::Pool::try_from(pool::Fixed::new())?,
74            codec: ffi::Codec::try_new()?,
75        })
76    }
77
78    fn encode(&mut self, src: &[u8]) -> Option<Frozen> {
79        if !(MIN_COMPRESSIBLE..=MAX_INPUT).contains(&src.len()) {
80            return None;
81        }
82        self.codec.encode(&mut self.pool, src, src.len() - 1).ok()
83    }
84
85    fn try_encode(&mut self, src: &[u8]) -> Result<Frozen, Error> {
86        if src.len() > MAX_INPUT {
87            return Err(Error::Input {
88                actual: src.len(),
89                limit: MAX_INPUT,
90            });
91        }
92        self.codec.encode(&mut self.pool, src, Self::CAPACITY.get())
93    }
94}
95
96impl Compression for () {
97    fn try_new() -> Result<Self, alloc::Error> {
98        Ok(())
99    }
100
101    fn encode(&mut self, _: &[u8]) -> Option<Frozen> {
102        None
103    }
104
105    fn try_encode(&mut self, _: &[u8]) -> Result<Frozen, Error> {
106        Err(Error::Unavailable)
107    }
108}