diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 83c0b8f..c2856b2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,11 +15,13 @@ jobs: steps: - uses: actions/checkout@v7 - uses: dtolnay/rust-toolchain@stable - - run: cargo test + - run: cargo test --release - run: cargo check --all-features - uses: actions/setup-python@v7 with: python-version: '3.12' + - run: cargo build --release --bins + - run: python tools/stage_binaries.py - run: pip install -e '.[dev]' - run: pytest -q @@ -31,10 +33,17 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@stable + - name: Stage native binary + if: runner.os != 'Linux' + run: | + cargo build --release --bins + python tools/stage_binaries.py - uses: PyO3/maturin-action@v1 with: args: --release --out dist -i python3.10 -i python3.11 -i python3.12 -i python3.13 manylinux: auto + before-script-linux: cargo build --release --bins && python3.10 tools/stage_binaries.py - uses: actions/upload-artifact@v7 with: name: wheels-${{ matrix.os }} diff --git a/Cargo.toml b/Cargo.toml index 336e6e8..25ae867 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,12 +13,26 @@ documentation = "https://github.com/AnswerDotAI/fastbz2" name = "fastbz2" crate-type = ["cdylib", "rlib"] +[[bin]] +name = "fastbz2" +path = "src/bin/fastbz2.rs" +test = false + [profile.release] lto = true codegen-units = 1 [dependencies] -pyo3 = { version = ">=0.28", optional = true } +blake3 = "1.8.7" +clap = { version = "4.6.6", features = ["derive"] } +memmap2 = "0.9.11" +pyo3 = { version = ">=0.29.2", optional = true } +rayon = "1.12.0" +tempfile = "3.27.0" + +[dev-dependencies] +crabz2 = "0.4.0" +libbz2-rs-sys = { version = "0.2.5", default-features = false, features = ["std"] } [features] python = ["dep:pyo3"] diff --git a/DEV.md b/DEV.md index 027f06d..46cf707 100644 --- a/DEV.md +++ b/DEV.md @@ -6,34 +6,67 @@ ```text src/bitreader.rs bounded MSB-first in-memory bit reads +src/block.rs independently decodable block construction and validation src/crc.rs bzip2 block and combined-stream CRC primitives +src/decode.rs serial/parallel decode scheduling and index construction +src/decoder.rs bzip2 block machinery and 12-bit Huffman fast tables src/format.rs cheap structural scan for header and marker candidates +src/index.rs stable persistent index format +src/indexed.rs seekable decoded view and block cache src/lib.rs public Rust API and private PyO3 binding +src/source.rs owned and memory-mapped compressed sources python/fastbz2/ thin Python I/O wrapper over fastbz2._core -tests/ Python API and integration tests +tests/corpus/ selected upstream conformance and corruption fixtures +tests/ Rust CLI/corpus and Python API integration tests +tools/stage_binaries.py copy the release executable into Maturin wheel data ``` The current scanner deliberately does not treat 48-bit marker matches or later `BZh` headers as validated structure. Full decoding must establish the exact block chain and validate every block CRC plus the combined stream CRC before marker candidates can become trusted index entries. Python integration tests use standard-library `bz2`/libbz2 as an independent fixture generator. The decoder remains independent of files, threads, Python, and the CLI. Parallel scanning/decoding and indexed seeking are layered over it. Native workers never call Python. Large offsets use explicit 64-bit bit/byte types, and speculative block-marker hits are accepted only when they form an exact stream chain with valid block and combined stream CRCs. -Start with safe scalar Rust designed for LLVM auto-vectorisation. Add narrowly scoped unsafe or architecture-specific SIMD only after profiling, with the safe implementation retained as a differential oracle. +The production decoder is safe scalar Rust designed for LLVM auto-vectorisation. Huffman decoding uses a 4096-entry direct table for codes up to 12 bits and canonical fallback for longer codes. Add narrowly scoped unsafe or architecture-specific SIMD only after profiling; `libbz2-rs-sys` remains the dev-only differential oracle. ## Commands ```bash cargo test +cargo test --release cargo check --all-features -maturin develop +cargo build --release --bins +python tools/stage_binaries.py +maturin develop --release pytest -q ship-rs-build ``` Run `cargo fmt --check` after Rust edits and `chkstyle` after Python edits once tests pass. -## Performance acceptance +## Correctness and performance acceptance -Build the checked-out `librapidarchive` implementation and compare on the same host, input, output sink, cache condition, and thread counts. Compare several-run medians for single-thread and parallel throughput, scaling, peak RSS, and time to first output. Within 20% end-to-end throughput is good enough when correctness and memory requirements pass. +The normal release test path decodes selected valid and corrupt cases from the maintained upstream `bzip2-testfiles` collection. Generated byte distributions add differential coverage. Valid outputs are compared byte-for-byte with `libbz2-rs-sys`, which is a dev-only oracle and never part of production decoding. + +The same test binary contains a warmed end-to-end performance gate requiring `fastbz2` to complete a representative workload within 1.2 times the oracle. Keep the whole release test suite below five seconds on the primary development laptop; individual timed workloads should normally be about 0.1 seconds or less. Use the Simple English Wikipedia dump for heavier local throughput, scaling, memory, and time-to-first-output checks. `librapidarchive` was a one-time design comparison, not a retained baseline. + +Legacy randomized blocks produced by bzip2 versions before 0.9.5 are intentionally unsupported. Supporting that obsolete format would add complexity to the production decoder for data that is not realistically encountered today. + +### Local SimpleWiki benchmark + +`tests/wiki_perf.rs` contains a release-only local benchmark that is skipped by default. Its git-ignored fixture is a single bzip2 stream containing the first 84,423,012 decoded bytes (about 5%) of SimpleWiki, stored at `meta/simplewiki-first-5pct.xml.bz2`. Run it with: + +```bash +cargo test --release --test wiki_perf simplewiki_first_five_percent -- --ignored --nocapture +``` + +It uses all available CPUs by default. Set `FASTBZ2_THREADS` to compare an explicit thread count. The timed section includes allocation and decompression but excludes reading the compressed file and calculating its BLAKE3; decoded length, block/stream CRCs, and BLAKE3 are all checked. + +For an occasional full-dump confirmation, create `meta/simplewiki-full.xml.bz2` as a symlink to the local dump and run: + +```bash +cargo test --release --test wiki_perf simplewiki_full -- --ignored --nocapture +``` + +The full test streams decoded bytes into a counting sink and validates every block and stream CRC. Stream headers found during the structural scan remain speculative: only the exact byte-aligned header following a validated end-of-stream marker starts another stream. ## Platforms @@ -45,8 +78,9 @@ The canonical version lives in `Cargo.toml`. `pyproject.toml` gets the Python pa ## Release -1. Run `maturin develop && pytest -q`. -2. Confirm the release version in `Cargo.toml` (`[package].version`). -3. Run `ship-release`. +1. Run `cargo build --release --bins && python tools/stage_binaries.py`. +2. Run `maturin develop --release && pytest -q`. +3. Confirm the release version in `Cargo.toml` (`[package].version`). +4. Run `ship-release`. Fastship pushes the version tag for GitHub Actions, then bumps and pushes `Cargo.toml`. diff --git a/README.md b/README.md index 3d073e9..a474253 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,9 @@ Fast parallel and indexed bzip2 decompression for Rust and Python. `fastbz2` is initially focused solely on bzip2: a portable Rust core, a native CLI, and a thin PyO3 seekable-file API. The primary targets are Linux on x86-64 and ARM64, and macOS on ARM64; macOS Intel is best-effort. Correct output, block and stream CRC validation, bounded memory, and deterministic behaviour across thread counts are hard requirements. -The first performance target is end-to-end throughput within 20% of `librapidarchive`'s `indexed_bzip2` on the same host and input. Portable, SIMD-friendly Rust comes first; architecture-specific SIMD is added only when profiles justify it. +The performance floor is end-to-end decompression within 20% of the maintained pure-Rust `libbz2-rs-sys` decoder on a representative corpus. Portable, SIMD-friendly Rust comes first; architecture-specific SIMD is added only when profiles justify it. The much larger Simple English Wikipedia dump is used for local throughput measurements. -The first implemented layer is a safe, portable MSB-first bit reader, bzip2 CRC primitives, and a structural scanner for stream headers and non-byte-aligned block/end markers. The scanner reports candidates rather than claiming validation: the decoder, exact stream-chain validation, indexing, parallel scheduler, CLI, and seekable Python file API are not implemented yet. +The implementation includes a safe structural scanner, an in-repo decoder with a tuned 12-bit Huffman lookup table, CRC-validated block decoding, bounded parallel scheduling, persistent indexes, a native CLI, and a seekable Python file API. Marker scans remain speculative until decoding establishes an exact stream chain and validates block and combined-stream CRCs. ```python import bz2 @@ -19,15 +19,19 @@ result.blocks[0].bit_offset ## Inspiration and credit -The architecture is inspired by Maximilian Knespel's [`librapidarchive`](https://github.com/mxmlnkn/librapidarchive) and [`indexed_bzip2`](https://github.com/mxmlnkn/indexed_bzip2): in particular, scanning for non-byte-aligned bzip2 block markers, independently decoding blocks, ordered prefetch, and indexed seeking. That project's specialised decoder is itself derived from Rob Landley's 0BSD [`bzcat` implementation in Toybox](https://github.com/landley/toybox). `fastbz2` is intended as a new Rust implementation, with the original project retained as the correctness and performance reference. +The architecture was inspired by Maximilian Knespel's [`librapidarchive`](https://github.com/mxmlnkn/librapidarchive) and [`indexed_bzip2`](https://github.com/mxmlnkn/indexed_bzip2): in particular, scanning for non-byte-aligned bzip2 block markers, independently decoding blocks, ordered prefetch, and indexed seeking. That project's specialised decoder is itself derived from Rob Landley's 0BSD [`bzcat` implementation in Toybox](https://github.com/landley/toybox). ## Development ```bash pip install -e .[dev] -maturin develop && pytest -q +cargo build --release --bins && python tools/stage_binaries.py +cargo test --release +maturin develop --release && pytest -q ``` +Python wheels also install the native `fastbz2` executable directly into the environment's scripts directory; it is not a Python entry point or wrapper. + ## Build ```bash @@ -37,7 +41,8 @@ ship-rs-build ## Release ```bash -maturin develop && pytest -q +cargo build --release --bins && python tools/stage_binaries.py +maturin develop --release && pytest -q ship-release ``` diff --git a/pyproject.toml b/pyproject.toml index 5e615e2..a04f392 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -27,6 +27,7 @@ Issues = "https://github.com/AnswerDotAI/fastbz2/issues" features = ["extension-module"] python-source = "python" module-name = "fastbz2._core" +data = "target/wheel-data" [tool.uv] cache-keys = [{ file = "pyproject.toml" }, { file = "src/**/*.rs" }, { file = "Cargo.toml" }, { file = "Cargo.lock" }] diff --git a/python/fastbz2/__init__.py b/python/fastbz2/__init__.py index b1c5abe..f7a82c9 100644 --- a/python/fastbz2/__init__.py +++ b/python/fastbz2/__init__.py @@ -1,6 +1,12 @@ from collections import namedtuple +import io +import os +from pathlib import Path -from ._core import __version__, _scan, bz2_crc32 +from ._core import BadBzip2File, _IndexedReader, __version__, _build_index, _decompress, _scan, _test, bz2_crc32 + +DEFAULT_MEMORY_LIMIT = 512 * 1024 * 1024 +DEFAULT_CACHE_LIMIT = 64 * 1024 * 1024 StreamHeaderCandidate = namedtuple("StreamHeaderCandidate", "byte_offset block_size_100k") BlockCandidate = namedtuple("BlockCandidate", "bit_offset expected_crc randomized orig_ptr") @@ -19,6 +25,78 @@ def scan(data: bytes) -> ScanResult: stream_ends = [EndCandidate(*item) for item in stream_ends] return ScanResult(streams, blocks, stream_ends) +def decompress(data: bytes, *, threads=0, memory_limit=DEFAULT_MEMORY_LIMIT) -> bytes: + """Decompress and fully CRC-validate one or more concatenated bzip2 streams.""" + return _decompress(data, threads, memory_limit) + +class IndexedBzip2File(io.RawIOBase): + """Seekable binary reader backed by a validated bzip2 block index.""" + + def __init__(self, source, *, threads=0, index=None, memory_limit=DEFAULT_MEMORY_LIMIT, cache_limit=DEFAULT_CACHE_LIMIT): + super().__init__() + if isinstance(source, (bytes, bytearray, memoryview)): + if index is not None and not isinstance(index, (bytes, bytearray, memoryview)): + index = Path(index).read_bytes() + self._reader = _IndexedReader.from_bytes(bytes(source), threads, memory_limit, index, cache_limit) + else: + if index is not None and isinstance(index, (bytes, bytearray, memoryview)): + raise TypeError("an in-memory index requires an in-memory bzip2 source") + index_path = None if index is None else os.fspath(index) + self._reader = _IndexedReader.from_path(os.fspath(source), threads, memory_limit, index_path, cache_limit) + + def readable(self): return True + def seekable(self): return True + + def read(self, size=-1): + self._checkClosed() + return self._reader.read(size) + + def readinto(self, buffer): + data = self.read(len(buffer)) + buffer[:len(data)] = data + return len(data) + + def seek(self, offset, whence=io.SEEK_SET): + self._checkClosed() + return self._reader.seek(offset, whence) + + def tell(self): + self._checkClosed() + return self._reader.tell() + + @property + def size(self): + self._checkClosed() + return self._reader.size + + def index_bytes(self): + self._checkClosed() + return self._reader.index_bytes() + + def close(self): + self._reader = None + super().close() + +def open(source, *, threads=0, index=None, memory_limit=DEFAULT_MEMORY_LIMIT, cache_limit=DEFAULT_CACHE_LIMIT): + """Open a path or bytes object as a seekable bzip2 binary file.""" + return IndexedBzip2File(source, threads=threads, index=index, memory_limit=memory_limit, cache_limit=cache_limit) + +def build_index(source, path=None, *, threads=0, memory_limit=DEFAULT_MEMORY_LIMIT) -> bytes: + """Fully validate *source* and return its source-bound binary block index.""" + if isinstance(source, (bytes, bytearray, memoryview)): + reader = _IndexedReader.from_bytes(bytes(source), threads, memory_limit, None, DEFAULT_CACHE_LIMIT) + encoded = reader.index_bytes() + else: encoded = _build_index(os.fspath(source), threads, memory_limit) + if path is not None: Path(path).write_bytes(encoded) + return encoded + +def test(source, *, threads=0, memory_limit=DEFAULT_MEMORY_LIMIT): + """Fully decode and CRC-validate *source*, returning ``None`` on success.""" + if isinstance(source, (bytes, bytearray, memoryview)): + _IndexedReader.from_bytes(bytes(source), threads, memory_limit, None, DEFAULT_CACHE_LIMIT) + else: _test(os.fspath(source), threads, memory_limit) + __all__ = [ - "__version__", "BlockCandidate", "EndCandidate", "ScanResult", "StreamHeaderCandidate", "bz2_crc32", "scan" + "__version__", "BadBzip2File", "BlockCandidate", "DEFAULT_CACHE_LIMIT", "DEFAULT_MEMORY_LIMIT", "EndCandidate", + "IndexedBzip2File", "ScanResult", "StreamHeaderCandidate", "build_index", "bz2_crc32", "decompress", "open", "scan", "test" ] diff --git a/src/bin/fastbz2.rs b/src/bin/fastbz2.rs new file mode 100644 index 0000000..96a5952 --- /dev/null +++ b/src/bin/fastbz2.rs @@ -0,0 +1,179 @@ +use std::{ + fs, + io::{self, Read, Write}, + path::{Path, PathBuf}, + process::ExitCode, +}; + +use clap::{Parser, Subcommand}; +use fastbz2::{DecodeOptions, Error, Index, Source, build_index, decompress_to_writer}; +use tempfile::NamedTempFile; + +#[derive(Parser)] +#[command(version, about = "Fast parallel and indexed bzip2 decompression")] +struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand)] +enum Command { + /// Decompress INPUT, using - for stdin. + Decode { + input: String, + #[arg(short, long)] + output: Option, + #[arg(short = 'c', long, conflicts_with = "output")] + stdout: bool, + #[arg(short = 'P', long, default_value_t = 0)] + threads: usize, + #[arg(long, default_value = "512M", value_parser = parse_size)] + memory_limit: usize, + #[arg(short, long)] + force: bool, + }, + /// Fully decode and validate INPUT without writing plaintext. + Test { + input: String, + #[arg(short = 'P', long, default_value_t = 0)] + threads: usize, + #[arg(long, default_value = "512M", value_parser = parse_size)] + memory_limit: usize, + }, + /// Build a validated, source-bound block index. + Index { + input: PathBuf, + #[arg(short, long)] + output: Option, + #[arg(short = 'P', long, default_value_t = 0)] + threads: usize, + #[arg(long, default_value = "512M", value_parser = parse_size)] + memory_limit: usize, + #[arg(short, long)] + force: bool, + }, + /// Validate INPUT and show its stream/block layout. + List { + input: PathBuf, + #[arg(short = 'P', long, default_value_t = 0)] + threads: usize, + #[arg(long, default_value = "512M", value_parser = parse_size)] + memory_limit: usize, + }, +} + +fn main() -> ExitCode { + match run(Cli::parse()) { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("fastbz2: {error}"); + ExitCode::from(exit_status(&error)) + } + } +} + +fn run(cli: Cli) -> fastbz2::Result<()> { + match cli.command { + Command::Decode { input, output, stdout, threads, memory_limit, force } => { + let options = DecodeOptions { threads, memory_limit }; + if input == "-" { + if stdout || output.is_none() { + return decode_stdin(&mut io::stdout().lock()); + } + return atomic_write(output.as_ref().unwrap(), force, |writer| decode_stdin(writer)); + } + let input_path = Path::new(&input); + let source = Source::open(input_path)?; + if stdout { + decompress_to_writer(source.as_slice(), &mut io::stdout().lock(), options)?; + } else { + let output = output.unwrap_or_else(|| default_output(input_path)); + atomic_write(&output, force, |writer| decompress_to_writer(source.as_slice(), writer, options))?; + } + } + Command::Test { input, threads, memory_limit } => { + if input == "-" { + decode_stdin(&mut io::sink())?; + } else { + let source = Source::open(input)?; + decompress_to_writer(source.as_slice(), &mut io::sink(), DecodeOptions { threads, memory_limit })?; + } + } + Command::Index { input, output, threads, memory_limit, force } => { + let source = Source::open(&input)?; + let index = build_index(source.as_slice(), DecodeOptions { threads, memory_limit })?; + let output = output.unwrap_or_else(|| PathBuf::from(format!("{}.fbz2i", input.display()))); + atomic_write(&output, force, |writer| writer.write_all(&index.to_bytes()).map_err(Error::from))?; + } + Command::List { input, threads, memory_limit } => { + let source = Source::open(input)?; + let index = build_index(source.as_slice(), DecodeOptions { threads, memory_limit })?; + print_index(&index); + } + } + Ok(()) +} + +fn decode_stdin(output: &mut impl Write) -> fastbz2::Result<()> { + let mut input = Vec::new(); + io::stdin().lock().read_to_end(&mut input)?; + decompress_to_writer(&input, output, DecodeOptions::default()) +} + +fn atomic_write(path: &Path, force: bool, write: impl FnOnce(&mut fs::File) -> fastbz2::Result<()>) -> fastbz2::Result<()> { + if path.exists() && !force { + return Err(Error::Io(io::Error::new(io::ErrorKind::AlreadyExists, format!("{} already exists (use --force)", path.display())))); + } + let parent = path.parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")); + let mut temporary = NamedTempFile::new_in(parent)?; + write(temporary.as_file_mut())?; + temporary.as_file_mut().flush()?; + if force { + temporary.persist(path).map_err(|error| Error::Io(error.error))?; + } else { + temporary.persist_noclobber(path).map_err(|error| Error::Io(error.error))?; + } + Ok(()) +} + +fn default_output(input: &Path) -> PathBuf { + match input.extension().and_then(|extension| extension.to_str()) { + Some("bz2") => input.with_extension(""), + _ => PathBuf::from(format!("{}.out", input.display())), + } +} + +fn print_index(index: &Index) { + println!("compressed_bytes\t{}", index.source_len); + println!("decoded_bytes\t{}", index.decoded_len); + println!("streams\t{}", index.streams.len()); + println!("blocks\t{}", index.blocks.len()); + for (number, stream) in index.streams.iter().enumerate() { + println!( + "stream\t{number}\theader={}\tlevel={}\tblocks={}\tdecoded={}", + stream.compressed_header_byte, stream.block_size_100k, stream.block_count, stream.decoded_len + ); + } +} + +fn parse_size(value: &str) -> Result { + let split = value.find(|character: char| !character.is_ascii_digit()).unwrap_or(value.len()); + let number: usize = value[..split].parse().map_err(|_| format!("invalid size {value:?}"))?; + let multiplier = match value[split..].to_ascii_lowercase().as_str() { + "" | "b" => 1, + "k" | "kb" | "kib" => 1024, + "m" | "mb" | "mib" => 1024 * 1024, + "g" | "gb" | "gib" => 1024 * 1024 * 1024, + _ => return Err(format!("invalid size suffix in {value:?}")), + }; + number.checked_mul(multiplier).ok_or_else(|| format!("size {value:?} overflows this platform")) +} + +fn exit_status(error: &Error) -> u8 { + match error { + Error::Io(source) if source.kind() != io::ErrorKind::InvalidData => 1, + Error::InvalidConfiguration(_) => 2, + Error::InvalidStreamHeader | Error::Decode { .. } | Error::InvalidIndex(_) => 3, + _ => 4, + } +} diff --git a/src/block.rs b/src/block.rs new file mode 100644 index 0000000..83d9482 --- /dev/null +++ b/src/block.rs @@ -0,0 +1,31 @@ +use crate::{Result, decoder}; + +pub const MAX_ENCODED_BLOCK: usize = 900_000; +pub const MAX_DECODED_BLOCK: usize = MAX_ENCODED_BLOCK / 5 * 259 + 4; + +/// Decode and CRC-validate one bzip2 block bounded by two exact markers. +pub fn decode_block(data: &[u8], start_bit: u64, end_bit: u64, level: u8, expected_crc: u32) -> Result> { + decoder::decode_block(data, start_bit, end_bit, level, expected_crc) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{combine_stream_crc, scan}; + + const HELLO: &[u8] = &[ + 0x42, 0x5a, 0x68, 0x39, 0x31, 0x41, 0x59, 0x26, 0x53, 0x59, 0x71, 0x1c, 0x50, 0xc0, 0x00, 0x00, 0x03, 0xd9, 0x80, 0x00, 0x10, 0x40, 0x00, 0x10, 0x00, + 0x3a, 0x44, 0x90, 0x10, 0x20, 0x00, 0x31, 0x03, 0x40, 0xd0, 0x29, 0x80, 0x1e, 0xa2, 0xe0, 0x4c, 0xed, 0x69, 0xe0, 0xe1, 0x77, 0x24, 0x53, 0x85, 0x09, + 0x07, 0x11, 0xc5, 0x0c, 0x00, + ]; + + #[test] + fn decodes_scanned_block() { + let scan = scan(HELLO).unwrap(); + let block = &scan.blocks[0]; + let end = &scan.stream_ends[0]; + let out = decode_block(HELLO, block.bit_offset, end.bit_offset, 9, block.expected_crc).unwrap(); + assert_eq!(out, b"hello crabz2\n"); + assert_eq!(combine_stream_crc(0, block.expected_crc), end.expected_stream_crc); + } +} diff --git a/src/decode.rs b/src/decode.rs new file mode 100644 index 0000000..f6e312b --- /dev/null +++ b/src/decode.rs @@ -0,0 +1,302 @@ +use std::{collections::HashMap, io::Write, sync::Arc, thread}; + +use rayon::{ThreadPool, ThreadPoolBuilder, prelude::*}; + +use crate::format::scan_with_pool; +use crate::{ + BlockCandidate, BlockIndex, DecodeError, EndCandidate, Error, Index, MAX_DECODED_BLOCK, Result, StreamIndex, combine_stream_crc, decode_block, decoder, +}; + +pub const DEFAULT_MEMORY_LIMIT: usize = 512 * 1024 * 1024; + +#[derive(Clone, Copy, Debug)] +pub struct DecodeOptions { + /// Zero selects the process's available parallelism. + pub threads: usize, + /// Maximum decoded bytes held in the reorder window. + pub memory_limit: usize, +} + +impl Default for DecodeOptions { + fn default() -> Self { + Self { threads: 0, memory_limit: DEFAULT_MEMORY_LIMIT } + } +} + +impl DecodeOptions { + pub fn resolved_threads(self) -> usize { + if self.threads != 0 { self.threads } else { thread::available_parallelism().map(usize::from).unwrap_or(1) } + } + + fn validate(self) -> Result { + if self.memory_limit < MAX_DECODED_BLOCK { + return Err(Error::InvalidConfiguration(format!("memory limit must be at least {MAX_DECODED_BLOCK} bytes"))); + } + Ok(self) + } +} + +#[derive(Clone, Debug)] +enum Marker { + Block(BlockCandidate), + End(EndCandidate), +} + +impl Marker { + fn bit_offset(&self) -> u64 { + match self { + Self::Block(block) => block.bit_offset, + Self::End(end) => end.bit_offset, + } + } +} + +pub fn decompress(data: &[u8], options: DecodeOptions) -> Result> { + let options = options.validate()?; + if options.resolved_threads() == 1 { + let mut output = Vec::new(); + decoder::decode_serial(data, &mut output)?; + return Ok(output); + } + let mut output = Vec::new(); + decompress_to_writer(data, &mut output, options)?; + Ok(output) +} + +/// Decode to a streaming output. A one-thread request uses the same pure-Rust +/// block codec without the indexing/speculation overhead. +pub fn decompress_to_writer(data: &[u8], output: &mut impl Write, options: DecodeOptions) -> Result<()> { + let options = options.validate()?; + if options.resolved_threads() == 1 { + return decoder::decode_serial(data, output); + } + decode_to_writer(data, output, options).map(|_| ()) +} + +pub fn build_index(data: &[u8], options: DecodeOptions) -> Result { + decode_to_writer(data, &mut std::io::sink(), options) +} + +/// Decode a complete bzip2 input, validate every CRC, and build its block index. +pub fn decode_to_writer(data: &[u8], output: &mut impl Write, options: DecodeOptions) -> Result { + let options = options.validate()?; + let threads = options.resolved_threads(); + let pool = thread_pool(threads)?; + let scanned = scan_with_pool(data, pool.as_deref())?; + let mut markers: Vec<_> = scanned.blocks.into_iter().map(Marker::Block).collect(); + markers.extend(scanned.stream_ends.into_iter().map(Marker::End)); + markers.sort_unstable_by_key(Marker::bit_offset); + markers.dedup_by_key(|marker| marker.bit_offset()); + + if markers.len() > data.len() / 16 + 64 { + return Err(Error::InvalidConfiguration("input contains too many speculative markers".into())); + } + + let mut blocks = Vec::new(); + let mut streams = Vec::new(); + let mut decoded_offset = 0_u64; + let mut header_byte = 0_u64; + + while header_byte < data.len() as u64 { + let level = parse_header(data, header_byte)?; + let stream_number = streams.len() as u64; + let first_block = blocks.len() as u64; + let stream_decoded_start = decoded_offset; + let mut combined_crc = 0_u32; + let mut current_bit = header_byte.checked_mul(8).and_then(|bit| bit.checked_add(32)).ok_or_else(offset_overflow)?; + let mut marker_index = marker_at(&markers, current_bit)?; + let max_block = (usize::from(level) * 100_000 / 5 * 259 + 4).max(1); + let batch_size = (options.memory_limit / max_block).max(1).min(threads.saturating_mul(2).max(1)); + let mut ready: HashMap>> = HashMap::new(); + + loop { + match &markers[marker_index] { + Marker::End(end) => { + if end.expected_stream_crc != combined_crc { + return Err(Error::Decode { bit_offset: end.bit_offset, source: DecodeError::CrcMismatch }); + } + let after_eos = end.bit_offset.checked_add(80).ok_or_else(offset_overflow)?; + header_byte = after_eos.checked_add(7).ok_or_else(offset_overflow)? / 8; + streams.push(StreamIndex { + compressed_header_byte: current_stream_header(current_bit, first_block, &blocks, header_byte), + block_size_100k: level, + first_block, + block_count: blocks.len() as u64 - first_block, + decoded_start: stream_decoded_start, + decoded_len: decoded_offset - stream_decoded_start, + eos_bit: end.bit_offset, + expected_stream_crc: end.expected_stream_crc, + }); + break; + } + Marker::Block(block) => { + if ready.is_empty() { + ready = decode_batch(data, &markers, marker_index, batch_size, level, pool.as_deref()); + } + let mut end_index = marker_index + 1; + let decoded = match ready.remove(&marker_index) { + Some(Ok(decoded)) => decoded, + Some(Err(first_error)) => { + ready.clear(); + match retry_merged(data, &markers, marker_index, level) { + Ok((decoded, found_end)) => { + end_index = found_end; + decoded + } + Err(_) => return Err(first_error), + } + } + None => return Err(required_marker(current_bit)), + }; + output.write_all(&decoded)?; + let decoded_len = decoded.len() as u64; + blocks.push(BlockIndex { + compressed_start_bit: block.bit_offset, + compressed_end_bit: markers[end_index].bit_offset(), + decoded_start: decoded_offset, + decoded_len, + expected_crc: block.expected_crc, + stream: stream_number, + }); + decoded_offset = decoded_offset.checked_add(decoded_len).ok_or_else(offset_overflow)?; + combined_crc = combine_stream_crc(combined_crc, block.expected_crc); + current_bit = markers[end_index].bit_offset(); + marker_index = end_index; + ready.retain(|&index, _| index >= marker_index); + } + } + } + if header_byte == data.len() as u64 { + break; + } + if header_byte > data.len() as u64 { + return Err(Error::Decode { bit_offset: data.len() as u64 * 8, source: DecodeError::Truncated }); + } + } + + output.flush()?; + Ok(Index::new(data, decoded_offset, streams, blocks)) +} + +fn decode_batch(data: &[u8], markers: &[Marker], start: usize, limit: usize, level: u8, pool: Option<&ThreadPool>) -> HashMap>> { + let end = (start + limit).min(markers.len().saturating_sub(1)); + let jobs: Vec<_> = (start..end) + .take_while(|&index| matches!(markers[index], Marker::Block(_))) + .map(|index| { + let Marker::Block(block) = &markers[index] else { unreachable!() }; + (index, block.bit_offset, markers[index + 1].bit_offset(), block.expected_crc) + }) + .collect(); + let decode = || jobs.par_iter().map(|&(index, start_bit, end_bit, crc)| (index, decode_block(data, start_bit, end_bit, level, crc))).collect(); + match pool { + Some(pool) => pool.install(decode), + None => jobs.into_iter().map(|(index, start_bit, end_bit, crc)| (index, decode_block(data, start_bit, end_bit, level, crc))).collect(), + } +} + +fn retry_merged(data: &[u8], markers: &[Marker], start: usize, level: u8) -> Result<(Vec, usize)> { + let Marker::Block(block) = &markers[start] else { return Err(required_marker(markers[start].bit_offset())) }; + let mut last_error = None; + for (end, marker) in markers.iter().enumerate().skip(start + 2) { + match decode_block(data, block.bit_offset, marker.bit_offset(), level, block.expected_crc) { + Ok(decoded) => return Ok((decoded, end)), + Err(error) => last_error = Some(error), + } + } + Err(last_error.unwrap_or_else(|| required_marker(block.bit_offset))) +} + +fn thread_pool(threads: usize) -> Result>> { + if threads <= 1 { + return Ok(None); + } + ThreadPoolBuilder::new() + .num_threads(threads) + .thread_name(|number| format!("fastbz2-{number}")) + .build() + .map(Arc::new) + .map(Some) + .map_err(|error| Error::InvalidConfiguration(error.to_string())) +} + +fn marker_at(markers: &[Marker], bit_offset: u64) -> Result { + markers.binary_search_by_key(&bit_offset, Marker::bit_offset).map_err(|_| required_marker(bit_offset)) +} + +fn parse_header(data: &[u8], byte_offset: u64) -> Result { + let offset = usize::try_from(byte_offset).map_err(|_| offset_overflow())?; + let Some(header) = data.get(offset..offset.saturating_add(4)) else { + return Err(Error::Decode { bit_offset: byte_offset.saturating_mul(8), source: DecodeError::Truncated }); + }; + if &header[..3] != b"BZh" { + return Err(Error::Decode { bit_offset: byte_offset * 8, source: DecodeError::InvalidMagic }); + } + if !(b'1'..=b'9').contains(&header[3]) { + return Err(Error::Decode { bit_offset: byte_offset * 8 + 24, source: DecodeError::InvalidLevel }); + } + Ok(header[3] - b'0') +} + +fn current_stream_header(current_bit: u64, first_block: u64, blocks: &[BlockIndex], next_header: u64) -> u64 { + if let Some(first) = blocks.get(first_block as usize) { + (first.compressed_start_bit - 32) / 8 + } else { + // Empty streams have no block from which to derive the header. `current_bit` + // is their EOS position, exactly 32 bits after the header. + let candidate = current_bit.saturating_sub(32) / 8; + candidate.min(next_header) + } +} + +fn required_marker(bit_offset: u64) -> Error { + Error::Decode { bit_offset, source: DecodeError::InvalidMagic } +} + +fn offset_overflow() -> Error { + Error::InvalidConfiguration("offset arithmetic overflow".into()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crabz2::{Level, compress}; + + fn patterned(size: usize) -> Vec { + (0..size).map(|index| ((index * 37 + index / 251) & 255) as u8).collect() + } + + #[test] + fn decodes_multiple_blocks_at_every_thread_setting() { + let plain = patterned(350_000); + let compressed = compress(&plain, Level::FASTEST); + for threads in [1, 2, 4, 0] { + let options = DecodeOptions { threads, ..DecodeOptions::default() }; + assert_eq!(decompress(&compressed, options).unwrap(), plain); + } + } + + #[test] + fn validates_concatenated_streams_and_indexes_them() { + let first = patterned(180_000); + let second = patterned(70_000); + let mut compressed = compress(&first, Level::FASTEST); + compressed.extend_from_slice(&compress(&second, Level::BEST)); + let mut expected = first; + expected.extend_from_slice(&second); + + let mut output = Vec::new(); + let index = decode_to_writer(&compressed, &mut output, DecodeOptions::default()).unwrap(); + assert_eq!(output, expected); + assert_eq!(index.streams.len(), 2); + assert_eq!(index.decoded_len, expected.len() as u64); + assert!(index.blocks.len() >= 3); + } + + #[test] + fn rejects_stream_crc_corruption() { + let mut compressed = compress(b"integrity matters", Level::BEST); + let last = compressed.len() - 2; + compressed[last] ^= 1; + assert!(matches!(decompress(&compressed, DecodeOptions::default()), Err(Error::Decode { .. }))); + } +} diff --git a/src/decoder.rs b/src/decoder.rs new file mode 100644 index 0000000..fc5b2e2 --- /dev/null +++ b/src/decoder.rs @@ -0,0 +1,444 @@ +use std::io::Write; + +use crate::{DecodeError, Error, Result, bz2_crc32, combine_stream_crc}; + +const BLOCK_MAGIC: u64 = 0x3141_5926_5359; +const END_MAGIC: u64 = 0x1772_4538_5090; +const MAX_CODE_LEN: usize = 20; +const GROUP_SIZE: usize = 50; +const LUT_BITS: u8 = 12; +const LUT_SIZE: usize = 1 << LUT_BITS; + +struct Bits<'a> { + data: &'a [u8], + bit: usize, +} + +impl<'a> Bits<'a> { + fn at(data: &'a [u8], bit: u64) -> Result { + let bit = usize::try_from(bit).map_err(|_| Error::Decode { bit_offset: u64::MAX, source: DecodeError::Truncated })?; + if bit > data.len().saturating_mul(8) { + return Err(Error::Decode { bit_offset: bit as u64, source: DecodeError::Truncated }); + } + Ok(Self { data, bit }) + } + + #[inline] + fn position(&self) -> u64 { + self.bit as u64 + } + + #[inline] + fn remaining(&self) -> usize { + self.data.len().saturating_mul(8).saturating_sub(self.bit) + } + + #[inline] + fn peek(&self, count: u8) -> Result { + let count = usize::from(count); + if count > self.remaining() { + return Err(Error::Decode { bit_offset: self.position(), source: DecodeError::Truncated }); + } + let byte = self.bit >> 3; + let offset = self.bit & 7; + if byte + 8 <= self.data.len() { + let word = u64::from_be_bytes(self.data[byte..byte + 8].try_into().unwrap()); + return Ok(((word << offset) >> (64 - count)) as u32); + } + let stop = (self.bit + count).div_ceil(8); + let mut word = 0_u64; + for &value in &self.data[byte..stop] { + word = (word << 8) | u64::from(value); + } + let available = (stop - byte) * 8; + Ok(((word >> (available - offset - count)) & ((1_u64 << count) - 1)) as u32) + } + + #[inline] + fn read(&mut self, count: u8) -> Result { + if count == 0 { + return Ok(0); + } + let value = self.peek(count)?; + self.bit += usize::from(count); + Ok(value) + } + + #[inline] + fn bit(&mut self) -> Result { + Ok(self.read(1)? != 0) + } + + #[inline] + fn skip(&mut self, count: u8) { + self.bit += usize::from(count); + } + + #[inline] + fn magic(&mut self) -> Result { + Ok((u64::from(self.read(24)?) << 24) | u64::from(self.read(24)?)) + } + + fn align_byte(&mut self) { + self.bit = (self.bit + 7) & !7; + } +} + +struct Huffman { + min_len: u8, + max_len: u8, + limit: [i32; MAX_CODE_LEN + 1], + base: [i32; MAX_CODE_LEN + 1], + symbols: Vec, + lut: Box<[u32; LUT_SIZE]>, +} + +impl Huffman { + fn build(lengths: &[u8], bit_offset: u64) -> Result { + let min_len = *lengths.iter().min().ok_or_else(|| decode_error(bit_offset, DecodeError::InvalidHuffman))?; + let max_len = *lengths.iter().max().unwrap(); + if min_len == 0 || usize::from(max_len) > MAX_CODE_LEN { + return Err(decode_error(bit_offset, DecodeError::InvalidHuffman)); + } + + let mut counts = [0_u32; MAX_CODE_LEN + 1]; + for &length in lengths { + counts[usize::from(length)] += 1; + } + let mut next_code = [0_u32; MAX_CODE_LEN + 1]; + let mut code = 0_u32; + for length in 1..=MAX_CODE_LEN { + code = (code + counts[length - 1]) << 1; + next_code[length] = code; + if code + counts[length] > 1_u32 << length { + return Err(decode_error(bit_offset, DecodeError::InvalidHuffman)); + } + } + + let mut lut = Box::new([0_u32; LUT_SIZE]); + for (symbol, &length) in lengths.iter().enumerate() { + let canonical = next_code[usize::from(length)]; + next_code[usize::from(length)] += 1; + if length <= LUT_BITS { + let fill = 1_usize << (LUT_BITS - length); + let start = canonical as usize * fill; + let entry = (u32::from(length) << 16) | symbol as u32; + lut[start..start + fill].fill(entry); + } + } + + let mut symbols = Vec::with_capacity(lengths.len()); + for length in min_len..=max_len { + symbols.extend(lengths.iter().enumerate().filter_map(|(symbol, &value)| (value == length).then_some(symbol as u16))); + } + + let mut base = [0_i32; MAX_CODE_LEN + 1]; + for &length in lengths { + if usize::from(length) == MAX_CODE_LEN { + continue; + } + base[usize::from(length) + 1] += 1; + } + for index in 1..base.len() { + base[index] += base[index - 1]; + } + let mut limit = [0_i32; MAX_CODE_LEN + 1]; + let mut value = 0_i32; + for length in usize::from(min_len)..=usize::from(max_len) { + value += counts[length] as i32; + limit[length] = value - 1; + value <<= 1; + } + for length in usize::from(min_len) + 1..=usize::from(max_len) { + base[length] = ((limit[length - 1] + 1) << 1) - base[length]; + } + Ok(Self { min_len, max_len, limit, base, symbols, lut }) + } + + #[inline] + fn decode(&self, bits: &mut Bits<'_>) -> Result { + if bits.remaining() >= usize::from(LUT_BITS) { + let entry = self.lut[bits.peek(LUT_BITS)? as usize]; + let length = (entry >> 16) as u8; + if length != 0 { + bits.skip(length); + return Ok((entry & 0xffff) as usize); + } + } + + let mut length = self.min_len; + let mut code = bits.read(length)? as i32; + loop { + if code <= self.limit[usize::from(length)] { + let index = code - self.base[usize::from(length)]; + if index >= 0 + && let Some(&symbol) = self.symbols.get(index as usize) + { + return Ok(usize::from(symbol)); + } + return Err(decode_error(bits.position(), DecodeError::InvalidHuffman)); + } + if length == self.max_len { + return Err(decode_error(bits.position(), DecodeError::InvalidHuffman)); + } + length += 1; + code = (code << 1) | bits.read(1)? as i32; + } + } +} + +struct Decoder { + tt: Vec, +} + +impl Decoder { + fn new() -> Self { + Self { tt: Vec::new() } + } + + fn block(&mut self, bits: &mut Bits<'_>, level: u8, expected_crc: Option) -> Result<(Vec, u32)> { + let block_offset = bits.position().saturating_sub(48); + let stored_crc = bits.read(32)?; + if expected_crc.is_some_and(|expected| expected != stored_crc) { + return Err(decode_error(block_offset, DecodeError::InvalidBlock)); + } + if bits.bit()? { + return Err(decode_error(block_offset, DecodeError::RandomizedBlock)); + } + let origin = bits.read(24)? as usize; + + let mut used = [false; 256]; + let groups = bits.read(16)?; + for group in 0..16 { + if groups & (1 << (15 - group)) != 0 { + let values = bits.read(16)?; + for value in 0..16 { + used[group * 16 + value] = values & (1 << (15 - value)) != 0; + } + } + } + let alphabet: Vec = (0..256).filter(|&value| used[value]).map(|value| value as u8).collect(); + if alphabet.is_empty() { + return Err(decode_error(block_offset, DecodeError::InvalidBlock)); + } + let alpha_size = alphabet.len() + 2; + let eob = alpha_size - 1; + + let table_count = bits.read(3)? as usize; + if !(2..=6).contains(&table_count) { + return Err(decode_error(bits.position(), DecodeError::InvalidHuffman)); + } + let selector_count = bits.read(15)? as usize; + if selector_count == 0 { + return Err(decode_error(bits.position(), DecodeError::InvalidBlock)); + } + let mut selector_mtf: Vec = (0..table_count as u8).collect(); + let mut selectors = Vec::with_capacity(selector_count); + for _ in 0..selector_count { + let mut index = 0; + while bits.bit()? { + index += 1; + if index >= table_count { + return Err(decode_error(bits.position(), DecodeError::InvalidBlock)); + } + } + let selected = selector_mtf[index]; + selector_mtf.copy_within(0..index, 1); + selector_mtf[0] = selected; + selectors.push(selected as usize); + } + + let mut tables = Vec::with_capacity(table_count); + for _ in 0..table_count { + let mut current = bits.read(5)? as i32; + let mut lengths = vec![0_u8; alpha_size]; + for length in &mut lengths { + loop { + if !(1..=MAX_CODE_LEN as i32).contains(¤t) { + return Err(decode_error(bits.position(), DecodeError::InvalidHuffman)); + } + if !bits.bit()? { + break; + } + current += if bits.bit()? { -1 } else { 1 }; + } + *length = current as u8; + } + tables.push(Huffman::build(&lengths, bits.position())?); + } + + let block_size = usize::from(level) * 100_000; + self.tt.clear(); + self.tt.reserve(block_size.saturating_sub(self.tt.capacity())); + let mut counts = [0_u32; 257]; + let mut mtf = alphabet; + let mut selector = 0; + let mut group_left = 0; + let mut table = 0; + let mut run = 0_u64; + let mut run_bit = 0_u32; + + loop { + if group_left == 0 { + table = *selectors.get(selector).ok_or_else(|| decode_error(bits.position(), DecodeError::InvalidBlock))?; + selector += 1; + group_left = GROUP_SIZE; + } + group_left -= 1; + let symbol = tables[table].decode(bits)?; + if symbol <= 1 { + run += (symbol as u64 + 1) << run_bit; + run_bit += 1; + if run_bit >= 32 || run > block_size as u64 { + return Err(decode_error(bits.position(), DecodeError::BlockOverflow)); + } + continue; + } + if run != 0 { + let byte = mtf[0]; + let run = run as usize; + if self.tt.len() + run > block_size { + return Err(decode_error(bits.position(), DecodeError::BlockOverflow)); + } + self.tt.resize(self.tt.len() + run, u32::from(byte)); + counts[usize::from(byte) + 1] += run as u32; + run_bit = 0; + } + run = 0; + if symbol == eob { + break; + } + let index = symbol - 1; + if index >= mtf.len() || self.tt.len() == block_size { + return Err(decode_error(bits.position(), DecodeError::InvalidBlock)); + } + let byte = mtf[index]; + mtf.copy_within(0..index, 1); + mtf[0] = byte; + self.tt.push(u32::from(byte)); + counts[usize::from(byte) + 1] += 1; + } + + let block_len = self.tt.len(); + if block_len == 0 || origin >= block_len { + return Err(decode_error(block_offset, DecodeError::InvalidBlock)); + } + for index in 1..counts.len() { + counts[index] += counts[index - 1]; + } + for index in 0..block_len { + let byte = (self.tt[index] & 0xff) as usize; + let target = counts[byte] as usize; + self.tt[target] |= (index as u32) << 8; + counts[byte] += 1; + } + + let max_output = block_size / 5 * 259 + 4; + let mut output = Vec::with_capacity(block_len.min(max_output)); + let mut position = self.tt[origin] >> 8; + let mut previous = None; + let mut repeated = 0_u8; + for _ in 0..block_len { + let entry = self.tt[position as usize]; + let byte = entry as u8; + position = entry >> 8; + if repeated == 4 { + let extra = usize::from(byte); + if output.len() + extra > max_output { + return Err(decode_error(block_offset, DecodeError::BlockOverflow)); + } + output.resize(output.len() + extra, previous.unwrap()); + previous = None; + repeated = 0; + } else { + if output.len() == max_output { + return Err(decode_error(block_offset, DecodeError::BlockOverflow)); + } + output.push(byte); + if previous == Some(byte) { + repeated += 1; + } else { + previous = Some(byte); + repeated = 1; + } + } + } + if bz2_crc32(&output) != stored_crc { + return Err(decode_error(block_offset, DecodeError::CrcMismatch)); + } + Ok((output, stored_crc)) + } +} + +pub(crate) fn decode_block(data: &[u8], start_bit: u64, end_bit: u64, level: u8, expected_crc: u32) -> Result> { + if !(1..=9).contains(&level) || end_bit <= start_bit { + return Err(decode_error(start_bit, DecodeError::InvalidBlock)); + } + let mut bits = Bits::at(data, start_bit)?; + if bits.magic()? != BLOCK_MAGIC { + return Err(decode_error(start_bit, DecodeError::InvalidMagic)); + } + let (output, _) = Decoder::new().block(&mut bits, level, Some(expected_crc))?; + if bits.position() != end_bit { + return Err(decode_error(bits.position(), DecodeError::InvalidBlock)); + } + Ok(output) +} + +pub(crate) fn decode_serial(data: &[u8], output: &mut impl Write) -> Result<()> { + let mut bits = Bits::at(data, 0)?; + let mut decoder = Decoder::new(); + while bits.remaining() != 0 { + bits.align_byte(); + if bits.remaining() < 32 { + return Err(decode_error(bits.position(), DecodeError::Truncated)); + } + if bits.read(8)? != u32::from(b'B') || bits.read(8)? != u32::from(b'Z') || bits.read(8)? != u32::from(b'h') { + return Err(decode_error(bits.position().saturating_sub(24), DecodeError::InvalidMagic)); + } + let level = bits.read(8)? as u8; + if !(b'1'..=b'9').contains(&level) { + return Err(decode_error(bits.position().saturating_sub(8), DecodeError::InvalidLevel)); + } + let level = level - b'0'; + let mut combined_crc = 0_u32; + loop { + let marker_offset = bits.position(); + match bits.magic()? { + BLOCK_MAGIC => { + let (block, crc) = decoder.block(&mut bits, level, None)?; + output.write_all(&block)?; + combined_crc = combine_stream_crc(combined_crc, crc); + } + END_MAGIC => { + if bits.read(32)? != combined_crc { + return Err(decode_error(marker_offset, DecodeError::CrcMismatch)); + } + break; + } + _ => return Err(decode_error(marker_offset, DecodeError::InvalidMagic)), + } + } + bits.align_byte(); + } + output.flush()?; + Ok(()) +} + +fn decode_error(bit_offset: u64, source: DecodeError) -> Error { + Error::Decode { bit_offset, source } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn huffman_lut_and_fallback_decode_all_symbols() { + let lengths = [2, 2, 3, 3, 3, 3]; + let table = Huffman::build(&lengths, 0).unwrap(); + let data = [0b0001_1001, 0b0111_0111]; + let mut bits = Bits::at(&data, 0).unwrap(); + assert_eq!((0..6).map(|_| table.decode(&mut bits).unwrap()).collect::>(), [0, 1, 2, 3, 4, 5]); + } +} diff --git a/src/error.rs b/src/error.rs index 35049ec..bd62af1 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,13 +1,46 @@ -use std::{error, fmt}; +use std::{error, fmt, io}; pub type Result = std::result::Result; -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DecodeError { + InvalidMagic, + InvalidLevel, + Truncated, + CrcMismatch, + RandomizedBlock, + InvalidHuffman, + InvalidBlock, + BlockOverflow, +} + +impl fmt::Display for DecodeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::InvalidMagic => "invalid bzip2 magic", + Self::InvalidLevel => "invalid bzip2 block size", + Self::Truncated => "unexpected end of bzip2 stream", + Self::CrcMismatch => "bzip2 CRC mismatch", + Self::RandomizedBlock => "legacy randomized bzip2 block not supported", + Self::InvalidHuffman => "invalid bzip2 Huffman table", + Self::InvalidBlock => "invalid bzip2 block structure", + Self::BlockOverflow => "bzip2 block exceeds its declared size", + }) + } +} + +impl error::Error for DecodeError {} + +#[derive(Debug)] pub enum Error { InvalidBitCount(u8), InvalidBitOffset { bit_offset: u64, len_bits: u64 }, UnexpectedEof { bit_offset: u64, requested: u64, remaining: u64 }, InvalidStreamHeader, + Decode { bit_offset: u64, source: DecodeError }, + InvalidIndex(String), + InvalidConfiguration(String), + Io(io::Error), } impl fmt::Display for Error { @@ -21,8 +54,26 @@ impl fmt::Display for Error { write!(f, "unexpected end of input at bit {bit_offset}: requested {requested} bits, {remaining} remain") } Self::InvalidStreamHeader => write!(f, "input does not start with a bzip2 BZh1-BZh9 header"), + Self::Decode { bit_offset, source } => write!(f, "bzip2 decode error at bit {bit_offset}: {source}"), + Self::InvalidIndex(message) => write!(f, "invalid fastbz2 index: {message}"), + Self::InvalidConfiguration(message) => write!(f, "invalid configuration: {message}"), + Self::Io(source) => source.fmt(f), } } } -impl error::Error for Error {} +impl error::Error for Error { + fn source(&self) -> Option<&(dyn error::Error + 'static)> { + match self { + Self::Decode { source, .. } => Some(source), + Self::Io(source) => Some(source), + _ => None, + } + } +} + +impl From for Error { + fn from(source: io::Error) -> Self { + Self::Io(source) + } +} diff --git a/src/format.rs b/src/format.rs index 13498ba..e1f4608 100644 --- a/src/format.rs +++ b/src/format.rs @@ -1,10 +1,14 @@ use crate::{BitReader, Error, Result}; +use rayon::{ThreadPool, prelude::*}; pub const BLOCK_MAGIC: u64 = 0x3141_5926_5359; pub const END_MAGIC: u64 = 0x1772_4538_5090; const MAGIC_BITS: u8 = 48; const MAGIC_MASK: u64 = (1_u64 << MAGIC_BITS) - 1; const WINDOW_MASK: u64 = (1_u64 << 56) - 1; +const SCAN_CHUNK: usize = 1 << 20; +const BLOCK_PREFIX: [u8; 256] = prefix_table(BLOCK_MAGIC); +const END_PREFIX: [u8; 256] = prefix_table(END_MAGIC); #[derive(Clone, Debug, PartialEq, Eq)] pub struct StreamHeaderCandidate { @@ -42,24 +46,44 @@ pub fn scan(data: &[u8]) -> Result { if !is_stream_header(data, 0) { return Err(Error::InvalidStreamHeader); } + Ok(scan_range(data, 0, data.len())) +} + +pub(crate) fn scan_with_pool(data: &[u8], pool: Option<&ThreadPool>) -> Result { + if !is_stream_header(data, 0) { + return Err(Error::InvalidStreamHeader); + } + let Some(pool) = pool.filter(|_| data.len() > SCAN_CHUNK) else { return Ok(scan_range(data, 0, data.len())) }; + let chunks = data.len().div_ceil(SCAN_CHUNK); + let partial: Vec<_> = + pool.install(|| (0..chunks).into_par_iter().map(|chunk| scan_range(data, chunk * SCAN_CHUNK, ((chunk + 1) * SCAN_CHUNK).min(data.len()))).collect()); + let mut result = ScanResult { streams: Vec::new(), blocks: Vec::new(), stream_ends: Vec::new() }; + for mut chunk in partial { + result.streams.append(&mut chunk.streams); + result.blocks.append(&mut chunk.blocks); + result.stream_ends.append(&mut chunk.stream_ends); + } + Ok(result) +} - let streams = (0..=data.len().saturating_sub(4)) +fn scan_range(data: &[u8], start: usize, end: usize) -> ScanResult { + let streams = (start..end) .filter(|&offset| is_stream_header(data, offset)) .map(|offset| StreamHeaderCandidate { byte_offset: offset as u64, block_size_100k: data[offset + 3] - b'0' }) .collect(); let mut blocks = Vec::new(); let mut stream_ends = Vec::new(); - if data.len() < 7 { - return Ok(ScanResult { streams, blocks, stream_ends }); + if data.len() < 7 || start >= end { + return ScanResult { streams, blocks, stream_ends }; } - // A 56-bit rolling window contains all eight 48-bit candidates beginning - // in one byte. The simple fixed-width inner loop is intentionally friendly - // to unrolling and auto-vectorisation on both x86-64 and ARM64. - let mut window = data[..7].iter().fold(0_u64, |word, &byte| (word << 8) | u64::from(byte)); - for byte_offset in 0..=data.len() - 7 { - for shift in 0..8_u32 { + let mut window = (start..start + 7).fold(0_u64, |word, offset| (word << 8) | u64::from(byte_at(data, offset))); + for byte_offset in start..end { + let mut shifts = BLOCK_PREFIX[(window >> 48) as usize] | END_PREFIX[(window >> 48) as usize]; + while shifts != 0 { + let shift = shifts.trailing_zeros(); + shifts &= shifts - 1; let marker = (window >> (8 - shift)) & MAGIC_MASK; let bit_offset = byte_offset as u64 * 8 + u64::from(shift); if marker == BLOCK_MAGIC { @@ -72,12 +96,32 @@ pub fn scan(data: &[u8]) -> Result { stream_ends.push(end); } } - if let Some(&next) = data.get(byte_offset + 7) { - window = ((window << 8) & WINDOW_MASK) | u64::from(next); + window = ((window << 8) & WINDOW_MASK) | u64::from(byte_at(data, byte_offset + 7)); + } + + ScanResult { streams, blocks, stream_ends } +} + +const fn prefix_table(magic: u64) -> [u8; 256] { + let mut table = [0_u8; 256]; + let mut byte = 0_usize; + while byte < 256 { + let mut shift = 0_u32; + while shift < 8 { + let wanted = (magic >> (40 + shift)) as u8; + let kept = ((1_u16 << (8 - shift)) - 1) as u8; + if byte as u8 & kept == wanted { + table[byte] |= 1 << shift; + } + shift += 1; } + byte += 1; } + table +} - Ok(ScanResult { streams, blocks, stream_ends }) +fn byte_at(data: &[u8], offset: usize) -> u8 { + data.get(offset).copied().unwrap_or(0) } fn is_stream_header(data: &[u8], offset: usize) -> bool { @@ -137,6 +181,6 @@ mod tests { #[test] fn rejects_non_bzip_input() { - assert_eq!(scan(b"not bzip2"), Err(Error::InvalidStreamHeader)); + assert!(matches!(scan(b"not bzip2"), Err(Error::InvalidStreamHeader))); } } diff --git a/src/index.rs b/src/index.rs new file mode 100644 index 0000000..74f5e0f --- /dev/null +++ b/src/index.rs @@ -0,0 +1,264 @@ +use std::{fs, path::Path}; + +use crate::{Error, Result}; + +const MAGIC: &[u8; 8] = b"FBZ2IDX\0"; +const VERSION: u32 = 1; +const CHECKSUM_LEN: usize = 32; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BlockIndex { + pub compressed_start_bit: u64, + pub compressed_end_bit: u64, + pub decoded_start: u64, + pub decoded_len: u64, + pub expected_crc: u32, + pub stream: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StreamIndex { + pub compressed_header_byte: u64, + pub block_size_100k: u8, + pub first_block: u64, + pub block_count: u64, + pub decoded_start: u64, + pub decoded_len: u64, + pub eos_bit: u64, + pub expected_stream_crc: u32, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Index { + pub source_len: u64, + pub source_hash: [u8; 32], + pub decoded_len: u64, + pub streams: Vec, + pub blocks: Vec, +} + +impl Index { + pub(crate) fn new(source: &[u8], decoded_len: u64, streams: Vec, blocks: Vec) -> Self { + Self { source_len: source.len() as u64, source_hash: *blake3::hash(source).as_bytes(), decoded_len, streams, blocks } + } + + pub fn to_bytes(&self) -> Vec { + let mut out = Vec::with_capacity(76 + self.streams.len() * 53 + self.blocks.len() * 44 + CHECKSUM_LEN); + out.extend_from_slice(MAGIC); + put_u32(&mut out, VERSION); + put_u64(&mut out, self.source_len); + out.extend_from_slice(&self.source_hash); + put_u64(&mut out, self.decoded_len); + put_u64(&mut out, self.streams.len() as u64); + put_u64(&mut out, self.blocks.len() as u64); + for stream in &self.streams { + put_u64(&mut out, stream.compressed_header_byte); + out.push(stream.block_size_100k); + put_u64(&mut out, stream.first_block); + put_u64(&mut out, stream.block_count); + put_u64(&mut out, stream.decoded_start); + put_u64(&mut out, stream.decoded_len); + put_u64(&mut out, stream.eos_bit); + put_u32(&mut out, stream.expected_stream_crc); + } + for block in &self.blocks { + put_u64(&mut out, block.compressed_start_bit); + put_u64(&mut out, block.compressed_end_bit); + put_u64(&mut out, block.decoded_start); + put_u64(&mut out, block.decoded_len); + put_u32(&mut out, block.expected_crc); + put_u64(&mut out, block.stream); + } + let checksum = blake3::hash(&out); + out.extend_from_slice(checksum.as_bytes()); + out + } + + pub fn from_bytes(encoded: &[u8], source: &[u8]) -> Result { + if encoded.len() < CHECKSUM_LEN { + return Err(invalid("truncated header")); + } + let (payload, checksum) = encoded.split_at(encoded.len() - CHECKSUM_LEN); + if blake3::hash(payload).as_bytes() != checksum { + return Err(invalid("payload checksum mismatch")); + } + let mut reader = IndexReader::new(payload); + if reader.take(8)? != MAGIC { + return Err(invalid("bad magic")); + } + if reader.u32()? != VERSION { + return Err(invalid("unsupported version")); + } + let source_len = reader.u64()?; + let source_hash: [u8; 32] = reader.take(32)?.try_into().unwrap(); + let decoded_len = reader.u64()?; + let stream_count = reader.usize("stream count")?; + let block_count = reader.usize("block count")?; + if source_len != source.len() as u64 || source_hash != *blake3::hash(source).as_bytes() { + return Err(invalid("source identity mismatch")); + } + let required = stream_count + .checked_mul(53) + .and_then(|size| block_count.checked_mul(44).and_then(|blocks| size.checked_add(blocks))) + .ok_or_else(|| invalid("record counts overflow"))?; + if reader.remaining() != required { + return Err(invalid("record counts do not match payload length")); + } + + let mut streams = Vec::with_capacity(stream_count); + for _ in 0..stream_count { + streams.push(StreamIndex { + compressed_header_byte: reader.u64()?, + block_size_100k: reader.byte()?, + first_block: reader.u64()?, + block_count: reader.u64()?, + decoded_start: reader.u64()?, + decoded_len: reader.u64()?, + eos_bit: reader.u64()?, + expected_stream_crc: reader.u32()?, + }); + } + let mut blocks = Vec::with_capacity(block_count); + for _ in 0..block_count { + blocks.push(BlockIndex { + compressed_start_bit: reader.u64()?, + compressed_end_bit: reader.u64()?, + decoded_start: reader.u64()?, + decoded_len: reader.u64()?, + expected_crc: reader.u32()?, + stream: reader.u64()?, + }); + } + let index = Self { source_len, source_hash, decoded_len, streams, blocks }; + index.validate()?; + Ok(index) + } + + pub fn save(&self, path: impl AsRef) -> Result<()> { + fs::write(path, self.to_bytes()).map_err(Error::from) + } + + pub fn load(path: impl AsRef, source: &[u8]) -> Result { + Self::from_bytes(&fs::read(path)?, source) + } + + fn validate(&self) -> Result<()> { + let source_bits = self.source_len.checked_mul(8).ok_or_else(|| invalid("source length overflow"))?; + let mut decoded = 0_u64; + for (number, block) in self.blocks.iter().enumerate() { + if block.decoded_start != decoded || block.decoded_len == 0 { + return Err(invalid("block decoded offsets are not contiguous")); + } + if block.compressed_start_bit >= block.compressed_end_bit || block.compressed_end_bit > source_bits { + return Err(invalid("block compressed range is invalid")); + } + if block.stream as usize >= self.streams.len() { + return Err(invalid("block stream number is out of range")); + } + decoded = decoded.checked_add(block.decoded_len).ok_or_else(|| invalid("decoded offset overflow"))?; + if number > 0 && self.blocks[number - 1].compressed_start_bit >= block.compressed_start_bit { + return Err(invalid("block compressed offsets are not increasing")); + } + } + if decoded != self.decoded_len { + return Err(invalid("decoded size does not match block records")); + } + let mut first_block = 0_u64; + let mut stream_decoded = 0_u64; + for (number, stream) in self.streams.iter().enumerate() { + if !(1..=9).contains(&stream.block_size_100k) + || stream.first_block != first_block + || stream.decoded_start != stream_decoded + || stream.eos_bit > source_bits + { + return Err(invalid("stream record is inconsistent")); + } + let end = stream.first_block.checked_add(stream.block_count).ok_or_else(|| invalid("stream block count overflow"))?; + if end as usize > self.blocks.len() { + return Err(invalid("stream block range is out of bounds")); + } + for block in &self.blocks[stream.first_block as usize..end as usize] { + if block.stream != number as u64 { + return Err(invalid("block belongs to the wrong stream")); + } + } + first_block = end; + stream_decoded = stream_decoded.checked_add(stream.decoded_len).ok_or_else(|| invalid("stream size overflow"))?; + } + if first_block as usize != self.blocks.len() || stream_decoded != self.decoded_len { + return Err(invalid("stream records do not cover decoded data")); + } + Ok(()) + } +} + +fn invalid(message: impl Into) -> Error { + Error::InvalidIndex(message.into()) +} + +fn put_u32(out: &mut Vec, value: u32) { + out.extend_from_slice(&value.to_le_bytes()); +} + +fn put_u64(out: &mut Vec, value: u64) { + out.extend_from_slice(&value.to_le_bytes()); +} + +struct IndexReader<'a> { + data: &'a [u8], + pos: usize, +} + +impl<'a> IndexReader<'a> { + fn new(data: &'a [u8]) -> Self { + Self { data, pos: 0 } + } + + fn remaining(&self) -> usize { + self.data.len() - self.pos + } + + fn take(&mut self, count: usize) -> Result<&'a [u8]> { + let end = self.pos.checked_add(count).ok_or_else(|| invalid("offset overflow"))?; + let value = self.data.get(self.pos..end).ok_or_else(|| invalid("truncated payload"))?; + self.pos = end; + Ok(value) + } + + fn byte(&mut self) -> Result { + Ok(self.take(1)?[0]) + } + + fn u32(&mut self) -> Result { + Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap())) + } + + fn u64(&mut self) -> Result { + Ok(u64::from_le_bytes(self.take(8)?.try_into().unwrap())) + } + + fn usize(&mut self, name: &str) -> Result { + usize::try_from(self.u64()?).map_err(|_| invalid(format!("{name} does not fit this platform"))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn empty_index_round_trip_and_source_binding() { + let source = b"BZh9"; + let index = Index::new(source, 0, Vec::new(), Vec::new()); + let encoded = index.to_bytes(); + assert_eq!(Index::from_bytes(&encoded, source).unwrap(), index); + assert!(matches!(Index::from_bytes(&encoded, b"BZh8"), Err(Error::InvalidIndex(_)))); + } + + #[test] + fn rejects_tampered_payload() { + let mut encoded = Index::new(b"BZh9", 0, Vec::new(), Vec::new()).to_bytes(); + encoded[0] ^= 1; + assert!(matches!(Index::from_bytes(&encoded, b"BZh9"), Err(Error::InvalidIndex(_)))); + } +} diff --git a/src/indexed.rs b/src/indexed.rs new file mode 100644 index 0000000..0c26ac4 --- /dev/null +++ b/src/indexed.rs @@ -0,0 +1,189 @@ +use std::{ + collections::{HashMap, VecDeque}, + io::{self, Read, Seek, SeekFrom}, + path::Path, +}; + +use crate::{DecodeOptions, Error, Index, Result, Source, build_index, decode_block}; + +pub const DEFAULT_CACHE_LIMIT: usize = 64 * 1024 * 1024; + +pub struct IndexedReader { + source: Source, + index: Index, + position: u64, + cache: BlockCache, +} + +impl IndexedReader { + pub fn open(path: impl AsRef, options: DecodeOptions) -> Result { + Self::from_source(Source::open(path)?, None, options, DEFAULT_CACHE_LIMIT) + } + + pub fn open_with_index(path: impl AsRef, index_path: impl AsRef, cache_limit: usize) -> Result { + let source = Source::open(path)?; + let index = Index::load(index_path, source.as_slice())?; + Self::from_source(source, Some(index), DecodeOptions::default(), cache_limit) + } + + pub fn from_bytes(data: Vec, options: DecodeOptions) -> Result { + Self::from_source(Source::from_bytes(data), None, options, DEFAULT_CACHE_LIMIT) + } + + pub fn from_bytes_with_index(data: Vec, encoded_index: &[u8], cache_limit: usize) -> Result { + let source = Source::from_bytes(data); + let index = Index::from_bytes(encoded_index, source.as_slice())?; + Self::from_source(source, Some(index), DecodeOptions::default(), cache_limit) + } + + pub fn from_source(source: Source, index: Option, options: DecodeOptions, cache_limit: usize) -> Result { + let index = match index { + Some(index) => index, + None => build_index(source.as_slice(), options)?, + }; + Ok(Self { source, index, position: 0, cache: BlockCache::new(cache_limit) }) + } + + pub fn index(&self) -> &Index { + &self.index + } + + pub fn size(&self) -> u64 { + self.index.decoded_len + } + + pub fn position(&self) -> u64 { + self.position + } + + pub fn save_index(&self, path: impl AsRef) -> Result<()> { + self.index.save(path) + } + + fn block_number(&self, position: u64) -> Option { + let number = self.index.blocks.partition_point(|block| block.decoded_start + block.decoded_len <= position); + (number < self.index.blocks.len()).then_some(number) + } + + fn read_block_part(&mut self, number: usize, output: &mut [u8]) -> Result { + let block = &self.index.blocks[number]; + let offset = usize::try_from(self.position - block.decoded_start) + .map_err(|_| Error::InvalidConfiguration("decoded block offset does not fit this platform".into()))?; + if let Some(cached) = self.cache.get(number) { + let count = output.len().min(cached.len() - offset); + output[..count].copy_from_slice(&cached[offset..offset + count]); + return Ok(count); + } + let stream = &self.index.streams[block.stream as usize]; + let decoded = decode_block(self.source.as_slice(), block.compressed_start_bit, block.compressed_end_bit, stream.block_size_100k, block.expected_crc)?; + if decoded.len() as u64 != block.decoded_len { + return Err(Error::InvalidIndex("decoded block length does not match index".into())); + } + let count = output.len().min(decoded.len() - offset); + output[..count].copy_from_slice(&decoded[offset..offset + count]); + self.cache.insert(number, decoded); + Ok(count) + } +} + +impl Read for IndexedReader { + fn read(&mut self, mut output: &mut [u8]) -> io::Result { + let requested = output.len(); + while !output.is_empty() && self.position < self.index.decoded_len { + let number = self.block_number(self.position).ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "index has a decoded gap"))?; + let count = self.read_block_part(number, output).map_err(io::Error::other)?; + if count == 0 { + return Err(io::Error::new(io::ErrorKind::InvalidData, "decoder made no progress")); + } + self.position += count as u64; + output = &mut output[count..]; + } + Ok(requested - output.len()) + } +} + +impl Seek for IndexedReader { + fn seek(&mut self, position: SeekFrom) -> io::Result { + let next = match position { + SeekFrom::Start(position) => i128::from(position), + SeekFrom::Current(offset) => i128::from(self.position) + i128::from(offset), + SeekFrom::End(offset) => i128::from(self.index.decoded_len) + i128::from(offset), + }; + if !(0..=i128::from(self.index.decoded_len)).contains(&next) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "seek outside decompressed data")); + } + self.position = next as u64; + Ok(self.position) + } +} + +struct BlockCache { + entries: HashMap>, + order: VecDeque, + bytes: usize, + limit: usize, +} + +impl BlockCache { + fn new(limit: usize) -> Self { + Self { entries: HashMap::new(), order: VecDeque::new(), bytes: 0, limit } + } + + fn get(&mut self, number: usize) -> Option<&Vec> { + if !self.entries.contains_key(&number) { + return None; + } + self.order.retain(|&entry| entry != number); + self.order.push_back(number); + self.entries.get(&number) + } + + fn insert(&mut self, number: usize, data: Vec) { + if data.len() > self.limit { + return; + } + while self.bytes + data.len() > self.limit { + let Some(oldest) = self.order.pop_front() else { break }; + if let Some(removed) = self.entries.remove(&oldest) { + self.bytes -= removed.len(); + } + } + self.bytes += data.len(); + self.order.push_back(number); + self.entries.insert(number, data); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crabz2::{Level, compress}; + + #[test] + fn reads_and_seeks_across_blocks() { + let plain: Vec<_> = (0..350_000).map(|index| ((index * 17 + index / 101) & 255) as u8).collect(); + let compressed = compress(&plain, Level::FASTEST); + let mut reader = IndexedReader::from_bytes(compressed, DecodeOptions { threads: 2, ..DecodeOptions::default() }).unwrap(); + assert!(reader.index().blocks.len() >= 3); + + for &(position, count) in &[(0, 17), (99_990, 40), (170_123, 8192), (349_990, 20)] { + reader.seek(SeekFrom::Start(position as u64)).unwrap(); + let mut actual = vec![0; count]; + let got = reader.read(&mut actual).unwrap(); + assert_eq!(&actual[..got], &plain[position..(position + count).min(plain.len())]); + } + assert_eq!(reader.seek(SeekFrom::End(-10)).unwrap(), plain.len() as u64 - 10); + } + + #[test] + fn loads_source_bound_index() { + let plain = b"indexed bzip2".repeat(10_000); + let compressed = compress(&plain, Level::FASTEST); + let built = IndexedReader::from_bytes(compressed.clone(), DecodeOptions::default()).unwrap(); + let encoded = built.index().to_bytes(); + let mut loaded = IndexedReader::from_bytes_with_index(compressed, &encoded, 1024 * 1024).unwrap(); + let mut actual = Vec::new(); + loaded.read_to_end(&mut actual).unwrap(); + assert_eq!(actual, plain); + } +} diff --git a/src/lib.rs b/src/lib.rs index 4f25c79..eaa07c3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,18 +1,49 @@ //! Portable bzip2 primitives and format inspection. mod bitreader; +mod block; mod crc; +mod decode; +mod decoder; mod error; mod format; +mod index; +mod indexed; +mod source; pub use bitreader::BitReader; +pub use block::{MAX_DECODED_BLOCK, MAX_ENCODED_BLOCK, decode_block}; pub use crc::{bz2_crc32, combine_stream_crc}; -pub use error::{Error, Result}; +pub use decode::{DEFAULT_MEMORY_LIMIT, DecodeOptions, build_index, decode_to_writer, decompress, decompress_to_writer}; +pub use error::{DecodeError, Error, Result}; pub use format::{BLOCK_MAGIC, BlockCandidate, END_MAGIC, EndCandidate, ScanResult, StreamHeaderCandidate, scan}; +pub use index::{BlockIndex, Index, StreamIndex}; +pub use indexed::{DEFAULT_CACHE_LIMIT, IndexedReader}; +pub use source::Source; #[cfg(feature = "python")] mod python { - use pyo3::{exceptions::PyValueError, prelude::*}; + use std::{ + io::{Read, Seek, SeekFrom}, + sync::Mutex, + }; + + use pyo3::{ + create_exception, + exceptions::{PyOSError, PyValueError}, + prelude::*, + types::PyBytes, + }; + + create_exception!(fastbz2, BadBzip2File, PyOSError); + + fn python_error(error: crate::Error) -> PyErr { + match error { + crate::Error::Io(source) => PyOSError::new_err(source.to_string()), + crate::Error::InvalidConfiguration(message) | crate::Error::InvalidIndex(message) => PyValueError::new_err(message), + error => BadBzip2File::new_err(error.to_string()), + } + } #[pyfunction(name = "_scan")] #[allow(clippy::type_complexity)] @@ -29,10 +60,124 @@ mod python { crate::bz2_crc32(data) } + #[pyfunction(name = "_decompress", signature = (data, threads=0, memory_limit=crate::DEFAULT_MEMORY_LIMIT))] + fn py_decompress(py: Python<'_>, data: &[u8], threads: usize, memory_limit: usize) -> PyResult> { + let data = data.to_vec(); + let output = py.detach(move || crate::decompress(&data, crate::DecodeOptions { threads, memory_limit })).map_err(python_error)?; + Ok(PyBytes::new(py, &output).unbind()) + } + + #[pyfunction(name = "_build_index", signature = (path, threads=0, memory_limit=crate::DEFAULT_MEMORY_LIMIT))] + fn py_build_index(py: Python<'_>, path: String, threads: usize, memory_limit: usize) -> PyResult> { + let encoded = py + .detach(move || { + let source = crate::Source::open(path)?; + Ok::<_, crate::Error>(crate::build_index(source.as_slice(), crate::DecodeOptions { threads, memory_limit })?.to_bytes()) + }) + .map_err(python_error)?; + Ok(PyBytes::new(py, &encoded).unbind()) + } + + #[pyfunction(name = "_test", signature = (path, threads=0, memory_limit=crate::DEFAULT_MEMORY_LIMIT))] + fn py_test(py: Python<'_>, path: String, threads: usize, memory_limit: usize) -> PyResult<()> { + py.detach(move || { + let source = crate::Source::open(path)?; + crate::build_index(source.as_slice(), crate::DecodeOptions { threads, memory_limit })?; + Ok::<_, crate::Error>(()) + }) + .map_err(python_error) + } + + #[pyclass(name = "_IndexedReader")] + struct PyIndexedReader { + inner: Mutex, + } + + #[pymethods] + impl PyIndexedReader { + #[staticmethod] + #[pyo3(signature = (path, threads=0, memory_limit=crate::DEFAULT_MEMORY_LIMIT, index_path=None, cache_limit=crate::DEFAULT_CACHE_LIMIT))] + fn from_path(py: Python<'_>, path: String, threads: usize, memory_limit: usize, index_path: Option, cache_limit: usize) -> PyResult { + let inner = py + .detach(move || match index_path { + Some(index_path) => crate::IndexedReader::open_with_index(path, index_path, cache_limit), + None => crate::IndexedReader::from_source(crate::Source::open(path)?, None, crate::DecodeOptions { threads, memory_limit }, cache_limit), + }) + .map_err(python_error)?; + Ok(Self { inner: Mutex::new(inner) }) + } + + #[staticmethod] + #[pyo3(signature = (data, threads=0, memory_limit=crate::DEFAULT_MEMORY_LIMIT, index=None, cache_limit=crate::DEFAULT_CACHE_LIMIT))] + fn from_bytes(py: Python<'_>, data: &[u8], threads: usize, memory_limit: usize, index: Option<&[u8]>, cache_limit: usize) -> PyResult { + let data = data.to_vec(); + let index = index.map(<[u8]>::to_vec); + let inner = py + .detach(move || match index { + Some(index) => crate::IndexedReader::from_bytes_with_index(data, &index, cache_limit), + None => { + crate::IndexedReader::from_source(crate::Source::from_bytes(data), None, crate::DecodeOptions { threads, memory_limit }, cache_limit) + } + }) + .map_err(python_error)?; + Ok(Self { inner: Mutex::new(inner) }) + } + + fn read(&self, py: Python<'_>, size: i64) -> PyResult> { + let output = py + .detach(|| { + let mut reader = self.inner.lock().map_err(|_| crate::Error::InvalidConfiguration("reader lock poisoned".into()))?; + let remaining = reader.size() - reader.position(); + let count = if size < 0 { remaining } else { remaining.min(size as u64) }; + let count = usize::try_from(count).map_err(|_| crate::Error::InvalidConfiguration("requested read does not fit this platform".into()))?; + let mut output = vec![0; count]; + reader.read_exact(&mut output)?; + Ok::<_, crate::Error>(output) + }) + .map_err(python_error)?; + Ok(PyBytes::new(py, &output).unbind()) + } + + #[pyo3(signature = (offset, whence=0))] + fn seek(&self, py: Python<'_>, offset: i64, whence: i32) -> PyResult { + py.detach(|| { + let mut reader = self.inner.lock().map_err(|_| crate::Error::InvalidConfiguration("reader lock poisoned".into()))?; + let position = match whence { + 0 if offset >= 0 => SeekFrom::Start(offset as u64), + 0 => return Err(crate::Error::Io(std::io::Error::new(std::io::ErrorKind::InvalidInput, "negative absolute seek"))), + 1 => SeekFrom::Current(offset), + 2 => SeekFrom::End(offset), + _ => return Err(crate::Error::Io(std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid whence"))), + }; + reader.seek(position).map_err(crate::Error::from) + }) + .map_err(python_error) + } + + fn tell(&self) -> PyResult { + self.inner.lock().map(|reader| reader.position()).map_err(|_| PyValueError::new_err("reader lock poisoned")) + } + + #[getter] + fn size(&self) -> PyResult { + self.inner.lock().map(|reader| reader.size()).map_err(|_| PyValueError::new_err("reader lock poisoned")) + } + + fn index_bytes(&self, py: Python<'_>) -> PyResult> { + let encoded = self.inner.lock().map(|reader| reader.index().to_bytes()).map_err(|_| PyValueError::new_err("reader lock poisoned"))?; + Ok(PyBytes::new(py, &encoded).unbind()) + } + } + #[pymodule] fn _core(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(py_scan, m)?)?; m.add_function(wrap_pyfunction!(py_bz2_crc32, m)?)?; + m.add_function(wrap_pyfunction!(py_decompress, m)?)?; + m.add_function(wrap_pyfunction!(py_build_index, m)?)?; + m.add_function(wrap_pyfunction!(py_test, m)?)?; + m.add_class::()?; + m.add("BadBzip2File", m.py().get_type::())?; m.add("__version__", env!("CARGO_PKG_VERSION"))?; Ok(()) } diff --git a/src/source.rs b/src/source.rs new file mode 100644 index 0000000..8e8f281 --- /dev/null +++ b/src/source.rs @@ -0,0 +1,49 @@ +use std::{fs::File, io, path::Path, sync::Arc}; + +use memmap2::{Mmap, MmapOptions}; + +#[derive(Clone)] +pub struct Source(Arc); + +enum SourceInner { + Bytes(Vec), + Mmap(Mmap), +} + +impl Source { + pub fn from_bytes(data: Vec) -> Self { + Self(Arc::new(SourceInner::Bytes(data))) + } + + pub fn open(path: impl AsRef) -> io::Result { + let file = File::open(path)?; + if file.metadata()?.len() == 0 { + return Ok(Self::from_bytes(Vec::new())); + } + // SAFETY: the read-only mapping owns no borrowed file state and `Mmap` + // keeps the mapping alive until the last cloned `Source` is dropped. + let mmap = unsafe { MmapOptions::new().map(&file)? }; + Ok(Self(Arc::new(SourceInner::Mmap(mmap)))) + } + + pub fn as_slice(&self) -> &[u8] { + match self.0.as_ref() { + SourceInner::Bytes(data) => data, + SourceInner::Mmap(data) => data, + } + } + + pub fn len(&self) -> usize { + self.as_slice().len() + } + + pub fn is_empty(&self) -> bool { + self.as_slice().is_empty() + } +} + +impl AsRef<[u8]> for Source { + fn as_ref(&self) -> &[u8] { + self.as_slice() + } +} diff --git a/tests/cli.rs b/tests/cli.rs new file mode 100644 index 0000000..7fd9e62 --- /dev/null +++ b/tests/cli.rs @@ -0,0 +1,47 @@ +use std::{fs, process::Command}; + +use crabz2::{Level, compress}; + +fn binary() -> Command { + Command::new(env!("CARGO_BIN_EXE_fastbz2")) +} + +#[test] +fn decode_test_index_and_list() { + let directory = tempfile::tempdir().unwrap(); + let input = directory.path().join("sample.bz2"); + let output = directory.path().join("sample.txt"); + let index = directory.path().join("sample.fbz2i"); + let plain: Vec<_> = (0..250_000).map(|i| ((i * 31 + i / 97) & 255) as u8).collect(); + fs::write(&input, compress(&plain, Level::FASTEST)).unwrap(); + + let decoded = binary().args(["decode", input.to_str().unwrap(), "-o", output.to_str().unwrap(), "-P", "2"]).status().unwrap(); + assert!(decoded.success()); + assert_eq!(fs::read(&output).unwrap(), plain); + + let tested = binary().args(["test", input.to_str().unwrap()]).status().unwrap(); + assert!(tested.success()); + + let indexed = binary().args(["index", input.to_str().unwrap(), "-o", index.to_str().unwrap()]).status().unwrap(); + assert!(indexed.success()); + assert!(fs::metadata(index).unwrap().len() > 100); + + let listed = binary().args(["list", input.to_str().unwrap()]).output().unwrap(); + assert!(listed.status.success()); + assert!(String::from_utf8(listed.stdout).unwrap().contains("blocks\t")); +} + +#[test] +fn corruption_has_distinct_exit_status_and_atomic_output() { + let directory = tempfile::tempdir().unwrap(); + let input = directory.path().join("corrupt.bz2"); + let output = directory.path().join("output"); + let mut compressed = compress(b"corrupt me", Level::BEST); + let last = compressed.len() - 2; + compressed[last] ^= 1; + fs::write(&input, compressed).unwrap(); + + let result = binary().args(["decode", input.to_str().unwrap(), "-o", output.to_str().unwrap()]).status().unwrap(); + assert_eq!(result.code(), Some(3)); + assert!(!output.exists()); +} diff --git a/tests/corpus.rs b/tests/corpus.rs new file mode 100644 index 0000000..5f1a2b9 --- /dev/null +++ b/tests/corpus.rs @@ -0,0 +1,155 @@ +use std::{ + ffi::{c_char, c_uint}, + fs, + path::{Path, PathBuf}, + ptr, +}; + +use crabz2::{Level, compress}; +use fastbz2::{DecodeOptions, decompress}; +use libbz2_rs_sys::{BZ_OK, BZ_STREAM_END, BZ2_bzDecompress, BZ2_bzDecompressEnd, BZ2_bzDecompressInit, bz_stream}; + +const CHUNK: usize = 64 * 1024; + +fn corpus_files(extension: &str) -> Vec { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus"); + let mut files = Vec::new(); + for source in ["go", "lbzip2"] { + for entry in fs::read_dir(root.join(source)).unwrap() { + let path = entry.unwrap().path(); + if path.to_string_lossy().ends_with(extension) { + files.push(path) + } + } + } + files.sort(); + files +} + +/// Decode every concatenated stream through the low-level API so the oracle +/// has the same whole-file semantics as fastbz2. +fn oracle_decompress(input: &[u8]) -> Result, i32> { + if input.is_empty() { + return Err(libbz2_rs_sys::BZ_DATA_ERROR_MAGIC); + } + let mut decoded = Vec::new(); + let mut input_offset = 0; + + while input_offset < input.len() { + let remaining = &input[input_offset..]; + let input_len = c_uint::try_from(remaining.len()).unwrap(); + let mut stream = bz_stream { + next_in: remaining.as_ptr().cast::(), + avail_in: input_len, + total_in_lo32: 0, + total_in_hi32: 0, + next_out: ptr::null_mut(), + avail_out: 0, + total_out_lo32: 0, + total_out_hi32: 0, + state: ptr::null_mut(), + bzalloc: None, + bzfree: None, + opaque: ptr::null_mut(), + }; + let init = unsafe { BZ2_bzDecompressInit(&mut stream, 0, 0) }; + if init != BZ_OK { + return Err(init); + } + + let result = loop { + let start = decoded.len(); + decoded.resize(start + CHUNK, 0); + stream.next_out = decoded[start..].as_mut_ptr().cast::(); + stream.avail_out = CHUNK as c_uint; + let status = unsafe { BZ2_bzDecompress(&mut stream) }; + decoded.truncate(start + CHUNK - stream.avail_out as usize); + + if status == BZ_STREAM_END { + break Ok(()); + } + if status != BZ_OK { + break Err(status); + } + if stream.avail_in == 0 && stream.avail_out != 0 { + break Err(libbz2_rs_sys::BZ_UNEXPECTED_EOF); + } + }; + let consumed = input_len - stream.avail_in; + let end = unsafe { BZ2_bzDecompressEnd(&mut stream) }; + result?; + if end != BZ_OK { + return Err(end); + } + if consumed == 0 { + return Err(libbz2_rs_sys::BZ_DATA_ERROR); + } + input_offset += consumed as usize; + } + Ok(decoded) +} + +fn patterned(size: usize, stride: usize) -> Vec { + (0..size).map(|index| ((index * stride + index / 251) & 255) as u8).collect() +} + +#[test] +fn valid_upstream_corpus_matches_oracle() { + let files = corpus_files(".bz2"); + assert!(files.len() >= 16); + for path in files { + let encoded = fs::read(&path).unwrap(); + let expected = oracle_decompress(&encoded).unwrap_or_else(|status| panic!("oracle rejected {} with {status}", path.display())); + for threads in [1, 2] { + let actual = decompress(&encoded, DecodeOptions { threads, ..DecodeOptions::default() }) + .unwrap_or_else(|error| panic!("fastbz2 rejected {} with {error}", path.display())); + assert_eq!(actual, expected, "{} with {threads} threads", path.display()); + } + } +} + +#[test] +fn corrupt_upstream_corpus_is_rejected() { + let files = corpus_files(".bz2.bad"); + assert!(files.len() >= 5); + for path in files { + let encoded = fs::read(&path).unwrap(); + assert!(oracle_decompress(&encoded).is_err(), "oracle accepted {}", path.display()); + assert!(decompress(&encoded, DecodeOptions::default()).is_err(), "fastbz2 accepted {}", path.display()); + } +} + +#[test] +fn generated_shapes_match_oracle() { + let cases = [Vec::new(), vec![0; 200_000], (0_u8..=255).cycle().take(200_000).collect(), patterned(200_000, 37), patterned(1_100_000, 251)]; + for (case, level) in cases.into_iter().zip([Level::FASTEST, Level::BEST, Level::FASTEST, Level::BEST, Level::FASTEST]) { + let encoded = compress(&case, level); + assert_eq!(decompress(&encoded, DecodeOptions { threads: 2, ..DecodeOptions::default() }).unwrap(), oracle_decompress(&encoded).unwrap()); + } +} + +#[cfg(not(debug_assertions))] +fn elapsed(repeats: usize, mut decode: impl FnMut()) -> std::time::Duration { + decode(); + let start = std::time::Instant::now(); + for _ in 0..repeats { + decode() + } + start.elapsed() +} + +#[test] +#[cfg(not(debug_assertions))] +fn performance_stays_within_twenty_percent_of_oracle() { + let source = oracle_decompress(include_bytes!("corpus/go/Isaac.Newton-Opticks.txt.bz2")).unwrap(); + let plain = source.repeat(2); + let encoded = compress(&plain, Level::FASTEST); + let repeats = 3; + let fastbz2_time = elapsed(repeats, || { + std::hint::black_box(decompress(&encoded, DecodeOptions { threads: 2, ..DecodeOptions::default() }).unwrap()); + }); + let oracle_time = elapsed(repeats, || { + std::hint::black_box(oracle_decompress(&encoded).unwrap()); + }); + assert!(fastbz2_time.as_secs_f64() <= oracle_time.as_secs_f64() * 1.2, "fastbz2 {fastbz2_time:?} exceeded 1.2x oracle {oracle_time:?}"); +} diff --git a/tests/corpus/README.md b/tests/corpus/README.md new file mode 100644 index 0000000..0548c6a --- /dev/null +++ b/tests/corpus/README.md @@ -0,0 +1,18 @@ +# bzip2 test corpus + +These are selected small cases from maintained upstream test suites. They are +kept in the repository so correctness tests are deterministic and need no +network access. + +- `go/` and `lbzip2/` come from the official + [`bzip2-testfiles`](https://gitlab.com/bzip2/bzip2-testfiles) collection. + Files ending in `.bz2` are valid and files ending in `.bz2.bad` are + deliberately corrupt. Each directory contains its upstream license. + +Legacy randomized blocks produced by bzip2 versions before 0.9.5 are excluded: +supporting this obsolete format would complicate the production decoder and +its hot path for no realistic modern input. + +The uncompressed reference bytes are deliberately not stored. Tests decode +valid inputs with the maintained pure-Rust `libbz2-rs-sys` implementation and +compare `fastbz2` byte-for-byte with that differential oracle. diff --git a/tests/corpus/go/Isaac.Newton-Opticks.txt.bz2 b/tests/corpus/go/Isaac.Newton-Opticks.txt.bz2 new file mode 100644 index 0000000..6c56de3 Binary files /dev/null and b/tests/corpus/go/Isaac.Newton-Opticks.txt.bz2 differ diff --git a/tests/corpus/go/LICENSE b/tests/corpus/go/LICENSE new file mode 100644 index 0000000..6a66aea --- /dev/null +++ b/tests/corpus/go/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2009 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tests/corpus/go/e.txt.bz2 b/tests/corpus/go/e.txt.bz2 new file mode 100644 index 0000000..65bf3b4 Binary files /dev/null and b/tests/corpus/go/e.txt.bz2 differ diff --git a/tests/corpus/go/fail-issue5747.bz2.bad b/tests/corpus/go/fail-issue5747.bz2.bad new file mode 100644 index 0000000..2bf2b6a Binary files /dev/null and b/tests/corpus/go/fail-issue5747.bz2.bad differ diff --git a/tests/corpus/go/pass-random1.bz2 b/tests/corpus/go/pass-random1.bz2 new file mode 100644 index 0000000..f6a9dc7 Binary files /dev/null and b/tests/corpus/go/pass-random1.bz2 differ diff --git a/tests/corpus/go/pass-random2.bz2 b/tests/corpus/go/pass-random2.bz2 new file mode 100644 index 0000000..91ef775 Binary files /dev/null and b/tests/corpus/go/pass-random2.bz2 differ diff --git a/tests/corpus/go/pass-sawtooth.bz2 b/tests/corpus/go/pass-sawtooth.bz2 new file mode 100644 index 0000000..579a378 Binary files /dev/null and b/tests/corpus/go/pass-sawtooth.bz2 differ diff --git a/tests/corpus/go/random.data.bz2 b/tests/corpus/go/random.data.bz2 new file mode 100644 index 0000000..1ef2300 Binary files /dev/null and b/tests/corpus/go/random.data.bz2 differ diff --git a/tests/corpus/lbzip2/32767.bz2 b/tests/corpus/lbzip2/32767.bz2 new file mode 100644 index 0000000..f2755e8 Binary files /dev/null and b/tests/corpus/lbzip2/32767.bz2 differ diff --git a/tests/corpus/lbzip2/LICENSE b/tests/corpus/lbzip2/LICENSE new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/tests/corpus/lbzip2/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/tests/corpus/lbzip2/ch255.bz2 b/tests/corpus/lbzip2/ch255.bz2 new file mode 100644 index 0000000..8438480 Binary files /dev/null and b/tests/corpus/lbzip2/ch255.bz2 differ diff --git a/tests/corpus/lbzip2/codelen20.bz2 b/tests/corpus/lbzip2/codelen20.bz2 new file mode 100644 index 0000000..a224901 Binary files /dev/null and b/tests/corpus/lbzip2/codelen20.bz2 differ diff --git a/tests/corpus/lbzip2/concat.bz2 b/tests/corpus/lbzip2/concat.bz2 new file mode 100644 index 0000000..a963795 Binary files /dev/null and b/tests/corpus/lbzip2/concat.bz2 differ diff --git a/tests/corpus/lbzip2/crc1.bz2.bad b/tests/corpus/lbzip2/crc1.bz2.bad new file mode 100644 index 0000000..cba1a73 Binary files /dev/null and b/tests/corpus/lbzip2/crc1.bz2.bad differ diff --git a/tests/corpus/lbzip2/crc2.bz2.bad b/tests/corpus/lbzip2/crc2.bz2.bad new file mode 100644 index 0000000..4541601 Binary files /dev/null and b/tests/corpus/lbzip2/crc2.bz2.bad differ diff --git a/tests/corpus/lbzip2/cve.bz2.bad b/tests/corpus/lbzip2/cve.bz2.bad new file mode 100644 index 0000000..6634c45 Binary files /dev/null and b/tests/corpus/lbzip2/cve.bz2.bad differ diff --git a/tests/corpus/lbzip2/cve2.bz2.bad b/tests/corpus/lbzip2/cve2.bz2.bad new file mode 100644 index 0000000..6634c45 Binary files /dev/null and b/tests/corpus/lbzip2/cve2.bz2.bad differ diff --git a/tests/corpus/lbzip2/empty.bz2 b/tests/corpus/lbzip2/empty.bz2 new file mode 100644 index 0000000..b56f3b9 Binary files /dev/null and b/tests/corpus/lbzip2/empty.bz2 differ diff --git a/tests/corpus/lbzip2/fib.bz2 b/tests/corpus/lbzip2/fib.bz2 new file mode 100644 index 0000000..f129141 Binary files /dev/null and b/tests/corpus/lbzip2/fib.bz2 differ diff --git a/tests/corpus/lbzip2/idx899999.bz2 b/tests/corpus/lbzip2/idx899999.bz2 new file mode 100644 index 0000000..83678fc Binary files /dev/null and b/tests/corpus/lbzip2/idx899999.bz2 differ diff --git a/tests/corpus/lbzip2/incomp-1.bz2 b/tests/corpus/lbzip2/incomp-1.bz2 new file mode 100644 index 0000000..fd139a2 Binary files /dev/null and b/tests/corpus/lbzip2/incomp-1.bz2 differ diff --git a/tests/corpus/lbzip2/incomp-2.bz2 b/tests/corpus/lbzip2/incomp-2.bz2 new file mode 100644 index 0000000..6203421 Binary files /dev/null and b/tests/corpus/lbzip2/incomp-2.bz2 differ diff --git a/tests/corpus/lbzip2/overrun.bz2.bad b/tests/corpus/lbzip2/overrun.bz2.bad new file mode 100644 index 0000000..79cc5ec Binary files /dev/null and b/tests/corpus/lbzip2/overrun.bz2.bad differ diff --git a/tests/corpus/lbzip2/overrun2.bz2.bad b/tests/corpus/lbzip2/overrun2.bz2.bad new file mode 100644 index 0000000..6765d72 Binary files /dev/null and b/tests/corpus/lbzip2/overrun2.bz2.bad differ diff --git a/tests/corpus/lbzip2/repet.bz2 b/tests/corpus/lbzip2/repet.bz2 new file mode 100644 index 0000000..687f85b Binary files /dev/null and b/tests/corpus/lbzip2/repet.bz2 differ diff --git a/tests/corpus/lbzip2/void.bz2.bad b/tests/corpus/lbzip2/void.bz2.bad new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_api.py b/tests/test_api.py new file mode 100644 index 0000000..02adc91 --- /dev/null +++ b/tests/test_api.py @@ -0,0 +1,77 @@ +import bz2 +import io +from threading import Event, Thread + +import pytest + +import fastbz2 + +def patterned(size): return bytes((i * 37 + i // 251) & 255 for i in range(size)) + +@pytest.mark.parametrize("level", range(1, 10)) +def test_decompress_matches_libbz2_at_every_level(level): + plain = patterned(20_000) + assert fastbz2.decompress(bz2.compress(plain, compresslevel=level), threads=2) == plain + +def test_parallel_multiblock_and_concatenated_are_deterministic(): + first, second = patterned(350_000), patterned(75_000) + compressed = bz2.compress(first, compresslevel=1) + bz2.compress(second, compresslevel=9) + expected = first + second + for threads in (1, 2, 4, 0): assert fastbz2.decompress(compressed, threads=threads) == expected + +def test_bad_crc_raises_package_error(): + compressed = bytearray(bz2.compress(b"integrity matters")) + compressed[-2] ^= 1 + with pytest.raises(fastbz2.BadBzip2File): fastbz2.decompress(bytes(compressed)) + +def test_seekable_file_and_persisted_index(tmp_path): + plain = patterned(350_000) + compressed = bz2.compress(plain, compresslevel=1) + source = tmp_path / "data.bz2" + index_path = tmp_path / "data.fbz2i" + source.write_bytes(compressed) + encoded = fastbz2.build_index(source, index_path, threads=2) + + with fastbz2.open(source, index=index_path) as handle: + assert handle.size == len(plain) + assert handle.seek(99_990) == 99_990 + assert handle.read(40) == plain[99_990:100_030] + handle.seek(-17, io.SEEK_END) + target = bytearray(20) + assert handle.readinto(target) == 17 + assert target[:17] == plain[-17:] + assert handle.index_bytes() == encoded + assert handle.closed + +def test_index_is_bound_to_source(): + first = bz2.compress(b"first") + second = bz2.compress(b"other") + index = fastbz2.build_index(first) + with pytest.raises(ValueError, match="source identity mismatch"): fastbz2.open(second, index=index) + +def test_buffered_reader_compatibility(): + plain = patterned(180_000) + with io.BufferedReader(fastbz2.open(bz2.compress(plain, compresslevel=1))) as handle: + assert handle.read(1234) == plain[:1234] + handle.seek(100_000) + assert handle.read() == plain[100_000:] + +def test_native_decode_releases_gil(): + plain = patterned(2_000_000) + compressed = bz2.compress(plain, compresslevel=1) + started, stop = Event(), Event() + counter = [0] + + def spin(): + started.set() + while not stop.is_set(): counter[0] += 1 + + thread = Thread(target=spin) + thread.start() + started.wait() + before = counter[0] + try: assert fastbz2.decompress(compressed, threads=2) == plain + finally: + stop.set() + thread.join() + assert counter[0] > before diff --git a/tests/test_install.py b/tests/test_install.py new file mode 100644 index 0000000..9f753d0 --- /dev/null +++ b/tests/test_install.py @@ -0,0 +1,11 @@ +import shutil, subprocess +from pathlib import Path + +import fastbz2 + +def test_pip_installs_native_cli(): + executable = shutil.which("fastbz2") + assert executable is not None + assert not Path(executable).read_bytes().startswith(b"#!") + result = subprocess.run([executable, "--version"], check=True, capture_output=True, text=True) + assert result.stdout.strip() == f"fastbz2 {fastbz2.__version__}" diff --git a/tests/wiki_perf.rs b/tests/wiki_perf.rs new file mode 100644 index 0000000..4c65fd8 --- /dev/null +++ b/tests/wiki_perf.rs @@ -0,0 +1,74 @@ +use std::{ + fs, + io::{self, Write}, + path::Path, + time::{Duration, Instant}, +}; + +use fastbz2::{DecodeOptions, Source, decompress, decompress_to_writer}; + +const FIVE_PERCENT_LEN: usize = 84_423_012; +const FIVE_PERCENT_BLAKE3: &str = "69f41f28dc8ac74509d368c6aaec02f3cdf891c9da4ccf8caf625687dcd61908"; +const FULL_LEN: u64 = 1_688_460_257; + +#[derive(Default)] +struct CountingSink(u64); + +impl Write for CountingSink { + fn write(&mut self, buffer: &[u8]) -> io::Result { + self.0 += buffer.len() as u64; + Ok(buffer.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +fn corpus_path(name: &str) -> std::path::PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("meta").join(name) +} + +fn requested_threads() -> usize { + std::env::var("FASTBZ2_THREADS").ok().map(|value| value.parse().expect("FASTBZ2_THREADS must be an integer")).unwrap_or(0) +} + +fn timed_fastbz2(path: &Path, threads: usize) -> Duration { + let start = Instant::now(); + let source = Source::open(path).unwrap(); + let mut output = CountingSink::default(); + decompress_to_writer(source.as_slice(), &mut output, DecodeOptions { threads, ..DecodeOptions::default() }).unwrap(); + let elapsed = start.elapsed(); + assert_eq!(output.0, FULL_LEN); + elapsed +} + +#[test] +#[ignore = "local SimpleWiki performance benchmark"] +fn simplewiki_first_five_percent() { + let path = corpus_path("simplewiki-first-5pct.xml.bz2"); + let encoded = fs::read(&path).unwrap_or_else(|error| panic!("could not read {}: {error}", path.display())); + let threads = requested_threads(); + let options = DecodeOptions { threads, ..DecodeOptions::default() }; + let resolved_threads = options.resolved_threads(); + + let start = Instant::now(); + let decoded = decompress(&encoded, options).unwrap(); + let elapsed = start.elapsed(); + let mib_per_second = decoded.len() as f64 / (1024.0 * 1024.0) / elapsed.as_secs_f64(); + let hash = blake3::hash(&decoded).to_hex().to_string(); + eprintln!("SimpleWiki 5%: {elapsed:.3?}, {mib_per_second:.1} MiB/s, {resolved_threads} threads, BLAKE3 {hash}"); + + assert_eq!(decoded.len(), FIVE_PERCENT_LEN); + assert_eq!(hash, FIVE_PERCENT_BLAKE3); +} + +#[test] +#[ignore = "local full SimpleWiki performance benchmark"] +fn simplewiki_full() { + let path = corpus_path("simplewiki-full.xml.bz2"); + let options = DecodeOptions { threads: requested_threads(), ..DecodeOptions::default() }; + + let elapsed = timed_fastbz2(&path, options.threads); + eprintln!("fastbz2 ({} threads): {elapsed:.3?}", options.resolved_threads()); +} diff --git a/tools/stage_binaries.py b/tools/stage_binaries.py new file mode 100644 index 0000000..ebf2e7a --- /dev/null +++ b/tools/stage_binaries.py @@ -0,0 +1,9 @@ +import os, shutil +from pathlib import Path + +root = Path(__file__).resolve().parents[1] +source = root / "target" / "release" +destination = root / "target" / "wheel-data" / "scripts" +destination.mkdir(parents=True, exist_ok=True) +suffix = ".exe" if os.name == "nt" else "" +shutil.copy2(source / f"fastbz2{suffix}", destination / f"fastbz2{suffix}")