Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Merge upstream/main into fix/coderabbit-c5-forms-misc

aiongg923e499597d1
diff --cc crates/content/src/lib.rs
index 3432f7ff3,097ec2689..ab42728c2
--- a/crates/content/src/lib.rs
+++ b/crates/content/src/lib.rs
@@@ -88,131 -86,90 +92,142 @@@ pub fn ops(data: &[u8]) -> Ops<'_>
/// 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 }
++ Parsed { ops, skipped: reader.skipped, ambiguous_images: reader.ambiguous_images, 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,
++ ambiguous_images: 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,
++ ambiguous_images: 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
+ }
++
++ /// Inline images read so far whose end is this parser's guess (as in
++ /// [`Parsed::ambiguous_images`]).
++ pub fn ambiguous_images(&self) -> usize {
++ self.ambiguous_images
++ }
+}
+
+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 Ops { data, lx, operands, start, skipped, ambiguous_images, 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" => {
- let image = inline_image(data, at, lx.pos);
- out.ambiguous_images += usize::from(image.ambiguous);
- let end = image.end;
- lx.pos = end;
- match image.image {
- Some((dict, img)) => {
- out.ops.push(Op {
- op: b"BI".to_vec(),
- operands: Vec::new(),
- inline: Some((dict, img)),
- span: start.take().unwrap_or(at)..end,
- });
- }
- None => {
- out.skipped += end.saturating_sub(at);
- start = None;
+ match kw {
+ b"true" => {
+ start.get_or_insert(at);
+ operands.push(Object::Bool(true));
+ }
+ 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,
- });
++ b"BI" => {
++ let image = inline_image(data, at, lx.pos);
++ *ambiguous_images += usize::from(image.ambiguous);
++ let end = image.end;
++ lx.pos = end;
++ operands.clear();
++ match image.image {
++ Some((dict, img)) => {
++ return Some(Op {
++ op: b"BI".to_vec(),
++ operands: Vec::new(),
++ inline: Some((dict, img)),
++ span: start.take().unwrap_or(at)..end,
++ });
++ }
++ None => {
++ *skipped += end.saturating_sub(at);
++ *start = None;
++ }
}
- Err(end) => {
- *skipped += end.saturating_sub(at);
- lx.pos = end;
- *start = None;
- operands.clear();
- }
- },
+ }
- operands.clear();
- }
- _ => {
- 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 });
+ _ => {
+ 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 });
+ }
}
}
}
diff --cc crates/content/src/tests.rs
index 094a0665d,c9abef834..f18aeaaec
--- a/crates/content/src/tests.rs
+++ b/crates/content/src/tests.rs
@@@ -142,12 -143,20 +143,23 @@@ fn filtered_unknown_and_damaged_inline_
b"/W 9223372036854775807 /H 9223372036854775807 /BPC 16 /CS /CMYK",
b"/W 9223372036854775807 /H 2 /BPC 8 /CS /G",
] {
+ // What follows the first `EI` (`!!~>`) does not read as content, so the renderer takes
+ // the later one.
let parsed = inline_pixels(parameters, b"! EI !!~>");
- assert_eq!(parsed.ops[1].inline.as_ref().unwrap().1, b"!", "{}", String::from_utf8_lossy(parameters));
+ let label = String::from_utf8_lossy(parameters);
+ assert_eq!(parsed.ops[1].inline.as_ref().unwrap().1, b"! EI !!~>", "{label}");
+ assert_eq!(parsed.ops.iter().map(|op| op.op.as_slice()).collect::<Vec<_>>(), [b"q".as_slice(), b"BI", b"Q"], "{label}");
+ assert_eq!(parsed.ambiguous_images, 0, "{label}");
}
- // A short payload still uses the tolerant recovery, including when there is no EI.
- for src in [b"BI /W 4 /H 1 /BPC 8 /CS /G ID abc\nEI Q".as_slice(), b"BI /W 4 /H 1 /BPC 8 /CS /G ID abc"] {
- assert_eq!(parse(src).ops[0].inline.as_ref().unwrap().1, b"abc");
+ // A short payload is read whole; without an `EI`, the renderer reads no image and this
+ // parser's end is a guess.
+ for (src, ambiguous) in [(b"BI /W 4 /H 1 /BPC 8 /CS /G ID abc\nEI Q".as_slice(), 0), (b"BI /W 4 /H 1 /BPC 8 /CS /G ID abc", 1)] {
+ let parsed = parse(src);
+ assert_eq!(parsed.ops[0].inline.as_ref().unwrap().1, b"abc");
+ assert_eq!(parsed.ambiguous_images, ambiguous);
++ let mut reader = ops(src);
++ reader.by_ref().for_each(drop);
++ assert_eq!(reader.ambiguous_images(), ambiguous, "the streaming reader counts it too");
}
}