Skip to main content

pdfcer_model/
graph.rs

1//! # `ObjectGraph` — one read view over "the document as it is right now"
2//!
3//! Pass 3.1 could get away without this. Pass 3.2 cannot, and the reason
4//! is recorded verbatim in `pdfcer_core::edit`'s own module docs:
5//!
6//! > ⚠️ Pass 3.2 must replace this with an overlay-aware walk. The moment
7//! > an edit can add or remove a `Kids` entry, patching a base-derived
8//! > list is not an approximation — it is **wrong**.
9//!
10//! Pass 3.1's mutations (`/Info`, `/Rotate`) changed dictionary *values*
11//! only, so [`crate::page_tree::pages`] could walk the **base** document
12//! and then patch each leaf's rotation from the overlay. A structural
13//! operation changes the page tree's *shape*: after a delete, the base
14//! walk still returns the deleted page; after a reorder, it returns the
15//! old order. Patching cannot fix either.
16//!
17//! ## The shape of the fix, and why it is a trait
18//!
19//! Every consumer of the object graph — the page-tree walk, the outline
20//! walk, the cross-document copier, the dangling-reference census —
21//! needs exactly three primitives:
22//!
23//! 1. fetch an indirect object by identity;
24//! 2. follow a reference chain to a non-reference value (§7.3.10);
25//! 3. read a trailer entry (in practice only `/Root`).
26//!
27//! [`Document`](crate::document::Document) provides all three, and so
28//! does an `EditSession` *with its overlay
29//! applied*. Making that a trait rather than duplicating each walk means
30//! there is exactly **one** page-tree walk in pdfcer, and it is
31//! automatically correct for both views. A second copy specialised to
32//! sessions is precisely the kind of drift that eventually renders a
33//! deleted page.
34//!
35//! ## Why the resolution rules live here as provided methods
36//!
37//! §7.3.10's rules — dangling reference yields `null` and *"shall not be
38//! considered an error"*, a generation mismatch is a dangling reference,
39//! a reference chain is depth-guarded — are **spec behaviour, not view
40//! behaviour**. Implementing them once as provided methods on the trait
41//! makes it impossible for a new view to get them subtly different; an
42//! implementor supplies only [`ObjectGraph::value`] and
43//! [`ObjectGraph::trailer_entry`], which are the parts that genuinely
44//! differ.
45//!
46//! ## Spec sources
47//!
48//! - `iso32000__s__7.3.10.md` — indirect objects, dangling references,
49//!   substitutability
50//! - `iso32000__s__7.7.2.md` — the document catalog, reached via the
51//!   trailer's `/Root`
52
53use crate::document::MAX_RESOLVE_DEPTH;
54use crate::object::{Dict, ObjId, Object, Stream};
55
56/// A read-only view of one PDF document's object graph.
57///
58/// Implemented by [`Document`](crate::document::Document) (the file as
59/// loaded) and by `EditSession`'s overlay
60/// view (the file as the operator currently has it). See the module
61/// docs for why this exists at all.
62///
63/// # Examples
64///
65/// ```
66/// use pdfcer_model::document::Document;
67/// use pdfcer_model::graph::ObjectGraph;
68///
69/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
70/// let doc = Document::from_bytes(
71///     include_bytes!("../../../fixtures/synthetic/hello.pdf").to_vec(),
72/// )?;
73/// // The catalog is reached through the trailer's /Root, whichever
74/// // view is doing the reaching.
75/// assert!(doc.catalog_dict().is_some());
76/// # Ok(())
77/// # }
78/// ```
79///
80/// # Thread safety — why this trait requires `Send + Sync`
81///
82/// **The bound exists so a page can be rasterized off the UI thread.**
83/// A GUI that rasterizes inline freezes for the length of the render,
84/// and on a real CAD sheet that is ~10 s at 1× and ~58 s at 2× — not a
85/// slow redraw but a dead application, with no repaint, no progress and
86/// no way to cancel. Moving that work to a worker requires the rendered
87/// value to cross a thread boundary, and
88/// [`DocumentView`](crate::view::DocumentView) is what crosses.
89///
90/// **Only the trait object was ever the obstacle.** `Document`,
91/// `EditSession`, `SessionGraph`, `PendingGraph` and the test graphs
92/// were all already thread-safe; `DocumentView<'a>` holds
93/// `&'a dyn ObjectGraph`, and an unbounded `dyn Trait` is neither
94/// `Send` nor `Sync` regardless of what implements it. Adding the
95/// supertrait compiled with **zero errors** across the workspace — it
96/// records a property every implementor already had rather than
97/// imposing a new one.
98///
99/// **Why now.** Adding a supertrait bound to a public trait is a
100/// breaking change for downstream implementors. pdfcer has no remote and
101/// no release (`LEGAL.md` rule 8 — publishing awaits an explicit
102/// go-ahead), so the set of affected implementors is exactly the ones
103/// in this repository, and it is empty. This is the cheapest moment
104/// this bound will ever have.
105///
106/// **The cost, stated.** Any future `ObjectGraph` implementor must be
107/// thread-safe. That forecloses one holding an `Rc`, a `RefCell`, or a
108/// non-thread-safe foreign handle. Rust API guideline **`C-SEND-SYNC`**
109/// asks for types to be `Send`/`Sync` where possible and for deliberate
110/// exceptions to be documented; an object graph is plain data behind an
111/// accessor, so an implementor that could not meet this would be the
112/// surprising one.
113pub trait ObjectGraph: Send + Sync {
114    // ^^^^^^^^^^^^ Added 2026-08-07. See the `# Thread safety` section
115    // in this trait's doc comment above for why, and why now.
116
117    /// The current value of `id`, or `None` when this view has no such
118    /// object.
119    ///
120    /// "No such object" folds together every §7.3.10/§7.5.4 way an id
121    /// can fail to resolve — never defined, freed, or named with a
122    /// stale generation — because they are indistinguishable to a
123    /// reader and the spec gives them one outcome.
124    fn value(&self, id: ObjId) -> Option<&Object>;
125
126    /// The current value of the trailer entry `key`, or `None`.
127    ///
128    /// Only `/Root` is consulted by anything in this crate today, but
129    /// the accessor is general because an overlay view must be able to
130    /// answer for a trailer the operator has patched (creating `/Info`
131    /// is already such a patch, from Pass 3.1).
132    fn trailer_entry(&self, key: &[u8]) -> Option<&Object>;
133
134    /// The raw (still-encoded) data of `stream`, an object of this graph,
135    /// or `None` when this graph cannot serve stream bytes.
136    ///
137    /// The default is `None`: a graph of values alone has no byte source.
138    /// [`crate::document::Document`], [`crate::view::DocumentView`] and an
139    /// editing session override it, so a walk generic over the graph can
140    /// read a value the format allows as either a string or a stream
141    /// (a §12.7.3.4 `/RV` text stream).
142    fn stream_raw(&self, stream: &Stream) -> Option<&[u8]> {
143        let _ = stream;
144        None
145    }
146
147    /// Follow a reference chain to a non-reference value, applying
148    /// §7.3.10's rules: an unresolvable reference yields `null` rather
149    /// than an error, and the chain is depth-guarded
150    /// ([`MAX_RESOLVE_DEPTH`]) so `5 0 obj 5 0 R endobj` — legal syntax
151    /// — cannot loop.
152    fn resolve<'a>(&'a self, obj: &'a Object) -> &'a Object {
153        const NULL: &Object = &Object::Null;
154        let mut current = obj;
155        for _ in 0..MAX_RESOLVE_DEPTH {
156            match current {
157                Object::Reference(id) => match self.value(*id) {
158                    Some(value) => current = value,
159                    None => return NULL,
160                },
161                other => return other,
162            }
163        }
164        NULL
165    }
166
167    /// Resolve `id` directly to a non-reference value, or `null`.
168    ///
169    /// Convenience for the very common *"I have an id, give me the
170    /// dictionary"* shape, which would otherwise need a temporary
171    /// [`Object::Reference`] to hand to [`ObjectGraph::resolve`] — and a
172    /// temporary cannot outlive the call, so the borrow does not
173    /// compile.
174    ///
175    /// Iterative, not recursive, and depth-guarded for the same reason
176    /// [`ObjectGraph::resolve`] is: `4 0 obj 4 0 R endobj` is legal
177    /// syntax, and a recursive implementation would answer it with a
178    /// stack overflow — which `pdfcer-core`'s panic-free policy forbids
179    /// on untrusted input just as firmly as it forbids an `unwrap`.
180    fn resolved(&self, id: ObjId) -> &Object {
181        const NULL: &Object = &Object::Null;
182        let mut current = id;
183        for _ in 0..MAX_RESOLVE_DEPTH {
184            match self.value(current) {
185                Some(Object::Reference(next)) => current = *next,
186                Some(other) => return other,
187                None => return NULL,
188            }
189        }
190        NULL
191    }
192
193    /// The document catalog (§7.7.2) — the dictionary the trailer's
194    /// `/Root` points at — or `None` if the file has no usable one.
195    ///
196    /// Returns `Option` rather than `Result` because every caller in the
197    /// structural-operations path already has its own error type and
198    /// maps this to a variant of it; a second error type in the middle
199    /// would only be unwrapped and rewrapped.
200    fn catalog_dict(&self) -> Option<&Dict> {
201        self.trailer_entry(b"Root")
202            .map(|root| self.resolve(root))
203            .and_then(Object::as_dict)
204    }
205
206    /// The object id the trailer's `/Root` names, if it is a reference.
207    ///
208    /// Needed separately from [`ObjectGraph::catalog_dict`] by anything
209    /// that must *write* the catalog back (structural operations all
210    /// do), because a dictionary borrowed out of the graph carries no
211    /// record of which object it came from.
212    fn catalog_id(&self) -> Option<ObjId> {
213        self.trailer_entry(b"Root").and_then(Object::as_reference)
214    }
215}
216
217/// The loaded file, as a graph.
218///
219/// `Document` already has inherent `resolve`/`catalog` methods with the
220/// same semantics; those keep working and keep winning method
221/// resolution (inherent methods are preferred), so this impl adds a
222/// generic entry point without changing a single existing call site.
223impl ObjectGraph for crate::document::Document {
224    fn value(&self, id: ObjId) -> Option<&Object> {
225        self.get(id).map(|io| &io.value)
226    }
227
228    fn trailer_entry(&self, key: &[u8]) -> Option<&Object> {
229        self.trailer().get(key)
230    }
231
232    fn stream_raw(&self, stream: &Stream) -> Option<&[u8]> {
233        stream.data_span.slice(self.bytes())
234    }
235}
236
237#[cfg(test)]
238#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
239mod tests {
240    use super::*;
241    use crate::object::Name;
242    use std::collections::BTreeMap;
243
244    /// A minimal hand-built graph, so the trait's provided methods are
245    /// tested without dragging a parsed file in.
246    struct TestGraph {
247        objects: BTreeMap<ObjId, Object>,
248        trailer: Dict,
249    }
250
251    impl ObjectGraph for TestGraph {
252        fn value(&self, id: ObjId) -> Option<&Object> {
253            self.objects.get(&id)
254        }
255        fn trailer_entry(&self, key: &[u8]) -> Option<&Object> {
256            self.trailer.get(key)
257        }
258    }
259
260    fn graph() -> TestGraph {
261        let mut objects = BTreeMap::new();
262        let mut catalog = Dict::new();
263        catalog.insert(Name::from(b"Type"), Object::Name(Name::from(b"Catalog")));
264        objects.insert(ObjId::new(1, 0), Object::Dict(catalog));
265        // A two-hop chain: 2 -> 3 -> the integer.
266        objects.insert(ObjId::new(2, 0), Object::Reference(ObjId::new(3, 0)));
267        objects.insert(ObjId::new(3, 0), Object::Integer(42));
268        // A self-reference, which is legal syntax and must not loop.
269        objects.insert(ObjId::new(4, 0), Object::Reference(ObjId::new(4, 0)));
270        let mut trailer = Dict::new();
271        trailer.insert(Name::from(b"Root"), Object::Reference(ObjId::new(1, 0)));
272        TestGraph { objects, trailer }
273    }
274
275    #[test]
276    fn resolve_follows_chains_and_nulls_dangling() {
277        let g = graph();
278        assert_eq!(g.resolved(ObjId::new(2, 0)), &Object::Integer(42));
279        // §7.3.10: a reference to nothing is null, not an error.
280        assert_eq!(g.resolved(ObjId::new(99, 0)), &Object::Null);
281    }
282
283    #[test]
284    fn a_reference_cycle_resolves_to_null_rather_than_looping() {
285        let g = graph();
286        assert_eq!(g.resolved(ObjId::new(4, 0)), &Object::Null);
287        let cyclic = Object::Reference(ObjId::new(4, 0));
288        assert_eq!(g.resolve(&cyclic), &Object::Null);
289    }
290
291    #[test]
292    fn the_catalog_is_reached_through_the_trailer() {
293        let g = graph();
294        assert_eq!(g.catalog_id(), Some(ObjId::new(1, 0)));
295        assert!(g.catalog_dict().unwrap().contains_key(b"Type"));
296    }
297}