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};
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    /// Follow a reference chain to a non-reference value, applying
135    /// §7.3.10's rules: an unresolvable reference yields `null` rather
136    /// than an error, and the chain is depth-guarded
137    /// ([`MAX_RESOLVE_DEPTH`]) so `5 0 obj 5 0 R endobj` — legal syntax
138    /// — cannot loop.
139    fn resolve<'a>(&'a self, obj: &'a Object) -> &'a Object {
140        const NULL: &Object = &Object::Null;
141        let mut current = obj;
142        for _ in 0..MAX_RESOLVE_DEPTH {
143            match current {
144                Object::Reference(id) => match self.value(*id) {
145                    Some(value) => current = value,
146                    None => return NULL,
147                },
148                other => return other,
149            }
150        }
151        NULL
152    }
153
154    /// Resolve `id` directly to a non-reference value, or `null`.
155    ///
156    /// Convenience for the very common *"I have an id, give me the
157    /// dictionary"* shape, which would otherwise need a temporary
158    /// [`Object::Reference`] to hand to [`ObjectGraph::resolve`] — and a
159    /// temporary cannot outlive the call, so the borrow does not
160    /// compile.
161    ///
162    /// Iterative, not recursive, and depth-guarded for the same reason
163    /// [`ObjectGraph::resolve`] is: `4 0 obj 4 0 R endobj` is legal
164    /// syntax, and a recursive implementation would answer it with a
165    /// stack overflow — which `pdfcer-core`'s panic-free policy forbids
166    /// on untrusted input just as firmly as it forbids an `unwrap`.
167    fn resolved(&self, id: ObjId) -> &Object {
168        const NULL: &Object = &Object::Null;
169        let mut current = id;
170        for _ in 0..MAX_RESOLVE_DEPTH {
171            match self.value(current) {
172                Some(Object::Reference(next)) => current = *next,
173                Some(other) => return other,
174                None => return NULL,
175            }
176        }
177        NULL
178    }
179
180    /// The document catalog (§7.7.2) — the dictionary the trailer's
181    /// `/Root` points at — or `None` if the file has no usable one.
182    ///
183    /// Returns `Option` rather than `Result` because every caller in the
184    /// structural-operations path already has its own error type and
185    /// maps this to a variant of it; a second error type in the middle
186    /// would only be unwrapped and rewrapped.
187    fn catalog_dict(&self) -> Option<&Dict> {
188        self.trailer_entry(b"Root")
189            .map(|root| self.resolve(root))
190            .and_then(Object::as_dict)
191    }
192
193    /// The object id the trailer's `/Root` names, if it is a reference.
194    ///
195    /// Needed separately from [`ObjectGraph::catalog_dict`] by anything
196    /// that must *write* the catalog back (structural operations all
197    /// do), because a dictionary borrowed out of the graph carries no
198    /// record of which object it came from.
199    fn catalog_id(&self) -> Option<ObjId> {
200        self.trailer_entry(b"Root").and_then(Object::as_reference)
201    }
202}
203
204/// The loaded file, as a graph.
205///
206/// `Document` already has inherent `resolve`/`catalog` methods with the
207/// same semantics; those keep working and keep winning method
208/// resolution (inherent methods are preferred), so this impl adds a
209/// generic entry point without changing a single existing call site.
210impl ObjectGraph for crate::document::Document {
211    fn value(&self, id: ObjId) -> Option<&Object> {
212        self.get(id).map(|io| &io.value)
213    }
214
215    fn trailer_entry(&self, key: &[u8]) -> Option<&Object> {
216        self.trailer().get(key)
217    }
218}
219
220#[cfg(test)]
221#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
222mod tests {
223    use super::*;
224    use crate::object::Name;
225    use std::collections::BTreeMap;
226
227    /// A minimal hand-built graph, so the trait's provided methods are
228    /// tested without dragging a parsed file in.
229    struct TestGraph {
230        objects: BTreeMap<ObjId, Object>,
231        trailer: Dict,
232    }
233
234    impl ObjectGraph for TestGraph {
235        fn value(&self, id: ObjId) -> Option<&Object> {
236            self.objects.get(&id)
237        }
238        fn trailer_entry(&self, key: &[u8]) -> Option<&Object> {
239            self.trailer.get(key)
240        }
241    }
242
243    fn graph() -> TestGraph {
244        let mut objects = BTreeMap::new();
245        let mut catalog = Dict::new();
246        catalog.insert(Name::from(b"Type"), Object::Name(Name::from(b"Catalog")));
247        objects.insert(ObjId::new(1, 0), Object::Dict(catalog));
248        // A two-hop chain: 2 -> 3 -> the integer.
249        objects.insert(ObjId::new(2, 0), Object::Reference(ObjId::new(3, 0)));
250        objects.insert(ObjId::new(3, 0), Object::Integer(42));
251        // A self-reference, which is legal syntax and must not loop.
252        objects.insert(ObjId::new(4, 0), Object::Reference(ObjId::new(4, 0)));
253        let mut trailer = Dict::new();
254        trailer.insert(Name::from(b"Root"), Object::Reference(ObjId::new(1, 0)));
255        TestGraph { objects, trailer }
256    }
257
258    #[test]
259    fn resolve_follows_chains_and_nulls_dangling() {
260        let g = graph();
261        assert_eq!(g.resolved(ObjId::new(2, 0)), &Object::Integer(42));
262        // §7.3.10: a reference to nothing is null, not an error.
263        assert_eq!(g.resolved(ObjId::new(99, 0)), &Object::Null);
264    }
265
266    #[test]
267    fn a_reference_cycle_resolves_to_null_rather_than_looping() {
268        let g = graph();
269        assert_eq!(g.resolved(ObjId::new(4, 0)), &Object::Null);
270        let cyclic = Object::Reference(ObjId::new(4, 0));
271        assert_eq!(g.resolve(&cyclic), &Object::Null);
272    }
273
274    #[test]
275    fn the_catalog_is_reached_through_the_trailer() {
276        let g = graph();
277        assert_eq!(g.catalog_id(), Some(ObjId::new(1, 0)));
278        assert!(g.catalog_dict().unwrap().contains_key(b"Type"));
279    }
280}