use ::brotli::{BrotliDecompressStream, BrotliResult, BrotliState, HeapAlloc, HuffmanCode};
use super::{FilterError, predictor};
use crate::object::Dict;
pub fn decode(data: &[u8], parms: Option<&Dict>) -> Result<Vec<u8>, FilterError> {
decode_polled(data, parms, &super::never_cancelled)
}
pub(super) fn decode_polled(
data: &[u8],
parms: Option<&Dict>,
cancelled: &dyn Fn() -> bool,
) -> Result<Vec<u8>, FilterError> {
let plain = decompress_bounded(data, cancelled)?;
match predictor::Params::from_dict(parms)? {
None => Ok(plain),
Some(p) => predictor::unpredict_polled(plain, &p, cancelled),
}
}
#[doc(hidden)] pub fn encode(data: &[u8], quality: u32) -> std::io::Result<Vec<u8>> {
let params = ::brotli::enc::BrotliEncoderParams {
quality: i32::try_from(quality.min(11)).unwrap_or(11),
lgwin: 22,
..Default::default()
};
let mut out = Vec::with_capacity(data.len() / 2 + 64);
::brotli::BrotliCompress(&mut &data[..], &mut out, ¶ms)?;
Ok(out)
}
fn decompress_bounded(data: &[u8], cancelled: &dyn Fn() -> bool) -> Result<Vec<u8>, FilterError> {
super::drain(
&mut Unbrotli::new(std::borrow::Cow::Borrowed(data)),
cancelled,
)
}
pub(super) struct Unbrotli<'a> {
data: std::borrow::Cow<'a, [u8]>,
state: BrotliState<HeapAlloc<u8>, HeapAlloc<u32>, HeapAlloc<HuffmanCode>>,
chunk: Vec<u8>,
available_in: usize,
input_offset: usize,
total_out: usize,
}
impl<'a> Unbrotli<'a> {
pub(super) fn new(data: std::borrow::Cow<'a, [u8]>) -> Self {
let state = BrotliState::new(
HeapAlloc::<u8>::new(0),
HeapAlloc::<u32>::new(0),
HeapAlloc::<HuffmanCode>::new(HuffmanCode::default()),
);
let available_in = data.len();
Self {
data,
state,
chunk: vec![0u8; super::CHUNK],
available_in,
input_offset: 0,
total_out: 0,
}
}
}
impl super::Pull for Unbrotli<'_> {
fn pull(&mut self, out: &mut Vec<u8>) -> Result<bool, FilterError> {
let mut available_out = self.chunk.len();
let mut output_offset = 0usize;
let status = BrotliDecompressStream(
&mut self.available_in,
&mut self.input_offset,
&self.data,
&mut available_out,
&mut output_offset,
&mut self.chunk,
&mut self.total_out,
&mut self.state,
);
let produced = output_offset;
out.extend_from_slice(self.chunk.get(..produced).unwrap_or(&[]));
match status {
BrotliResult::ResultSuccess => Ok(true),
BrotliResult::NeedsMoreInput => Err(FilterError::Truncated {
filter: "BrotliDecode",
}),
BrotliResult::ResultFailure => Err(FilterError::Corrupt {
filter: "BrotliDecode",
detail: "brotli stream rejected by the decoder".to_owned(),
}),
BrotliResult::NeedsMoreOutput if produced == 0 => Err(FilterError::Corrupt {
filter: "BrotliDecode",
detail: "decoder requested more output room without \
producing any bytes"
.to_owned(),
}),
BrotliResult::NeedsMoreOutput => Ok(false),
}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use super::*;
#[test]
fn encode_round_trips_through_decode_at_every_quality_end() {
let plain: Vec<u8> = (0..20_000u32).map(|i| (i % 251) as u8).collect();
for q in [0, 5, 11, 99] {
let packed = encode(&plain, q).unwrap();
assert!(packed.len() < plain.len(), "quality {q} did not shrink");
assert_eq!(decode(&packed, None).unwrap(), plain, "quality {q}");
}
}
#[test]
fn encode_of_nothing_decodes_to_nothing() {
assert_eq!(decode(&encode(b"", 11).unwrap(), None).unwrap(), b"");
}
fn compress(plain: &[u8]) -> Vec<u8> {
compress_at(plain, ::brotli::enc::BrotliEncoderParams::default().quality)
}
fn compress_at(plain: &[u8], quality: i32) -> Vec<u8> {
let mut out = Vec::new();
let mut input = plain;
let params = ::brotli::enc::BrotliEncoderParams {
quality,
..Default::default()
};
::brotli::BrotliCompress(&mut input, &mut out, ¶ms)
.expect("reference encoder compresses");
out
}
#[test]
fn a_round_trip_returns_the_original_bytes() {
let plain = b"pdfcer brotli round trip, with enough text to actually compress. \
pdfcer brotli round trip, with enough text to actually compress."
.repeat(4);
let decoded = decode(&compress(&plain), None).expect("decodes");
assert_eq!(decoded, plain);
}
#[test]
fn a_truncated_stream_is_an_error_and_not_a_short_read() {
let plain = b"enough bytes that the encoder emits a multi-part stream".repeat(64);
let full = compress(&plain);
let cut = full
.get(..full.len() / 2)
.expect("half of a slice is in bounds");
match decode(cut, None) {
Err(FilterError::Truncated { filter }) => assert_eq!(filter, "BrotliDecode"),
Err(other) => panic!("truncation must be Truncated, got {other:?}"),
Ok(v) => panic!(
"a truncated stream decoded to {} bytes instead of erroring — \
this is the silent-partial-data failure",
v.len()
),
}
}
#[test]
fn garbage_is_rejected_rather_than_guessed_at() {
let err = decode(&[0xff_u8; 64], None).unwrap_err();
assert!(
matches!(
err,
FilterError::Corrupt {
filter: "BrotliDecode",
..
} | FilterError::Truncated {
filter: "BrotliDecode"
}
),
"expected a Brotli-attributed refusal, got {err:?}"
);
}
#[test]
fn the_output_ceiling_refuses_a_bomb() {
let plain = vec![0u8; crate::filters::MAX_DECODED_LEN + (1 << 20)];
let err = decode(&compress_at(&plain, 1), None).unwrap_err();
assert!(
matches!(err, FilterError::OutputTooLarge),
"expected OutputTooLarge, got {err:?}"
);
}
}