use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
Absolute,
Relative,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LcwError {
Truncated,
BadOffset,
TooLarge,
}
impl fmt::Display for LcwError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LcwError::Truncated => write!(f, "stream ended in the middle of a command"),
LcwError::BadOffset => write!(f, "copy command references unwritten data"),
LcwError::TooLarge => write!(f, "output exceeds the size limit"),
}
}
}
impl std::error::Error for LcwError {}
pub fn decompress(src: &[u8], max_out: usize) -> Result<Vec<u8>, LcwError> {
match src.split_first() {
Some((0, rest)) => decompress_with(rest, Mode::Relative, max_out),
_ => decompress_with(src, Mode::Absolute, max_out),
}
}
pub fn decompress_with(src: &[u8], mode: Mode, max_out: usize) -> Result<Vec<u8>, LcwError> {
let mut out = Vec::new();
let mut sp = 0;
while let Some(&cmd) = src.get(sp) {
sp += 1;
if cmd == 0x80 {
break;
} else if cmd & 0x80 == 0 {
let count = usize::from(cmd >> 4) + 3;
let offset = usize::from(cmd & 0x0f) << 8
| usize::from(*src.get(sp).ok_or(LcwError::Truncated)?);
sp += 1;
copy_back(&mut out, offset, count, max_out)?;
} else if cmd & 0x40 == 0 {
let count = usize::from(cmd & 0x3f);
let literal = src.get(sp..sp + count).ok_or(LcwError::Truncated)?;
sp += count;
if out.len() + count > max_out {
return Err(LcwError::TooLarge);
}
out.extend_from_slice(literal);
} else if cmd == 0xfe {
let count = usize::from(read_u16(src, sp)?);
let color = *src.get(sp + 2).ok_or(LcwError::Truncated)?;
sp += 3;
if out.len() + count > max_out {
return Err(LcwError::TooLarge);
}
out.resize(out.len() + count, color);
} else {
let (count, pos) = if cmd == 0xff {
let count = usize::from(read_u16(src, sp)?);
let pos = usize::from(read_u16(src, sp + 2)?);
sp += 4;
(count, pos)
} else {
let pos = usize::from(read_u16(src, sp)?);
sp += 2;
(usize::from(cmd & 0x3f) + 3, pos)
};
if count > 0 {
let offset = match mode {
Mode::Absolute => out.len().checked_sub(pos).ok_or(LcwError::BadOffset)?,
Mode::Relative => pos,
};
copy_back(&mut out, offset, count, max_out)?;
}
}
}
Ok(out)
}
fn read_u16(src: &[u8], sp: usize) -> Result<u16, LcwError> {
let bytes = src.get(sp..sp + 2).ok_or(LcwError::Truncated)?;
Ok(u16::from_le_bytes([bytes[0], bytes[1]]))
}
fn copy_back(
out: &mut Vec<u8>,
offset: usize,
count: usize,
max_out: usize,
) -> Result<(), LcwError> {
if offset == 0 || offset > out.len() {
return Err(LcwError::BadOffset);
}
if out.len() + count > max_out {
return Err(LcwError::TooLarge);
}
for pos in (out.len() - offset..).take(count) {
let byte = out[pos];
out.push(byte);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn copies_literal_bytes() {
assert_eq!(decompress(b"\x82ab\x80", 64).unwrap(), b"ab");
}
#[test]
fn tolerates_missing_end_marker() {
assert_eq!(decompress(b"\x82ab", 64).unwrap(), b"ab");
}
#[test]
fn short_copy_references_recent_output() {
assert_eq!(decompress(b"\x83abc\x00\x03\x80", 64).unwrap(), b"abcabc");
}
#[test]
fn short_copy_with_offset_one_repeats_last_byte() {
assert_eq!(decompress(b"\x81a\x50\x01\x80", 64).unwrap(), b"aaaaaaaaa");
}
#[test]
fn fill_writes_color_count_times() {
assert_eq!(decompress(b"\xfe\x05\x00A\x80", 64).unwrap(), b"AAAAA");
}
#[test]
fn long_copy_absolute_addresses_from_start() {
assert_eq!(
decompress(b"\x84abcd\xc0\x01\x00\x80", 64).unwrap(),
b"abcdbcd"
);
}
#[test]
fn long_copy_relative_addresses_from_write_position() {
assert_eq!(
decompress(b"\x00\x84abcd\xc0\x04\x00\x80", 64).unwrap(),
b"abcdabc"
);
}
#[test]
fn very_long_copy_takes_count_and_position_words() {
let out = decompress(b"\x82ab\xff\x06\x00\x00\x00\x80", 64).unwrap();
assert_eq!(out, b"abababab");
}
#[test]
fn errors_on_backreference_before_start() {
assert_eq!(
decompress(b"\x81a\x00\x05\x80", 64),
Err(LcwError::BadOffset)
);
assert_eq!(
decompress(b"\x81a\xc0\x02\x00\x80", 64),
Err(LcwError::BadOffset)
);
}
#[test]
fn errors_on_truncated_command() {
assert_eq!(decompress(b"\x85ab", 64), Err(LcwError::Truncated));
assert_eq!(decompress(b"\xfe\x05", 64), Err(LcwError::Truncated));
assert_eq!(decompress(b"\xff\x06\x00", 64), Err(LcwError::Truncated));
}
#[test]
fn errors_when_output_exceeds_cap() {
assert_eq!(
decompress(b"\xfe\xff\xff\x41\x80", 64),
Err(LcwError::TooLarge)
);
}
}