pdfcer-image-codec 0.185.0

pdfcer terminal image codecs: DCTDecode, CCITTFaxDecode, JBIG2Decode and JPXDecode (ISO 32000-1 7.4.6-7.4.9). Re-exported by pdfcer-core as `image_codec`.
Documentation
//! `DecodeLimits` at decode time (decision 227, Pass 780.3): the pixel cap
//! refuses by pixels, the memory budget by predicted bytes plus downstream,
//! each exactly at its boundary, and the default refuses nothing ordinary.

use pdfcer_image_codec::peak::DecodeLimits;
use pdfcer_image_codec::{DecodeOptions, ImageCodecError, SizeLimit, decode_image_view_with};

use crate::peak_memory::{empty_document, image_dict};

const SIDE: u32 = 64;

fn decode(limits: DecodeLimits) -> Result<(), ImageCodecError> {
    let doc = empty_document();
    let dict = image_dict(None, SIDE, SIDE, 8, b"DeviceGray");
    let raw = vec![128u8; (SIDE * SIDE) as usize];
    let options = DecodeOptions::default().with_limits(limits);
    decode_image_view_with(&doc.view(), &dict, &raw, false, options).map(|_| ())
}

fn refusal(r: Result<(), ImageCodecError>) -> (SizeLimit, u64, u64) {
    match r {
        Err(ImageCodecError::LimitExceeded {
            limit,
            needed,
            allowed,
        }) => (limit, needed, allowed),
        other => panic!("expected LimitExceeded, got {other:?}"),
    }
}

#[test]
fn the_default_limits_decode_an_ordinary_image() {
    decode(DecodeLimits::default()).expect("a 64x64 image is far inside the fallback");
}

#[test]
fn the_pixel_cap_refuses_one_pixel_over_and_admits_at() {
    let pixels = u64::from(SIDE * SIDE);
    let base = DecodeLimits::new(1 << 30);
    let (limit, needed, allowed) = refusal(decode(base.with_max_pixels(Some(pixels - 1))));
    assert_eq!(limit, SizeLimit::OperatorPixelCap);
    assert_eq!((needed, allowed), (pixels, pixels - 1));
    assert_eq!(limit.refusal_key(), "image/limit/pixel-cap");
    decode(base.with_max_pixels(Some(pixels))).expect("at the cap is allowed");
}

#[test]
fn the_memory_budget_counts_downstream_bytes_and_refuses_exactly_over() {
    let pixels = u64::from(SIDE * SIDE);
    let (limit, needed, allowed) = refusal(decode(DecodeLimits::new(1)));
    assert_eq!((limit, allowed), (SizeLimit::MemoryBudget, 1));
    assert_eq!(limit.refusal_key(), "image/limit/memory-budget");
    assert!(
        needed >= pixels,
        "the decoded samples are counted: {needed}"
    );

    let downstream = DecodeLimits::new(1).with_downstream_bytes_per_pixel(4);
    let (_, with_pixmap, _) = refusal(decode(downstream));
    assert_eq!(
        with_pixmap,
        needed + 4 * pixels,
        "downstream is added per pixel"
    );

    decode(DecodeLimits::new(needed)).expect("exactly the needed figure is admitted");
    refusal(decode(DecodeLimits::new(needed - 1)));
}

#[test]
fn the_pixel_cap_is_checked_before_memory() {
    let limits = DecodeLimits::new(1).with_max_pixels(Some(1));
    assert_eq!(refusal(decode(limits)).0, SizeLimit::OperatorPixelCap);
}