Skip to main content

unbanished_formats/
stream.rs

1//! Block streams (`IO::CompressedStream`): a table of up-to-32 KiB blocks, each LZF or stored.
2//!
3//! ```text
4//! u32 n
5//! n x { u32 offset, u16 compSize (0 = stored), u16 rawSize }
6//! blocks...
7//! ```
8//! `IO::CompressedStream::Open` requires `4 + 8n + sum(compSize or rawSize) == len`.
9
10use crate::error::{format_err, Result};
11use crate::lzf;
12
13/// The largest expanded block, 32 KiB.
14pub const BLOCK_SIZE: usize = 0x8000;
15
16/// Expand a block stream.
17pub fn decode(buf: &[u8]) -> Result<Vec<u8>> {
18    let rd = |at: usize, n: usize| -> Result<&[u8]> {
19        buf.get(at..at + n)
20            .ok_or(crate::Error::Truncated { at, wanted: n })
21    };
22    let count = u32::from_le_bytes(rd(0, 4)?.try_into().unwrap()) as usize;
23    let table_end = 4usize.saturating_add(
24        count
25            .checked_mul(8)
26            .ok_or(crate::Error::Format("block count overflow".into()))?,
27    );
28    if table_end > buf.len() {
29        return format_err("block table exceeds stream");
30    }
31    let mut blocks = Vec::with_capacity(count);
32    let mut total = table_end;
33    for k in 0..count {
34        let e = rd(4 + 8 * k, 8)?;
35        let offset = u32::from_le_bytes(e[0..4].try_into().unwrap()) as usize;
36        let comp = u16::from_le_bytes(e[4..6].try_into().unwrap()) as usize;
37        let raw = u16::from_le_bytes(e[6..8].try_into().unwrap()) as usize;
38        total += if comp != 0 { comp } else { raw };
39        blocks.push((offset, comp, raw));
40    }
41    if total != buf.len() {
42        return format_err(format!(
43            "stream size mismatch: table says {total}, have {}",
44            buf.len()
45        ));
46    }
47    let mut out = Vec::with_capacity(blocks.iter().map(|b| b.2).sum());
48    for (offset, comp, raw) in blocks {
49        if comp != 0 {
50            lzf::decompress_into(rd(offset, comp)?, &mut out, BLOCK_SIZE)?;
51        } else {
52            out.extend_from_slice(rd(offset, raw)?);
53        }
54    }
55    Ok(out)
56}
57
58/// The writing side of [`decode`]: `raw` in 32 KiB blocks, each LZF unless storing it is no
59/// larger. Offsets count from the start of the stream.
60pub fn encode(raw: &[u8]) -> Vec<u8> {
61    let blocks: Vec<(Vec<u8>, usize)> = raw
62        .chunks(BLOCK_SIZE)
63        .map(|b| {
64            let packed = lzf::compress(b);
65            if packed.len() < b.len() {
66                (packed, b.len())
67            } else {
68                (Vec::new(), b.len())
69            }
70        })
71        .collect();
72    let mut out = Vec::new();
73    out.extend_from_slice(&(blocks.len() as u32).to_le_bytes());
74    let mut offset = 4 + 8 * blocks.len();
75    for (packed, len) in &blocks {
76        out.extend_from_slice(&(offset as u32).to_le_bytes());
77        out.extend_from_slice(&(packed.len() as u16).to_le_bytes());
78        out.extend_from_slice(&(*len as u16).to_le_bytes());
79        offset += if packed.is_empty() {
80            *len
81        } else {
82            packed.len()
83        };
84    }
85    for (chunk, (packed, _)) in raw.chunks(BLOCK_SIZE).zip(&blocks) {
86        out.extend_from_slice(if packed.is_empty() { chunk } else { packed });
87    }
88    out
89}