PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
fix(cos): find endstream once per document, not once per stream
aionggb1224557058a
diff --git a/crates/cos/src/document.rs b/crates/cos/src/document.rsindex 96975eb36..b783a8245 100644--- a/crates/cos/src/document.rs+++ b/crates/cos/src/document.rs@@ -10,7 +10,7 @@ use std::sync::{Arc, Mutex, Weak};use crate::CosError;use crate::object::{Dict, ObjRef, Object};-use crate::parser::{Lexer, is_whitespace, parse_indirect, parse_indirect_shared};+use crate::parser::{EndstreamIndex, Lexer, is_whitespace, parse_indirect, parse_indirect_shared};thread_local! {/// The objects being loaded on this thread, innermost last (see `Document::try_get`).@@ -405,6 +405,8 @@ impl std::fmt::Debug for ReadState {#[derive(Clone)]pub struct Document {data: Arc<Vec<u8>>,+ /// Where `endstream` occurs in `data`; see [`EndstreamIndex`].+ endstreams: Arc<EndstreamIndex>,source_identity: Arc<()>,entries: Arc<XrefIndex>,trailer: Dict,@@ -536,6 +538,7 @@ impl Document {pub fn new_empty() -> Self {let mut doc = Document {data: Arc::new(Vec::new()),+ endstreams: Arc::default(),source_identity: Arc::new(()),entries: Arc::new(XrefIndex::empty()),trailer: Dict::new(),@@ -618,6 +621,7 @@ impl Document {};let mut doc = Document {data,+ endstreams: Arc::default(),source_identity: Arc::new(()),entries: Arc::new(XrefIndex::empty()),trailer: Dict::new(),@@ -982,7 +986,7 @@ impl Document {match self.xref_entry(num) {None | Some(XrefEntry::Free { .. }) => true,Some(XrefEntry::InFile { offset, .. }) => {- let at = |off: usize| matches!(parse_indirect_shared(&self.data, off, &|_| None), Ok((id, _)) if id.num == num);+ let at = |off: usize| matches!(parse_indirect_shared(&self.data, off, &|_| None, &self.endstreams), Ok((id, _)) if id.num == num);// Offsets may count from a header that does not start the file.usize::try_from(offset).is_ok_and(|off| at(off) || (self.header_offset != 0 && at(off.saturating_add(self.header_offset))))}@@ -1180,7 +1184,7 @@ impl Document {length};let off = offset as usize;- let at = |off: usize| match parse_indirect_shared(&self.data, off, &resolve) {+ let at = |off: usize| match parse_indirect_shared(&self.data, off, &resolve, &self.endstreams) {Ok((id, o)) if id.num == num => Some(self.decrypted(id, o)),_ => None,};@@ -1246,7 +1250,7 @@ impl Document {if p > 0 && !is_whitespace(data[p - 1]) {continue;}- if let Ok((id, o)) = parse_indirect_shared(data, p, &|_| None)+ if let Ok((id, o)) = parse_indirect_shared(data, p, &|_| None, &self.endstreams)&& id.num == num{found = Some((id, o)); // keep the last (newest) definition@@ -2055,7 +2059,7 @@ impl Document {if trailer.as_ref().is_some_and(|((catalog, p), _)| *catalog && *p > at) {continue;}- if let Ok((_, Object::Stream(s))) = parse_indirect_shared(&data, at, &|_| None)+ if let Ok((_, Object::Stream(s))) = parse_indirect_shared(&data, at, &|_| None, &self.endstreams)&& s.dict.name(b"Type") == Some(b"XRef")&& let Some(r) = rank(at, &s.dict)&& trailer.as_ref().is_none_or(|(best, _)| r > *best)@@ -2997,6 +3001,33 @@ endobj}}+ #[test]+ fn streams_without_length_share_one_endstream_search() {+ let n = 2_000;+ let mut file = b"%PDF-1.7\n".to_vec();+ for k in 1..=n {+ file.extend_from_slice(format!("{k} 0 obj\n<< >>\nstream\nxx\n").as_bytes());+ }+ file.extend_from_slice(b"endstream\nendobj\n");+ file.extend_from_slice(+ format!(+ "{0} 0 obj\n<< /Type /Catalog /Pages {1} 0 R >>\nendobj\n{1} 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n",+ n + 1,+ n + 2+ )+ .as_bytes(),+ );+ file.extend_from_slice(format!("trailer\n<< /Root {} 0 R /Size {} >>\n%%EOF\n", n + 1, n + 3).as_bytes());+ let len = file.len();+ crate::parser::ENDSTREAM_SCAN.with(|c| c.set(0));+ let doc = Document::open(Arc::new(file)).unwrap();+ for k in [1, n / 2, n] {+ assert!(matches!(doc.try_get(k).as_deref(), Ok(Object::Stream(_))), "object {k}");+ }+ let scanned = crate::parser::ENDSTREAM_SCAN.with(|c| c.get());+ assert!(scanned <= 4 * len, "{scanned} bytes searched in a {len}-byte file");+ }+#[test]fn editor_cache_counts_deeply_nested_strings() {let mut nested = Object::String(crate::PdfString::literal(vec![b'x'; 1 << 20]));diff --git a/crates/cos/src/parser.rs b/crates/cos/src/parser.rsindex a16ff10c3..b470cffa4 100644--- a/crates/cos/src/parser.rs+++ b/crates/cos/src/parser.rs@@ -368,6 +368,8 @@ fn real_prefix_len(s: &[u8]) -> usize {#[cfg(test)]thread_local! {+ /// Bytes searched for `endstream` on this thread.+ pub(crate) static ENDSTREAM_SCAN: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };/// Bytes handed to number conversion on this thread.static NUMBER_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };}@@ -390,17 +392,30 @@ fn hexval(b: u8) -> Option<u8> {/// Parse an indirect object at `offset`: `N G obj <object> [stream…endstream] endobj`./// `resolve_length` resolves an indirect `/Length`. Returns the object and its (num, gen).pub fn parse_indirect(data: &[u8], offset: usize, resolve_length: &dyn Fn(ObjRef) -> Option<i64>) -> Result<(ObjRef, Object), CosError> {- parse_indirect_in(data, None, offset, resolve_length)+ parse_indirect_in(data, None, offset, resolve_length, None)}/// [`parse_indirect`] for a document's own bytes: stream data points into `data` instead of/// being copied out of it.+/// `endstreams` is the document's [`EndstreamIndex`] for `data`.pub(crate) fn parse_indirect_shared(data: &Arc<Vec<u8>>,offset: usize,resolve_length: &dyn Fn(ObjRef) -> Option<i64>,+ endstreams: &EndstreamIndex,) -> Result<(ObjRef, Object), CosError> {- parse_indirect_in(data, Some(data), offset, resolve_length)+ parse_indirect_in(data, Some(data), offset, resolve_length, Some(endstreams))+}++/// Where `endstream` occurs in a document's bytes, found once, the first time a stream's+/// /Length is wrong or missing. Searching the rest of the file for each such stream instead+/// makes many of them ending at one late `endstream` quadratic to read.+pub(crate) type EndstreamIndex = std::sync::OnceLock<Vec<usize>>;++fn endstream_offsets(data: &[u8]) -> Vec<usize> {+ #[cfg(test)]+ ENDSTREAM_SCAN.with(|c| c.set(c.get() + data.len()));+ data.windows(9).enumerate().filter(|(_, w)| *w == b"endstream").map(|(i, _)| i).collect()}fn parse_indirect_in(@@ -408,6 +423,7 @@ fn parse_indirect_in(shared: Option<&Arc<Vec<u8>>>,offset: usize,resolve_length: &dyn Fn(ObjRef) -> Option<i64>,+ endstreams: Option<&EndstreamIndex>,) -> Result<(ObjRef, Object), CosError> {let mut lx = Lexer::new(data, offset);lx.skip_ws();@@ -467,7 +483,11 @@ fn parse_indirect_in(let len = match declared {Some(l) if valid(l) => l as usize,// Wrong or missing /Length: search for "endstream" (§7.3.8.1 recovery).- _ => find_endstream(data, start).ok_or_else(|| CosError::Syntax { offset: start, detail: "stream without endstream".into() })? - start,+ _ => {+ find_endstream(data, start, endstreams)+ .ok_or_else(|| CosError::Syntax { offset: start, detail: "stream without endstream".into() })?+ - start+ }};let range = start..start + len;let raw = match shared {@@ -483,9 +503,20 @@ fn parse_indirect_in(}/// Offset where stream data ends (before the EOL preceding "endstream").-fn find_endstream(data: &[u8], from: usize) -> Option<usize> {- let hay = data.get(from..)?;- let at = hay.windows(9).position(|w| w == b"endstream")? + from;+fn find_endstream(data: &[u8], from: usize, endstreams: Option<&EndstreamIndex>) -> Option<usize> {+ let at = match endstreams {+ Some(index) => {+ let index = index.get_or_init(|| endstream_offsets(data));+ index.get(index.partition_point(|&p| p < from)).copied()?+ }+ None => {+ let hay = data.get(from..)?;+ let found = hay.windows(9).position(|w| w == b"endstream");+ #[cfg(test)]+ ENDSTREAM_SCAN.with(|c| c.set(c.get() + found.map_or(hay.len(), |p| p + 9)));+ found? + from+ }+ };let mut end = at;if end > from && data[end - 1] == b'\n' {end -= 1;