1use std::borrow::Cow;
4
5use crate::{Algorithm, Compression, Error, Sink};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11pub enum Mode {
12 #[default]
14 Generic,
15 Text,
17 Font,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct Brotli {
55 level: u32,
56 mode: Mode,
57}
58
59impl Default for Brotli {
60 fn default() -> Self {
61 Self::new()
62 }
63}
64
65impl Brotli {
66 pub const MIN_LEVEL: u32 = 0;
68 pub const MAX_LEVEL: u32 = 11;
70 pub const DEFAULT_LEVEL: u32 = 11;
72
73 pub const fn new() -> Self {
77 Brotli { level: Self::DEFAULT_LEVEL, mode: Mode::Generic }
78 }
79
80 pub const fn level(&self) -> u32 {
84 self.level
85 }
86
87 pub fn set_level(&mut self, level: i64) -> Result<(), Error> {
92 if level < i64::from(Self::MIN_LEVEL) || level > i64::from(Self::MAX_LEVEL) {
93 return Err(Error::InvalidArgument(format!(
94 "Level must be between {} and {}",
95 Self::MIN_LEVEL,
96 Self::MAX_LEVEL
97 )));
98 }
99 self.level = level as u32;
100 Ok(())
101 }
102
103 pub fn use_generic_mode(&mut self) {
107 self.mode = Mode::Generic;
108 }
109
110 pub fn use_text_mode(&mut self) {
116 self.mode = Mode::Generic;
117 }
118
119 pub fn use_font_mode(&mut self) {
125 self.mode = Mode::Generic;
126 }
127
128 pub const fn mode(&self) -> Mode {
130 self.mode
131 }
132
133 pub const fn is_supported() -> bool {
137 cfg!(feature = "brotli")
138 }
139
140 pub fn compress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
142 let mode = match self.mode {
143 Mode::Generic => 0,
144 Mode::Text => 1,
145 Mode::Font => 2,
146 };
147 imp::compress(data, i64::from(self.level), mode, out)
148 }
149
150 pub fn compress_with<S: Sink + ?Sized>(data: &[u8], level: i64, mode: i64, out: &mut S) -> Result<(), Error> {
156 imp::compress(data, level, mode, out)
157 }
158
159 pub fn decompress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
161 imp::decompress(data, out)
162 }
163}
164
165impl Algorithm for Brotli {
166 fn name(&self) -> &str {
167 Compression::BROTLI
168 }
169
170 fn content_encoding(&self) -> Cow<'_, str> {
171 Cow::Borrowed("br")
172 }
173
174 fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
175 let mut out = Vec::new();
176 self.compress_into(data, &mut out)?;
177 Ok(out)
178 }
179
180 fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
181 let mut out = Vec::new();
182 self.decompress_into(data, &mut out)?;
183 Ok(out)
184 }
185
186 fn supported(&self) -> bool {
187 Self::is_supported()
188 }
189}
190
191#[cfg(feature = "brotli")]
192mod imp {
193 use brotlic_sys as b;
200
201 use crate::sink::spare;
202 use crate::{Error, Sink};
203
204 const WINDOW: u32 = b::BROTLI_DEFAULT_WINDOW as u32;
206
207 const CHUNK: usize = 1 << 19;
209
210 const GEOMETRIC: usize = 8 << 20;
212
213 fn allocator<S: Sink + ?Sized>(out: &S) -> (b::brotli_alloc_func, b::brotli_free_func, *mut std::ffi::c_void) {
215 match out.allocator() {
216 Some(allocator) => (Some(allocator.alloc), Some(allocator.free), allocator.opaque),
217 None => (None, None, std::ptr::null_mut()),
218 }
219 }
220
221 struct Encoder(*mut b::BrotliEncoderState);
223
224 impl Drop for Encoder {
225 fn drop(&mut self) {
226 unsafe { b::BrotliEncoderDestroyInstance(self.0) };
228 }
229 }
230
231 struct Decoder(*mut b::BrotliDecoderState);
233
234 impl Drop for Decoder {
235 fn drop(&mut self) {
236 unsafe { b::BrotliDecoderDestroyInstance(self.0) };
238 }
239 }
240
241 pub(super) fn compress<S: Sink + ?Sized>(data: &[u8], level: i64, mode: i64, out: &mut S) -> Result<(), Error> {
246 let window = unsafe { b::BrotliEncoderMaxCompressedSize(data.len()) }.max(64);
248 let start = out.len();
249 let (alloc, free, opaque) = allocator(out);
250 let encoder = Encoder(unsafe { b::BrotliEncoderCreateInstance(alloc, free, opaque) });
252 if encoder.0.is_null() {
253 return Err(Error::Codec("brotli_compress(): failed to prepare compression".into()));
254 }
255 if !(0..=11).contains(&level) {
256 return Err(Error::Codec(format!(
257 "brotli_compress(): failed to compression level ({level}): must be within 0..11"
258 )));
259 }
260 if !(0..=2).contains(&mode) {
261 return Err(Error::Codec(format!(
262 "brotli_compress(): failed to compression mode ({mode}): must be BROTLI_GENERIC(0)|BROTLI_TEXT(1)|BROTLI_FONT(2)"
263 )));
264 }
265 let set = unsafe {
267 b::BrotliEncoderSetParameter(encoder.0, b::BrotliEncoderParameter_BROTLI_PARAM_QUALITY, level as u32) != 0
268 && b::BrotliEncoderSetParameter(encoder.0, b::BrotliEncoderParameter_BROTLI_PARAM_LGWIN, WINDOW) != 0
269 && b::BrotliEncoderSetParameter(encoder.0, b::BrotliEncoderParameter_BROTLI_PARAM_MODE, mode as u32)
270 != 0
271 };
272 if !set {
273 return Err(Error::Codec("brotli_compress(): failed to set compression parameters".into()));
274 }
275 let (mut available_in, mut next_in) = (data.len(), data.as_ptr());
276 while unsafe { b::BrotliEncoderIsFinished(encoder.0) } == 0 {
278 let len = out.len();
279 if !out.grow((len + window).max(if len == start { 0 } else { out.capacity() + out.capacity() / 2 })) {
280 return Err(Error::Codec("brotli_compress(): insufficient memory".into()));
281 }
282 let (at, _) = spare(out);
283 let (mut available_out, mut next_out) = (window, at);
284 let ok = unsafe {
287 b::BrotliEncoderCompressStream(
288 encoder.0,
289 b::BrotliEncoderOperation_BROTLI_OPERATION_FINISH,
290 &raw mut available_in,
291 &raw mut next_in,
292 &raw mut available_out,
293 &raw mut next_out,
294 std::ptr::null_mut(),
295 )
296 };
297 if ok == 0 {
298 return Err(Error::Codec("brotli_compress(): failed to compress".into()));
299 }
300 unsafe { out.set_len(len + (window - available_out)) };
302 }
303 Ok(())
304 }
305
306 pub(super) fn decompress<S: Sink + ?Sized>(data: &[u8], out: &mut S) -> Result<(), Error> {
310 let failed = || Error::Codec("brotli_uncompress(): failed to uncompress".into());
311 let decoder = Decoder(unsafe { b::BrotliDecoderCreateInstance(None, None, std::ptr::null_mut()) });
313 if decoder.0.is_null() {
314 return Err(Error::Codec("brotli_uncompress(): failed to prepare uncompression".into()));
315 }
316 if unsafe {
318 b::BrotliDecoderSetParameter(decoder.0, b::BrotliDecoderParameter_BROTLI_DECODER_PARAM_LARGE_WINDOW, 1)
319 } == 0
320 {
321 return Err(Error::Codec("brotli_uncompress(): failed to set uncompression parameters".into()));
322 }
323 let (mut available_in, mut next_in) = (data.len(), data.as_ptr());
324 let mut first = CHUNK.min(data.len().saturating_mul(4).max(1024));
325 loop {
326 let (len, capacity) = (out.len(), out.capacity());
327 let wanted = if capacity < GEOMETRIC { len + first } else { (len + first).max(capacity + capacity / 4) };
331 if len + first > capacity && !out.grow(wanted) {
332 return Err(Error::Codec("brotli_uncompress(): insufficient memory".into()));
333 }
334 first = CHUNK;
335 let (at, room) = spare(out);
336 let (mut available_out, mut next_out) = (room, at);
337 let result = unsafe {
340 b::BrotliDecoderDecompressStream(
341 decoder.0,
342 &raw mut available_in,
343 &raw mut next_in,
344 &raw mut available_out,
345 &raw mut next_out,
346 std::ptr::null_mut(),
347 )
348 };
349 unsafe { out.set_len(len + (room - available_out)) };
351 match result {
352 b::BrotliDecoderResult_BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT => {}
353 b::BrotliDecoderResult_BROTLI_DECODER_RESULT_SUCCESS => return Ok(()),
354 _ => return Err(failed()),
355 }
356 }
357 }
358}
359
360#[cfg(not(feature = "brotli"))]
361mod imp {
362 use crate::{Error, Sink};
363
364 pub(super) fn compress<S: Sink + ?Sized>(_: &[u8], _: i64, _: i64, _: &mut S) -> Result<(), Error> {
365 Err(Error::undefined("brotli_compress"))
366 }
367
368 pub(super) fn decompress<S: Sink + ?Sized>(_: &[u8], _: &mut S) -> Result<(), Error> {
369 Err(Error::undefined("brotli_uncompress"))
370 }
371}
372
373#[cfg(all(test, feature = "brotli"))]
374mod tests {
375 use super::*;
376
377 #[test]
378 fn levels() {
379 let mut brotli = Brotli::new();
380 assert_eq!(brotli.set_level(-1), Err(Error::InvalidArgument("Level must be between 0 and 11".into())));
381 assert_eq!(brotli.set_level(12), Err(Error::InvalidArgument("Level must be between 0 and 11".into())));
382 let data = b"Lorem ipsum dolor sit amet ".repeat(500);
383 for level in 0..=11 {
384 brotli.set_level(level).unwrap();
385 assert_eq!(brotli.decompress(&brotli.compress(&data).unwrap()).unwrap(), data);
386 }
387 }
388
389 #[test]
390 fn modes_stay_generic() {
391 let mut brotli = Brotli::new();
392 brotli.use_text_mode();
393 assert_eq!(brotli.mode(), Mode::Generic);
394 brotli.use_font_mode();
395 assert_eq!(brotli.mode(), Mode::Generic);
396 }
397
398 #[test]
399 fn invalid_data() {
400 let failed = Err(Error::Codec("brotli_uncompress(): failed to uncompress".into()));
401 assert_eq!(Brotli::new().decompress(b""), failed);
402 assert_eq!(Brotli::new().decompress(b"garbage"), failed);
403 let body = Brotli::new().compress(&b"Lorem ipsum ".repeat(1000)).unwrap();
404 assert_eq!(Brotli::new().decompress(&body[..body.len() - 1]), failed);
405 }
406
407 #[test]
408 fn unchecked_parameters() {
409 let mut out = Vec::new();
410 assert_eq!(
411 Brotli::compress_with(b"x", 12, 0, &mut out),
412 Err(Error::Codec("brotli_compress(): failed to compression level (12): must be within 0..11".into()))
413 );
414 assert_eq!(
415 Brotli::compress_with(b"x", 4, 3, &mut out),
416 Err(Error::Codec(
417 "brotli_compress(): failed to compression mode (3): must be BROTLI_GENERIC(0)|BROTLI_TEXT(1)|BROTLI_FONT(2)"
418 .into()
419 ))
420 );
421 Brotli::compress_with(b"text", 4, 1, &mut out).unwrap();
422 assert_eq!(Brotli::new().decompress(&out).unwrap(), b"text");
423 }
424
425 #[test]
426 fn large_output() {
427 let data = vec![b'a'; 3 << 20];
429 let body = Brotli::new().compress(&data).unwrap();
430 assert!(body.len() < 1000);
431 assert_eq!(Brotli::new().decompress(&body).unwrap(), data);
432 }
433}