Skip to main content

wasmcheck/
compression.rs

1//! How hard `wasmcheck` compresses before reporting a size.
2
3use std::fmt;
4
5use crate::error::WasmCheckError;
6
7/// The gzip level and brotli quality used to measure a bundle.
8///
9/// The defaults model **what a server or CDN does on the fly** — gzip level 6,
10/// brotli quality 5 — rather than the best compression achievable. Measuring at
11/// the maximum reports a size smaller than what actually goes over the wire, so
12/// a budget can pass here and still be blown in production.
13///
14/// Use [`Compression::max`] when your assets are precompressed at build time
15/// and served as-is.
16///
17/// # Examples
18///
19/// ```
20/// use wasmcheck::Compression;
21///
22/// // The default is the CDN preset.
23/// assert_eq!(Compression::default(), Compression::cdn());
24/// assert_eq!(Compression::cdn().gzip_level(), 6);
25/// assert_eq!(Compression::cdn().brotli_quality(), 5);
26///
27/// // Precompressed assets:
28/// assert_eq!(Compression::max(), Compression::new(9, 11)?);
29///
30/// assert!(Compression::new(10, 5).is_err());
31/// # Ok::<(), wasmcheck::WasmCheckError>(())
32/// ```
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
34pub struct Compression {
35    gzip_level: u32,
36    brotli_quality: i32,
37}
38
39impl Compression {
40    /// The gzip level [`Compression::cdn`] uses.
41    pub const CDN_GZIP_LEVEL: u32 = 6;
42    /// The brotli quality [`Compression::cdn`] uses.
43    pub const CDN_BROTLI_QUALITY: i32 = 5;
44    /// The gzip level [`Compression::max`] uses.
45    pub const MAX_GZIP_LEVEL: u32 = 9;
46    /// The brotli quality [`Compression::max`] uses.
47    pub const MAX_BROTLI_QUALITY: i32 = 11;
48
49    /// What a server or CDN does on the fly: gzip 6, brotli 5. This is the
50    /// default.
51    #[must_use]
52    pub const fn cdn() -> Self {
53        Self {
54            gzip_level: Self::CDN_GZIP_LEVEL,
55            brotli_quality: Self::CDN_BROTLI_QUALITY,
56        }
57    }
58
59    /// Precompression at the highest setting: gzip 9, brotli 11.
60    #[must_use]
61    pub const fn max() -> Self {
62        Self {
63            gzip_level: Self::MAX_GZIP_LEVEL,
64            brotli_quality: Self::MAX_BROTLI_QUALITY,
65        }
66    }
67
68    /// A custom setting.
69    ///
70    /// # Errors
71    ///
72    /// Returns [`WasmCheckError::InvalidGzipLevel`] when `gzip_level` is above
73    /// 9 and [`WasmCheckError::InvalidBrotliQuality`] when `brotli_quality` is
74    /// outside `0..=11`.
75    ///
76    /// # Examples
77    ///
78    /// ```
79    /// use wasmcheck::Compression;
80    ///
81    /// assert_eq!(Compression::new(9, 11)?.gzip_level(), 9);
82    /// assert!(Compression::new(5, 12).is_err());
83    /// # Ok::<(), wasmcheck::WasmCheckError>(())
84    /// ```
85    pub fn new(gzip_level: u32, brotli_quality: i32) -> Result<Self, WasmCheckError> {
86        let compression = Self {
87            gzip_level,
88            brotli_quality,
89        };
90        compression.validate()?;
91        Ok(compression)
92    }
93
94    /// The gzip compression level, `0..=9`.
95    #[must_use]
96    pub const fn gzip_level(&self) -> u32 {
97        self.gzip_level
98    }
99
100    /// The brotli quality, `0..=11`.
101    #[must_use]
102    pub const fn brotli_quality(&self) -> i32 {
103        self.brotli_quality
104    }
105
106    /// The same setting with a different gzip level.
107    ///
108    /// # Errors
109    ///
110    /// Returns [`WasmCheckError::InvalidGzipLevel`] when `level` is above 9.
111    pub fn with_gzip_level(self, level: u32) -> Result<Self, WasmCheckError> {
112        Self::new(level, self.brotli_quality)
113    }
114
115    /// The same setting with a different brotli quality.
116    ///
117    /// # Errors
118    ///
119    /// Returns [`WasmCheckError::InvalidBrotliQuality`] when `quality` is
120    /// outside `0..=11`.
121    pub fn with_brotli_quality(self, quality: i32) -> Result<Self, WasmCheckError> {
122        Self::new(self.gzip_level, quality)
123    }
124
125    /// `true` when this is the [`Compression::cdn`] preset, i.e. the default.
126    #[must_use]
127    pub const fn is_default(&self) -> bool {
128        self.gzip_level == Self::CDN_GZIP_LEVEL && self.brotli_quality == Self::CDN_BROTLI_QUALITY
129    }
130
131    fn validate(&self) -> Result<(), WasmCheckError> {
132        if self.gzip_level > Self::MAX_GZIP_LEVEL {
133            return Err(WasmCheckError::InvalidGzipLevel(i64::from(self.gzip_level)));
134        }
135        if self.brotli_quality < 0 || self.brotli_quality > Self::MAX_BROTLI_QUALITY {
136            return Err(WasmCheckError::InvalidBrotliQuality(i64::from(
137                self.brotli_quality,
138            )));
139        }
140        Ok(())
141    }
142}
143
144impl Default for Compression {
145    fn default() -> Self {
146        Self::cdn()
147    }
148}
149
150impl fmt::Display for Compression {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        write!(
153            f,
154            "gzip level {}, brotli quality {}",
155            self.gzip_level, self.brotli_quality
156        )
157    }
158}
159
160impl<'de> serde::Deserialize<'de> for Compression {
161    /// Deserializes `{"gzip_level": 6, "brotli_quality": 5}`, defaulting each
162    /// missing field to the CDN preset and rejecting out-of-range values.
163    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
164    where
165        D: serde::Deserializer<'de>,
166    {
167        #[derive(serde::Deserialize)]
168        struct Raw {
169            gzip_level: Option<u32>,
170            brotli_quality: Option<i32>,
171        }
172
173        let raw = Raw::deserialize(deserializer)?;
174        let cdn = Compression::cdn();
175        Compression::new(
176            raw.gzip_level.unwrap_or(cdn.gzip_level()),
177            raw.brotli_quality.unwrap_or(cdn.brotli_quality()),
178        )
179        .map_err(serde::de::Error::custom)
180    }
181}