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 FormatField,
26}
27
28impl SizeLimit {
29 #[must_use]
32 pub const fn refusal_key(self) -> &'static str {
33 match self {
34 Self::MemoryBudget => "image/limit/memory-budget",
35 Self::OperatorPixelCap => "image/limit/pixel-cap",
36 Self::FormatField => "image/limit/format-field",
37 }
38 }
39
40 #[must_use]
42 pub const fn unit(self) -> &'static str {
43 match self {
44 Self::MemoryBudget => "bytes",
45 Self::OperatorPixelCap => "pixels",
46 Self::FormatField => "samples per side",
47 }
48 }
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
65#[non_exhaustive]
66pub struct DecodeOptions {
67 pub cmyk_jpeg_polarity: CmykJpegPolarity,
69 pub limits: DecodeLimits,
71}
72
73impl DecodeOptions {
74 #[must_use]
76 pub const fn with_cmyk_jpeg_polarity(mut self, polarity: CmykJpegPolarity) -> Self {
77 self.cmyk_jpeg_polarity = polarity;
78 self
79 }
80
81 #[must_use]
83 pub const fn with_limits(mut self, limits: DecodeLimits) -> Self {
84 self.limits = limits;
85 self
86 }
87}
88
89pub(crate) fn check(
98 doc: &DocumentView<'_>,
99 dict: &Dict,
100 raw: &[u8],
101 limits: &DecodeLimits,
102) -> Result<(), ImageCodecError> {
103 let pixels = declared_pixels(doc, dict);
104 if let (Some(cap), Some(pixels)) = (limits.max_pixels, pixels)
105 && pixels > cap
106 {
107 return Err(ImageCodecError::LimitExceeded {
108 limit: SizeLimit::OperatorPixelCap,
109 needed: pixels,
110 allowed: cap,
111 });
112 }
113 let downstream = pixels
114 .unwrap_or(0)
115 .saturating_mul(limits.downstream_bytes_per_pixel);
116 let needed = predict_peak(doc, dict, raw)
117 .unwrap_or(0)
118 .saturating_add(downstream);
119 if needed > limits.memory_budget {
120 return Err(ImageCodecError::LimitExceeded {
121 limit: SizeLimit::MemoryBudget,
122 needed,
123 allowed: limits.memory_budget,
124 });
125 }
126 Ok(())
127}
128
129pub(crate) fn admit(limits: &DecodeLimits, needed: u64) -> Result<(), ImageCodecError> {
133 if needed > limits.memory_budget {
134 return Err(ImageCodecError::LimitExceeded {
135 limit: SizeLimit::MemoryBudget,
136 needed,
137 allowed: limits.memory_budget,
138 });
139 }
140 Ok(())
141}
142
143fn declared_pixels(doc: &DocumentView<'_>, dict: &Dict) -> Option<u64> {
144 let dim = |key: &[u8], short: &[u8]| -> Option<u64> {
145 let entry = dict.get(key).or_else(|| dict.get(short))?;
146 u64::try_from(doc.resolve(entry).as_int()?).ok()
147 };
148 Some(dim(b"Width", b"W")?.saturating_mul(dim(b"Height", b"H")?))
149}