use weezl::BitOrder;
use weezl::decode::Decoder;
use weezl::{LzwError, LzwStatus};
use super::{FilterError, FilterNotes, MAX_DECODED_LEN, predictor};
use crate::object::Dict;
const LZW_CHARACTER_BITS: u8 = 8;
pub fn encode(data: &[u8]) -> Result<Vec<u8>, FilterError> {
weezl::encode::Encoder::with_tiff_size_switch(BitOrder::Msb, LZW_CHARACTER_BITS)
.encode(data)
.map_err(|e| FilterError::Corrupt {
filter: "LZWDecode",
detail: e.to_string(),
})
}
pub fn decode(
data: &[u8],
parms: Option<&Dict>,
notes: &mut FilterNotes,
) -> Result<Vec<u8>, FilterError> {
let decompressed = decompress_bounded(data, early_change(parms), notes)?;
match predictor::Params::from_dict(parms)? {
None => Ok(decompressed),
Some(p) => predictor::unpredict(decompressed, &p),
}
}
fn early_change(parms: Option<&Dict>) -> bool {
parms
.and_then(|d| d.get(b"EarlyChange"))
.and_then(crate::object::Object::as_int)
.is_none_or(|v| v != 0)
}
fn decompress_bounded(
data: &[u8],
early_change: bool,
notes: &mut FilterNotes,
) -> Result<Vec<u8>, FilterError> {
const CHUNK: usize = 64 * 1024;
if !begins_with_clear_code(data) {
notes.lzw_framing_anomalies += 1;
}
let mut decoder = if early_change {
Decoder::with_tiff_size_switch(BitOrder::Msb, LZW_CHARACTER_BITS)
} else {
Decoder::new(BitOrder::Msb, LZW_CHARACTER_BITS)
};
let mut out: Vec<u8> = Vec::new();
let mut chunk = vec![0u8; CHUNK];
let mut consumed = 0usize;
loop {
let remaining = data.get(consumed..).unwrap_or(&[]);
let result = decoder.decode_bytes(remaining, &mut chunk);
let status = match result.status {
Ok(status) => status,
Err(LzwError::InvalidCode) => {
return Err(FilterError::Corrupt {
filter: "LZWDecode",
detail: "invalid code in LZW stream".to_owned(),
});
}
};
if out.len().saturating_add(result.consumed_out) > MAX_DECODED_LEN {
return Err(FilterError::OutputTooLarge);
}
out.extend_from_slice(chunk.get(..result.consumed_out).unwrap_or(&[]));
consumed = consumed.saturating_add(result.consumed_in);
match status {
LzwStatus::Done => return Ok(out),
LzwStatus::NoProgress => {
notes.lzw_framing_anomalies += 1;
return Ok(out);
}
LzwStatus::Ok => {
if result.consumed_in == 0 && result.consumed_out == 0 {
notes.lzw_framing_anomalies += 1;
return Ok(out);
}
}
}
}
}
fn begins_with_clear_code(data: &[u8]) -> bool {
match (data.first(), data.get(1)) {
(Some(0x80), Some(second)) => second & 0x80 == 0,
_ => false,
}
}
#[cfg(test)]
#[allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
mod tests {
use super::*;
use crate::object::{Name, Object};
fn lzw_encode(data: &[u8], early_change: bool) -> Vec<u8> {
use weezl::encode::Encoder;
let mut enc = if early_change {
Encoder::with_tiff_size_switch(BitOrder::Msb, LZW_CHARACTER_BITS)
} else {
Encoder::new(BitOrder::Msb, LZW_CHARACTER_BITS)
};
enc.encode(data).unwrap()
}
#[test]
fn the_shipping_encoder_round_trips_with_early_change_omitted() {
let original: Vec<u8> = (0..40_000u32).map(|i| ((i * 7) ^ (i >> 5)) as u8).collect();
for input in [Vec::new(), b"a".to_vec(), original] {
let encoded = encode(&input).unwrap();
let mut notes = FilterNotes::default();
assert_eq!(decode(&encoded, None, &mut notes).unwrap(), input);
assert_eq!(encoded, lzw_encode(&input, true));
}
}
fn parms_with(entries: &[(&[u8], i64)]) -> Dict {
let mut d = Dict::new();
for (k, v) in entries {
d.insert(Name::from(*k), Object::Integer(*v));
}
d
}
#[test]
fn roundtrip_early_change_default() {
let original: Vec<u8> = (0..40_000u32)
.map(|i| (i.wrapping_mul(37) >> 3) as u8)
.collect();
let encoded = lzw_encode(&original, true);
let mut notes = FilterNotes::default();
assert_eq!(decode(&encoded, None, &mut notes).unwrap(), original);
assert_eq!(
notes.lzw_framing_anomalies, 0,
"weezl emits a conformant ClearCode + EndOfInformation framing"
);
}
#[test]
fn roundtrip_early_change_one_explicit() {
let original = b"the quick brown fox jumps over the lazy dog. ".repeat(400);
let encoded = lzw_encode(&original, true);
let parms = parms_with(&[(b"EarlyChange", 1)]);
let mut notes = FilterNotes::default();
assert_eq!(
decode(&encoded, Some(&parms), &mut notes).unwrap(),
original
);
}
#[test]
fn roundtrip_early_change_zero() {
let original = b"the quick brown fox jumps over the lazy dog. ".repeat(400);
let encoded = lzw_encode(&original, false);
let parms = parms_with(&[(b"EarlyChange", 0)]);
let mut notes = FilterNotes::default();
assert_eq!(
decode(&encoded, Some(&parms), &mut notes).unwrap(),
original
);
}
#[test]
fn early_change_modes_are_not_interchangeable() {
let original: Vec<u8> = (0..40_000u32)
.map(|i| (i.wrapping_mul(37) >> 3) as u8)
.collect();
let encoded = lzw_encode(&original, false);
let wrong = parms_with(&[(b"EarlyChange", 1)]);
let mut notes = FilterNotes::default();
let got = decode(&encoded, Some(&wrong), &mut notes);
assert!(
got.map(|v| v != original).unwrap_or(true),
"EarlyChange 1 must NOT decode an EarlyChange-0 stream correctly"
);
}
#[test]
fn corrupt_stream_errs_never_passes_raw_bytes() {
let garbage = vec![0xFFu8; 64];
let mut notes = FilterNotes::default();
let result = decode(&garbage, None, &mut notes);
assert!(
matches!(result, Err(FilterError::Corrupt { .. })),
"got {result:?}"
);
}
#[test]
fn missing_clear_code_is_recovered_and_counted() {
let stream = [0x20u8, 0xC0, 0x40];
let mut notes = FilterNotes::default();
let out = decode(&stream, None, &mut notes).unwrap();
assert_eq!(out, b"A");
assert_eq!(notes.lzw_framing_anomalies, 1);
}
#[test]
fn missing_end_of_information_terminates_without_error() {
let stream = [0x80u8, 0x10, 0x40];
let mut notes = FilterNotes::default();
let out = decode(&stream, None, &mut notes).unwrap();
assert_eq!(out, b"A");
assert_eq!(notes.lzw_framing_anomalies, 1, "no EOI is one anomaly");
}
#[test]
fn empty_stream_is_empty_output_and_an_anomaly() {
let mut notes = FilterNotes::default();
assert!(decode(&[], None, &mut notes).unwrap().is_empty());
assert!(notes.lzw_framing_anomalies > 0);
}
#[test]
fn decompression_bomb_is_aborted_at_ceiling() {
let bomb_plain = vec![0u8; MAX_DECODED_LEN + 1024];
let bomb = lzw_encode(&bomb_plain, true);
assert!(bomb.len() < 4 * 1024 * 1024, "bomb should compress tiny");
let mut notes = FilterNotes::default();
assert_eq!(
decode(&bomb, None, &mut notes).unwrap_err(),
FilterError::OutputTooLarge
);
}
#[test]
fn predictor_applies_over_lzw_output() {
let filtered: Vec<u8> = [&[2u8][..], &[1, 2, 3, 4], &[2], &[10, 20, 30, 40]].concat();
let encoded = lzw_encode(&filtered, true);
let parms = parms_with(&[(b"Predictor", 12), (b"Columns", 4)]);
let mut notes = FilterNotes::default();
let out = decode(&encoded, Some(&parms), &mut notes).unwrap();
assert_eq!(out, vec![1, 2, 3, 4, 11, 22, 33, 44]);
}
#[test]
fn undefined_early_change_value_falls_back_to_the_default() {
let original = b"abcabcabcabc".repeat(50);
let encoded = lzw_encode(&original, true);
let parms = parms_with(&[(b"EarlyChange", 7)]);
let mut notes = FilterNotes::default();
assert_eq!(
decode(&encoded, Some(&parms), &mut notes).unwrap(),
original
);
}
#[test]
fn clear_code_detection_matches_msb_packing() {
assert!(begins_with_clear_code(&[0x80, 0x00]));
assert!(begins_with_clear_code(&[0x80, 0x7F]));
assert!(!begins_with_clear_code(&[0x80, 0x80]));
assert!(!begins_with_clear_code(&[0x00, 0x00]));
assert!(!begins_with_clear_code(&[0x80]));
assert!(!begins_with_clear_code(&[]));
}
}