PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
fix(preflight): read content colour one operator at a time
aiongg0a30b4e08107
diff --git a/crates/content/src/lib.rs b/crates/content/src/lib.rsindex eb126ffa2..3432f7ff3 100644--- a/crates/content/src/lib.rs+++ b/crates/content/src/lib.rs@@ -79,90 +79,143 @@ pub fn parse(data: &[u8]) -> Parsed {parse_pieces(data, &[])}+/// The operators of a (decoded) content stream, read one at a time, as [`parse`] reads them. A+/// caller that stops early or keeps only a summary never holds every operator of the stream.+pub fn ops(data: &[u8]) -> Ops<'_> {+ Ops::new(data, &[])+}+/// Parse `data`, recording which of the piece boundaries `ends` (as in [`Pieces`]) a comment/// crosses.fn parse_pieces(data: &[u8], ends: &[usize]) -> Parsed {- let mut out = Parsed { comment_edges: vec![(false, false); ends.len()], ..Parsed::default() };- let mut boundary = 0;- let mut lx = Lexer::new(data, 0);- let mut operands: Vec<Object> = Vec::new();- let mut start: Option<usize> = None;- loop {- let trivia = lx.pos;- lx.skip_ws();- // Only the whitespace the lexer skips here holds top-level comments: a `%` inside a- // string, a name, an array or dictionary operand or inline image data is not one.- if boundary < ends.len() {- comment_edges(data, trivia..lx.pos, ends, &mut boundary, &mut out.comment_edges);+ let mut reader = Ops::new(data, ends);+ let ops = reader.by_ref().collect();+ Parsed { ops, skipped: reader.skipped, comment_edges: reader.comment_edges }+}++/// The iterator [`ops`] returns.+pub struct Ops<'a> {+ data: &'a [u8],+ lx: Lexer<'a>,+ operands: Vec<Object>,+ start: Option<usize>,+ skipped: usize,+ ends: &'a [usize],+ boundary: usize,+ comment_edges: Vec<(bool, bool)>,+}++impl<'a> Ops<'a> {+ fn new(data: &'a [u8], ends: &'a [usize]) -> Self {+ Ops {+ data,+ lx: Lexer::new(data, 0),+ operands: Vec::new(),+ start: None,+ skipped: 0,+ ends,+ boundary: 0,+ comment_edges: vec![(false, false); ends.len()],}- let Some(&b) = data.get(lx.pos) else { break };- let at = lx.pos;- let operand_start = matches!(b, b'/' | b'(' | b'<' | b'[' | b'+' | b'-' | b'.') || b.is_ascii_digit();- if operand_start {- match lx.object() {- Ok(o) => {- start.get_or_insert(at);- operands.push(o);- }- Err(_) if b == b'(' => {- // An unterminated string runs to the end of the stream.- out.skipped += data.len() - at;- lx.pos = data.len();- }- Err(_) => {- // Skip the offending byte and carry on.- lx.pos = at + 1;- out.skipped += 1;- }+ }++ /// Bytes read so far that could not be read as operands or operators.+ pub fn skipped(&self) -> usize {+ self.skipped+ }+}++impl Iterator for Ops<'_> {+ type Item = Op;++ fn next(&mut self) -> Option<Op> {+ let Ops { data, lx, operands, start, skipped, ends, boundary, comment_edges: edges } = self;+ let (data, ends): (&[u8], &[usize]) = (data, ends);+ loop {+ let trivia = lx.pos;+ lx.skip_ws();+ // Only the whitespace the lexer skips here holds top-level comments: a `%` inside a+ // string, a name, an array or dictionary operand or inline image data is not one.+ if *boundary < ends.len() {+ comment_edges(data, trivia..lx.pos, ends, boundary, edges);}- continue;- }- if is_delim(b) {- // A stray `)`, `>`, `]`, `{`, `}`.- lx.pos += 1;- out.skipped += 1;- continue;- }- let kw = lx.token();- if kw.is_empty() {- lx.pos = at + 1;- out.skipped += 1;- continue;- }- match kw {- b"true" => {- start.get_or_insert(at);- operands.push(Object::Bool(true));+ let Some(&b) = data.get(lx.pos) else {+ // Operands left without an operator.+ *skipped += operands.len();+ operands.clear();+ return None;+ };+ let at = lx.pos;+ let operand_start = matches!(b, b'/' | b'(' | b'<' | b'[' | b'+' | b'-' | b'.') || b.is_ascii_digit();+ if operand_start {+ match lx.object() {+ Ok(o) => {+ start.get_or_insert(at);+ operands.push(o);+ }+ Err(_) if b == b'(' => {+ // An unterminated string runs to the end of the stream.+ *skipped += data.len() - at;+ lx.pos = data.len();+ }+ Err(_) => {+ // Skip the offending byte and carry on.+ lx.pos = at + 1;+ *skipped += 1;+ }+ }+ continue;}- b"false" => {- start.get_or_insert(at);- operands.push(Object::Bool(false));+ if is_delim(b) {+ // A stray `)`, `>`, `]`, `{`, `}`.+ lx.pos += 1;+ *skipped += 1;+ continue;}- b"null" => {- start.get_or_insert(at);- operands.push(Object::Null);+ let kw = lx.token();+ if kw.is_empty() {+ lx.pos = at + 1;+ *skipped += 1;+ continue;}- b"BI" => match inline_image(data, lx.pos) {- Ok((dict, img, end)) => {- lx.pos = end;- out.ops.push(Op { op: b"BI".to_vec(), operands: Vec::new(), inline: Some((dict, img)), span: start.take().unwrap_or(at)..end });- operands.clear();+ match kw {+ b"true" => {+ start.get_or_insert(at);+ operands.push(Object::Bool(true));}- Err(end) => {- out.skipped += end.saturating_sub(at);- lx.pos = end;- start = None;- operands.clear();+ b"false" => {+ start.get_or_insert(at);+ operands.push(Object::Bool(false));+ }+ b"null" => {+ start.get_or_insert(at);+ operands.push(Object::Null);+ }+ b"BI" => match inline_image(data, lx.pos) {+ Ok((dict, img, end)) => {+ lx.pos = end;+ operands.clear();+ return Some(Op {+ op: b"BI".to_vec(),+ operands: Vec::new(),+ inline: Some((dict, img)),+ span: start.take().unwrap_or(at)..end,+ });+ }+ Err(end) => {+ *skipped += end.saturating_sub(at);+ lx.pos = end;+ *start = None;+ operands.clear();+ }+ },+ _ => {+ let s = start.take().unwrap_or(at);+ return Some(Op { op: kw.to_vec(), operands: std::mem::take(operands), inline: None, span: s..lx.pos });}- },- _ => {- let s = start.take().unwrap_or(at);- out.ops.push(Op { op: kw.to_vec(), operands: std::mem::take(&mut operands), inline: None, span: s..lx.pos });}}}- out.skipped += operands.len();- out}/// Record the piece boundaries crossed by the comments in `trivia` (skipped whitespace anddiff --git a/crates/preflight/src/lib.rs b/crates/preflight/src/lib.rsindex 2cda29fea..4e5f7eb2a 100644--- a/crates/preflight/src/lib.rs+++ b/crates/preflight/src/lib.rs@@ -339,8 +339,17 @@ fn is_content(d: &Dict) -> bool {/// The device colour a content stream sets. It is read operator by operator, so the bytes of a/// string, a comment or an inline image are never taken for an operator, and an operator right/// before a delimiter (`1 k/GS0 gs`) is still found.-fn content_colour(data: &[u8], used: &mut DeviceColour) {- for op in pdfcraft_content::parse(data).ops {+///+/// Operators are read one at a time and dropped, so a stream of millions of tiny operators never+/// becomes millions of parsed ones in memory, and reading stops once all three spaces are set.+/// Returns how many operators it read.+fn content_colour(data: &[u8], used: &mut DeviceColour) -> usize {+ let mut read = 0;+ for op in pdfcraft_content::ops(data) {+ if used.gray && used.rgb && used.cmyk {+ break;+ }+ read += 1;match op.op.as_slice() {b"g" | b"G" => used.gray = true,b"rg" | b"RG" => used.rgb = true,@@ -366,6 +375,7 @@ fn content_colour(data: &[u8], used: &mut DeviceColour) {_ => {}}}+ read}/// Whether any content or object uses a device colour space.@@ -400,7 +410,7 @@ fn uses_device_colour(doc: &Document, objs: &[(ObjRef, std::sync::Arc<Object>)])&& (referenced.contains(r) || is_content(&s.dict))&& let Ok(data) = s.decoded(){- content_colour(&data, &mut used);+ let _ = content_colour(&data, &mut used);}}useddiff --git a/crates/preflight/src/tests.rs b/crates/preflight/src/tests.rsindex 80b1c63c4..290c7695a 100644--- a/crates/preflight/src/tests.rs+++ b/crates/preflight/src/tests.rs@@ -417,3 +417,16 @@ fn oversized_xmp_is_refused_while_decoding() {assert_eq!(stream.decoded().unwrap().len(), xmp::MAX_XMP_BYTES + 1, "fixture must actually decompress");assert!(metadata(&doc).is_none(), "compressed metadata must be limited during decoding");}++/// Content is read one operator at a time and no further than it needs: once gray, RGB and CMYK+/// are all set, the rest of the stream is not read.+#[test]+fn content_colour_reads_operators_one_at_a_time_and_stops_when_all_are_found() {+ let mut data = b"0 g 0 0 0 rg 0 0 0 0 k\n".to_vec();+ data.extend(b"n\n".repeat(100_000));+ let mut used = DeviceColour::default();+ let read = content_colour(&data, &mut used);+ assert!(used.gray && used.rgb && used.cmyk);+ assert_eq!(read, 3);+}+