pdfcer_image_codec/
limits.rs1use pdfcer_model::graph::ObjectGraph;
5use pdfcer_model::object::Dict;
6use pdfcer_model::view::DocumentView;
7
8use crate::peak::{DecodeLimits, predict_peak};
9use crate::{CmykJpegPolarity, ImageCodecError};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13#[non_exhaustive]
14pub enum SizeLimit {
15 MemoryBudget,
19 OperatorPixelCap,
22}
23
24impl SizeLimit {
25 #[must_use]
28 pub const fn refusal_key(self) -> &'static str {
29 match self {
30 Self::MemoryBudget => "image/limit/memory-budget",
31 Self::OperatorPixelCap => "image/limit/pixel-cap",
32 }
33 }
34
35 #[must_use]
37 pub const fn unit(self) -> &'static str {
38 match self {
39 Self::MemoryBudget => "bytes",
40 Self::OperatorPixelCap => "pixels",
41 }
42 }
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
59#[non_exhaustive]
60pub struct DecodeOptions {
61 pub cmyk_jpeg_polarity: CmykJpegPolarity,
63 pub limits: DecodeLimits,
65}
66
67impl DecodeOptions {
68 #[must_use]
70 pub const fn with_cmyk_jpeg_polarity(mut self, polarity: CmykJpegPolarity) -> Self {
71 self.cmyk_jpeg_polarity = polarity;
72 self
73 }
74
75 #[must_use]
77 pub const fn with_limits(mut self, limits: DecodeLimits) -> Self {
78 self.limits = limits;
79 self
80 }
81}
82
83pub(crate) fn check(
92 doc: &DocumentView<'_>,
93 dict: &Dict,
94 raw: &[u8],
95 limits: &DecodeLimits,
96) -> Result<(), ImageCodecError> {
97 let pixels = declared_pixels(doc, dict);
98 if let (Some(cap), Some(pixels)) = (limits.max_pixels, pixels)
99 && pixels > cap
100 {
101 return Err(ImageCodecError::LimitExceeded {
102 limit: SizeLimit::OperatorPixelCap,
103 needed: pixels,
104 allowed: cap,
105 });
106 }
107 let downstream = pixels
108 .unwrap_or(0)
109 .saturating_mul(limits.downstream_bytes_per_pixel);
110 let needed = predict_peak(doc, dict, raw)
111 .unwrap_or(0)
112 .saturating_add(downstream);
113 if needed > limits.memory_budget {
114 return Err(ImageCodecError::LimitExceeded {
115 limit: SizeLimit::MemoryBudget,
116 needed,
117 allowed: limits.memory_budget,
118 });
119 }
120 Ok(())
121}
122
123fn declared_pixels(doc: &DocumentView<'_>, dict: &Dict) -> Option<u64> {
124 let dim = |key: &[u8], short: &[u8]| -> Option<u64> {
125 let entry = dict.get(key).or_else(|| dict.get(short))?;
126 u64::try_from(doc.resolve(entry).as_int()?).ok()
127 };
128 Some(dim(b"Width", b"W")?.saturating_mul(dim(b"Height", b"H")?))
129}