jbig2-decoder 0.3.3

Memory-safe JBIG2 decoder under development
Documentation
//! Direct-to-bitmap text-region body decoders, including a hoisted pure-Huffman fast path.

#[cfg(verus_keep_ghost)]
use super::super::symbol_text_spec;
use super::super::{
    HuffmanCodec, IntegerField, PlacementBatch, ResourceTracker, SymbolCodebook, SymbolTextError,
    TextRegionConfig, TextRegionEnd, TextRegionState,
};
use super::{flush_placement_batch, prepare_placement};
use crate::huffman::HuffmanValue;
use crate::{Bitmap, Limits, MalformedError};
#[cfg(verus_keep_ghost)]
use vstd::prelude::*;

#[cfg_attr(verus_keep_ghost, verus_spec(out =>
    requires crate::huffman::huffman_spec::reader_valid(old(reader)),
    ensures
        crate::huffman::huffman_spec::reader_valid(final(reader)),
        final(reader).bytes@ == old(reader).bytes@,
))]
#[inline]
fn decode_required_huffman_i64(
    table: &crate::huffman::HuffmanTable,
    reader: &mut crate::reader::BitReader<'_>,
) -> Result<i64, SymbolTextError> {
    match table.decode(reader)? {
        HuffmanValue::Integer(value) => Ok(i64::from(value)),
        HuffmanValue::OutOfBand => Err(SymbolTextError::UnexpectedOutOfBand(
            "required integer field",
        )),
    }
}

/// Decodes a non-refinement pure-Huffman text region directly into `bitmap`,
/// hoisting all Huffman table lookups out of the per-instance loop.
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
#[cfg_attr(verus_keep_ghost, verus_spec(out =>
    requires
        crate::spec::bitmap::storage_valid(old(bitmap)),
        crate::huffman::huffman_spec::reader_valid(&old(huffman).reader),
        symbol_text_spec::codebook_valid(available_symbols),
        symbol_text_spec::work_units(old(resources)) <= limits.max_work_units,
        *old(end) == TextRegionEnd::Strict || *old(end) == TextRegionEnd::BoundedHuffman,
    ensures
        match out {
            Ok(()) =>
                crate::spec::bitmap::storage_valid(final(bitmap))
                    && crate::views::bitmap_width(final(bitmap))
                        == crate::views::bitmap_width(old(bitmap))
                    && crate::views::bitmap_height(final(bitmap))
                        == crate::views::bitmap_height(old(bitmap))
                    && crate::huffman::huffman_spec::reader_valid(&final(huffman).reader)
                    && final(huffman).reader.bytes@ == old(huffman).reader.bytes@
                    && final(huffman).refinement == old(huffman).refinement
                    && symbol_text_spec::work_units(final(resources)) <= limits.max_work_units
                    && match *final(end) {
                        TextRegionEnd::RecoveredHuffman { instances, padding_start } =>
                            *old(end) == TextRegionEnd::BoundedHuffman
                            && instances == number_of_instances
                            && instances > 0
                            && padding_start <= final(huffman).reader.bit_position
                            && final(huffman).reader.bit_position - padding_start < 8
                            && final(huffman).reader.bit_position
                                == final(huffman).reader.bytes@.len() * 8,
                        _ => *final(end) == *old(end),
                    },
            Err(_) => true,
        },
))]
pub(super) fn decode_text_region_body_huffman_into(
    bitmap: &mut Bitmap,
    huffman: &mut HuffmanCodec<'_>,
    available_symbols: SymbolCodebook<'_>,
    number_of_instances: u32,
    config: &TextRegionConfig,
    limits: &Limits,
    resources: &mut ResourceTracker,
    end: &mut TextRegionEnd,
) -> Result<(), SymbolTextError> {
    #[cfg(verus_keep_ghost)]
    proof_decl! { let ghost initial_end = *end; }
    let width = bitmap.width();
    let height = bitmap.height();
    resources.charge_bitmap(width, height, limits)?;
    let mut placement_batch = PlacementBatch::new();
    placement_batch.reserve(
        usize::try_from(number_of_instances).map_err(|_| MalformedError::IntegerOverflow)?,
        limits,
    )?;
    #[cfg(verus_keep_ghost)]
    proof! {
        reveal(symbol_text_spec::placement_batch_valid);
    }

    let log_strip_size = huffman.log_strip_size;
    let strip_delta_table = huffman.tables.table_for(IntegerField::StripDelta).ok_or(
        SymbolTextError::InvalidTableAssociation("no Huffman table bound for field"),
    )?;
    let first_s_table = huffman.tables.table_for(IntegerField::FirstS).ok_or(
        SymbolTextError::InvalidTableAssociation("no Huffman table bound for field"),
    )?;
    let subsequent_s_table = huffman.tables.table_for(IntegerField::SubsequentS).ok_or(
        SymbolTextError::InvalidTableAssociation("no Huffman table bound for field"),
    )?;
    let symbol_id_table = huffman
        .symbol_id_table
        .as_ref()
        .ok_or(SymbolTextError::InvalidState(
            "missing Huffman symbol-ID table",
        ))?;
    let reader = &mut huffman.reader;

    let initial_strip = decode_required_huffman_i64(strip_delta_table, reader)?;
    let mut state = TextRegionState::new(*config, number_of_instances, initial_strip, limits)?;

    let available_count =
        u32::try_from(available_symbols.len()).map_err(|_| MalformedError::IntegerOverflow)?;

    let mut decoded = 0_u32;
    let mut recovered_padding: Option<usize> = None;
    #[cfg_attr(verus_keep_ghost, verus_spec(
        invariant
            decoded <= number_of_instances,
            state.decoded_instances == decoded,
            state.strip.is_none(),
            symbol_text_spec::text_state_valid(&state),
            crate::huffman::huffman_spec::reader_valid(reader),
            reader.bytes@ == old(huffman).reader.bytes@,
            symbol_text_spec::codebook_valid(available_symbols),
            available_count as nat == symbol_text_spec::codebook_len(available_symbols),
            crate::spec::bitmap::storage_valid(bitmap),
            crate::views::bitmap_width(bitmap) == width,
            crate::views::bitmap_height(bitmap) == height,
            symbol_text_spec::placement_batch_valid(&placement_batch, bitmap),
            symbol_text_spec::work_units(resources) <= limits.max_work_units,
            initial_end == *old(end),
            *end == initial_end,
            recovered_padding.is_some() ==> (
                initial_end == TextRegionEnd::BoundedHuffman
                && decoded == number_of_instances
                && decoded > 0
                && recovered_padding.unwrap() <= reader.bit_position
                && reader.bit_position - recovered_padding.unwrap() < 8
                && reader.bit_position == reader.bytes@.len() * 8
            ),
        decreases number_of_instances - decoded,
    ))]
    while decoded < number_of_instances {
        let strip_start = decoded;
        let strip_delta = decode_required_huffman_i64(strip_delta_table, reader)?;
        let first_s_delta = decode_required_huffman_i64(first_s_table, reader)?;
        state.begin_strip(strip_delta, first_s_delta)?;
        let mut first_in_strip = true;
        #[cfg_attr(verus_keep_ghost, verus_spec(
            invariant
                decoded <= number_of_instances,
                strip_start <= decoded,
                strip_start < number_of_instances,
                first_in_strip ==> decoded == strip_start,
                !first_in_strip ==> decoded > strip_start,
                state.decoded_instances == decoded,
                state.strip.is_some(),
                symbol_text_spec::text_state_valid(&state),
                crate::huffman::huffman_spec::reader_valid(reader),
                reader.bytes@ == old(huffman).reader.bytes@,
                symbol_text_spec::codebook_valid(available_symbols),
                available_count as nat == symbol_text_spec::codebook_len(available_symbols),
                crate::spec::bitmap::storage_valid(bitmap),
                crate::views::bitmap_width(bitmap) == width,
                crate::views::bitmap_height(bitmap) == height,
                symbol_text_spec::placement_batch_valid(&placement_batch, bitmap),
                symbol_text_spec::work_units(resources) <= limits.max_work_units,
                *end == initial_end,
            invariant_except_break
                recovered_padding.is_none(),
            ensures
                recovered_padding.is_none() || (
                    initial_end == TextRegionEnd::BoundedHuffman
                    && decoded == number_of_instances
                    && decoded > 0
                    && recovered_padding.unwrap() <= reader.bit_position
                    && reader.bit_position - recovered_padding.unwrap() < 8
                    && reader.bit_position == reader.bytes@.len() * 8
                ),
            decreases number_of_instances - decoded,
        ))]
        loop {
            if decoded == number_of_instances && matches!(end, TextRegionEnd::BoundedHuffman) {
                let padding_start = reader.bit_position;
                match subsequent_s_table.decode_final_strip_value(reader)? {
                    Some(HuffmanValue::OutOfBand) => break,
                    Some(HuffmanValue::Integer(_)) => {
                        return Err(SymbolTextError::InvalidCount("too many text instances"));
                    }
                    None => {
                        recovered_padding = Some(padding_start);
                        break;
                    }
                }
            }
            let s_delta = if first_in_strip {
                None
            } else {
                match subsequent_s_table.decode(reader)? {
                    HuffmanValue::Integer(value) => Some(i64::from(value)),
                    HuffmanValue::OutOfBand => break,
                }
            };
            if decoded == number_of_instances {
                return Err(SymbolTextError::InvalidCount("too many text instances"));
            }
            let within_strip_t = if config.strip_size > 1 {
                let raw = reader.read_bits(log_strip_size)?;
                u8::try_from(raw).map_err(|_| {
                    SymbolTextError::InvalidEntropyValue("within-strip T coordinate")
                })?
            } else {
                0
            };
            let raw_id = match symbol_id_table.decode(reader)? {
                HuffmanValue::Integer(value) => value,
                HuffmanValue::OutOfBand => {
                    return Err(SymbolTextError::UnexpectedOutOfBand("symbol ID"));
                }
            };
            let symbol_id = u32::try_from(raw_id)
                .map_err(|_| SymbolTextError::InvalidEntropyValue("negative symbol ID"))?;
            let base_symbol = available_symbols.get(symbol_id as usize).ok_or(
                SymbolTextError::SymbolIdOutOfRange {
                    id: symbol_id,
                    available: available_count,
                },
            )?;

            let symbol_width = base_symbol.width();
            let symbol_height = base_symbol.height();
            let placement = match s_delta {
                None => state.place_first(
                    within_strip_t,
                    symbol_width,
                    symbol_height,
                    limits,
                    resources,
                )?,
                Some(delta) => state.place_subsequent(
                    delta,
                    within_strip_t,
                    symbol_width,
                    symbol_height,
                    limits,
                    resources,
                )?,
            };
            if let Some(prepared) =
                prepare_placement(bitmap, base_symbol, placement, limits, resources)?
            {
                if !placement_batch.compatible(prepared) {
                    flush_placement_batch(bitmap, &mut placement_batch, config.operator)?;
                }
                placement_batch.push(prepared, bitmap)?;
            }

            decoded += 1;
            first_in_strip = false;
        }
        if decoded == strip_start {
            return Err(SymbolTextError::InvalidState("empty text strip"));
        }
        flush_placement_batch(bitmap, &mut placement_batch, config.operator)?;
        state.end_strip()?;
    }
    if let Some(padding_start) = recovered_padding {
        *end = TextRegionEnd::RecoveredHuffman {
            instances: decoded,
            padding_start,
        };
    }
    flush_placement_batch(bitmap, &mut placement_batch, config.operator)?;
    state.finish()?;
    Ok(())
}