pdfcer_model/view.rs
1//! # `view` — "the document as it is right now", for every READ path
2//!
3//! This module is the answer to the defect recorded in
4//! `docs/decisions/018-edited-state-is-what-the-canvas-renders.md`: from
5//! Pass 3.1 through Pass 16.2 every editing feature wrote correctly into
6//! `EditSession`'s overlay, and **none of them
7//! were visible**, because the renderer and the vector object model both
8//! read `EditSession::document()` —
9//! whose own doc comment says *"this is the base revision, not the edited
10//! state."* One shared read path, fourteen invisible features.
11//!
12//! ## What a read path actually needs
13//!
14//! Reading a PDF page needs exactly two things, and they are separable:
15//!
16//! 1. **An object graph** — "what is object `12 0` right now?", "what does
17//! the trailer's `/Root` point at?". That is
18//! [`ObjectGraph`], and it has had two
19//! implementations since Pass 3.2: [`Document`](crate::document::Document)
20//! (the file as loaded) and
21//! `SessionGraph`/`EditSession`
22//! (the file as the operator currently has it).
23//! 2. **A byte source** — "give me the bytes this stream's
24//! [`ByteSpan`] covers". Every stream in pdfcer is span-backed rather
25//! than owning its payload, because that is what makes round-trip /
26//! minimal-diff editing possible at all (`ARCHITECTURE.md` §5,
27//! [`crate::span`]).
28//!
29//! [`DocumentView`] is that pair, plus the declared [`PdfVersion`]. It was
30//! originally introduced inside `pageops::assemble` (Pass 3.2) for
31//! extract/merge/split, which need to copy pages *out of* an open editing
32//! session. Decision 018 promotes it here because the renderer, the vector
33//! decomposer and the object-model provider need the identical abstraction
34//! — and because a type that three subsystems depend on should not live in
35//! the private corner of a fourth.
36//!
37//! ## Why the byte source is an ENUM and not a `&[u8]`
38//!
39//! For a plain [`Document`](crate::document::Document), the byte source is
40//! one contiguous buffer: the file as loaded. For an
41//! `EditSession` it is **two disjoint buffers**:
42//! the base file, plus the R45 staging buffer holding stream payloads the
43//! session has authored (dimension and markup appearance streams, spliced
44//! content streams). `EditSession::stage_bytes` (private) assigns those
45//! payloads spans in a **single combined coordinate system**:
46//!
47//! ```text
48//! span.start = base.len() + (offset within staging)
49//! ```
50//!
51//! so a span alone is enough to say which half it belongs to. There are
52//! three ways to serve such a span and only one of them is acceptable on a
53//! per-frame path:
54//!
55//! - `EditSession::authored_source`
56//! materializes `base ++ staging` as one buffer. Correct, and right for
57//! its once-per-operation `pageops` callers — but it is a `Cow::Owned`
58//! full memcpy of the whole file (~14 MB on decision 018's benchmark
59//! document). Calling it once per rendered frame is not an option.
60//! - Caching that concatenation inside the session costs one base-sized
61//! allocation plus invalidation logic, and buys nothing over the third
62//! option.
63//! - **[`StreamSource::Split`]** keeps the two halves borrowed and picks
64//! between them with one integer comparison. Zero copy, zero allocation,
65//! nothing to invalidate. That is what this module implements.
66//!
67//! ### The non-straddling invariant
68//!
69//! [`StreamSource::Split`]'s dispatch is only sound because **no span ever
70//! crosses the base/staging boundary**, and that is a structural property,
71//! not a hope:
72//!
73//! - A span with [`Provenance::File`](crate::object::Provenance::File) semantics — i.e. one
74//! parsed out of the base file — necessarily ends at or before
75//! `base.len()`, because it indexes bytes that came from that buffer.
76//! - A staged span necessarily starts at or after `base.len()`, because
77//! `EditSession::stage_bytes` computes `start = base.len() +
78//! staging.len()` *before* appending.
79//!
80//! A span that straddles is therefore a provenance bug, and
81//! [`StreamSource::slice`] answers it with `None` rather than splicing two
82//! unrelated buffers together — the `ARCHITECTURE.md` §10 fail-clean
83//! posture, and the same degradation [`ByteSpan::slice`] already uses for
84//! an out-of-bounds span. The invariant has its own regression test
85//! (`straddling_span_is_refused_not_spliced` below); if a future change to
86//! the staging offset scheme breaks it, that test fails loudly instead of
87//! the renderer quietly drawing garbage.
88//!
89//! ## ⚠️ `DocumentView` is a READ view. It must never become the writer's input.
90//!
91//! This prohibition is load-bearing enough that decision 018 §10 asks for
92//! it to live in the type's own documentation, and it is repeated on
93//! [`DocumentView`] itself. The short form: the writer's source of truth is
94//! `&Document` plus
95//! [`DirtySet::combined_source`](crate::writer::DirtySet::combined_source),
96//! and a future refactor that generalized `save_full`/`save_incremental`
97//! over `DocumentView` could mistake a session's [`StreamSource::Split`]
98//! for base bytes and splice staged payloads at base offsets. That is a
99//! **silent** violation of the §5 round-trip invariant — the saved file
100//! would be wrong and nothing would say so. Nothing the writer would need
101//! is implemented on this type, deliberately.
102//!
103//! ## Spec sources
104//!
105//! - `iso32000__s__7.3.10.md` — indirect objects and reference resolution
106//! (inherited wholesale from [`ObjectGraph`]'s provided methods).
107//! - `iso32000__s__7.3.8.md` — stream objects: the payload is bytes in the
108//! file, which is why a span + a buffer is the natural representation.
109
110use crate::PdfVersion;
111use crate::graph::ObjectGraph;
112use crate::object::{ObjId, Object};
113use crate::span::ByteSpan;
114
115/// Where a [`ByteSpan`] carried by a stream in some object graph resolves
116/// to actual bytes.
117///
118/// Two variants, because pdfcer has exactly two kinds of readable document
119/// (module docs): a loaded file, whose spans all index one buffer, and an
120/// editing session, whose spans index the base file **or** the R45 staging
121/// buffer under one combined coordinate system.
122///
123/// `Copy`, because it is a pair of shared borrows and threading it through
124/// a render walk by value is cheaper and clearer than by reference.
125///
126/// # Examples
127///
128/// ```
129/// use pdfcer_model::span::ByteSpan;
130/// use pdfcer_model::view::StreamSource;
131///
132/// let base = b"BASE-BYTES";
133/// let staged = b"STAGED";
134/// let src = StreamSource::Split { base, staged };
135///
136/// // A base-side span reads the base half.
137/// assert_eq!(src.slice(ByteSpan::new(0, 4)), Some(&b"BASE"[..]));
138/// // A staged span is expressed as `base.len() + local` (R45).
139/// assert_eq!(src.slice(ByteSpan::new(base.len(), 6)), Some(&b"STAGED"[..]));
140/// // A span that crosses the boundary is a provenance bug: refused.
141/// assert_eq!(src.slice(ByteSpan::new(base.len() - 1, 3)), None);
142/// ```
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub enum StreamSource<'a> {
145 /// One buffer: a plain [`Document`](crate::document::Document)'s
146 /// retained file bytes. Spans index it directly, exactly as
147 /// [`ByteSpan::slice`] does.
148 Contiguous(&'a [u8]),
149 /// Two disjoint buffers under one coordinate system: an
150 /// `EditSession`'s base file plus its R45
151 /// staging buffer.
152 ///
153 /// A span with `start < base.len()` belongs to `base`; a span with
154 /// `start >= base.len()` belongs to `staged` at local offset
155 /// `start - base.len()`. See the module docs for why a span can never
156 /// belong to both.
157 Split {
158 /// The base revision as loaded from disk.
159 base: &'a [u8],
160 /// Stream payloads authored this session, whose spans are offset
161 /// by `base.len()` (see
162 /// `EditSession::stage_bytes`).
163 staged: &'a [u8],
164 },
165}
166
167impl<'a> StreamSource<'a> {
168 /// The bytes `span` covers, or `None` if it cannot be served.
169 ///
170 /// `None` has exactly three causes, all of them logic errors rather
171 /// than data errors, and all of them degraded rather than panicked per
172 /// the crate's panic-free policy:
173 ///
174 /// 1. the span is out of bounds for the buffer it names;
175 /// 2. the span straddles the base/staging boundary (module docs —
176 /// structurally impossible today, refused so that it stays that
177 /// way);
178 /// 3. the span was produced against a *different* document's buffer.
179 ///
180 /// Callers turn `None` into their own named refusal — the renderer
181 /// counts it as an undecodable stream, `pageops` stages an empty
182 /// payload — rather than substituting plausible bytes.
183 #[must_use]
184 pub fn slice(&self, span: ByteSpan) -> Option<&'a [u8]> {
185 match *self {
186 Self::Contiguous(buf) => span.slice(buf),
187 Self::Split { base, staged } => {
188 if span.start >= base.len() {
189 // Wholly in the staged half. Re-express in staging-local
190 // coordinates; `checked_sub` cannot fail under the guard
191 // above but is used anyway so the arithmetic is total.
192 let local = span.start.checked_sub(base.len())?;
193 ByteSpan::new(local, span.len).slice(staged)
194 } else if span.end() <= base.len() {
195 // Wholly in the base half.
196 span.slice(base)
197 } else {
198 // Straddles. See the module docs: structurally
199 // impossible, refused rather than spliced.
200 None
201 }
202 }
203 }
204 }
205
206 /// Total addressable length of this source, in the span coordinate
207 /// system.
208 ///
209 /// Diagnostic only — used by [`DocumentView`]'s `Debug` and by tests
210 /// asserting the R45 offset scheme (see `EditSession::stage_bytes`). Deliberately NOT a way to get at a
211 /// buffer: there is no accessor returning the concatenation, because
212 /// materializing one is precisely the cost this type exists to avoid.
213 #[must_use]
214 pub const fn len(&self) -> usize {
215 match *self {
216 Self::Contiguous(buf) => buf.len(),
217 Self::Split { base, staged } => base.len().saturating_add(staged.len()),
218 }
219 }
220
221 /// Whether this source addresses no bytes at all.
222 #[must_use]
223 pub const fn is_empty(&self) -> bool {
224 self.len() == 0
225 }
226}
227
228/// A document to READ: its object graph, the byte source its stream spans
229/// resolve against, and the version it declares.
230///
231/// Built by [`Document::view`](crate::document::Document::view) (the file
232/// as loaded) or `EditSession::view` (the
233/// file as the operator currently has it). Every read path in pdfcer that
234/// can meaningfully run against either — the rasterizer, the vector object
235/// model, `pageops`' cross-document copier — takes one of these rather than
236/// a `&Document`, which is what makes "does this show unsaved edits?" a
237/// property of the *caller's choice of view* instead of a property
238/// scattered across fifty call sites.
239///
240/// # `impl ObjectGraph` is the whole trick
241///
242/// `DocumentView` implements [`ObjectGraph`] by delegating `value` and
243/// `trailer_entry` to the graph it wraps. Because `resolve`, `resolved`,
244/// `catalog_dict` and `catalog_id` are *provided* trait methods with
245/// signatures identical to [`Document`](crate::document::Document)'s
246/// inherent ones, changing a function's parameter from `&Document` to
247/// `&DocumentView<'_>` leaves its body untouched. Decision 018 measured
248/// this: 45 of `pdfcer-render`'s 50 `Document` call sites compiled
249/// unchanged. The only bodies that needed editing were the five
250/// `span.slice(doc.bytes())` sites, which became
251/// [`DocumentView::slice`].
252///
253/// # ⚠️ Read-only. Never hand this to the writer.
254///
255/// `docs/decisions/018` §10 hazard 1, restated where it cannot be missed:
256/// the writer's source of truth is `&Document` +
257/// [`DirtySet::combined_source`](crate::writer::DirtySet::combined_source).
258/// A `DocumentView` over an
259/// `EditSession` carries a
260/// [`StreamSource::Split`]; code that assumed it held base bytes would
261/// splice staged payloads at base offsets and emit a corrupt file with no
262/// error — a **silent** breach of the `ARCHITECTURE.md` §5 round-trip
263/// invariant, which is the worst failure mode this project has. Nothing
264/// the writer needs is implemented here, and nothing should be added.
265///
266/// # Examples
267///
268/// ```
269/// use pdfcer_model::document::Document;
270/// use pdfcer_model::graph::ObjectGraph;
271///
272/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
273/// let doc = Document::from_bytes(
274/// include_bytes!("../../../fixtures/synthetic/hello.pdf").to_vec(),
275/// )?;
276/// let view = doc.view();
277/// // The view answers graph questions exactly as the document does.
278/// assert_eq!(view.catalog_id(), doc.catalog_id());
279/// # Ok(())
280/// # }
281/// ```
282pub struct DocumentView<'a> {
283 graph: &'a dyn ObjectGraph,
284 source: StreamSource<'a>,
285 version: PdfVersion,
286}
287
288impl<'a> DocumentView<'a> {
289 /// Build a view whose stream spans index one contiguous `bytes`
290 /// buffer.
291 ///
292 /// This is the constructor every pre-decision-018 caller already uses
293 /// (`DocumentView::new(&doc, doc.bytes(), doc.version())`), kept with
294 /// its original signature so `pageops`, `pdfcer` and the page-op
295 /// tests are untouched by the promotion out of `pageops::assemble`.
296 ///
297 /// For an editing session use
298 /// `EditSession::view`, which builds
299 /// the [`StreamSource::Split`] form — passing
300 /// `session.document().bytes()` here would resolve authored appearance
301 /// spans off the end of the base buffer (the X5 failure the original
302 /// `DocumentView` doc comment was written to catch).
303 #[must_use]
304 pub const fn new(graph: &'a dyn ObjectGraph, bytes: &'a [u8], version: PdfVersion) -> Self {
305 Self {
306 graph,
307 source: StreamSource::Contiguous(bytes),
308 version,
309 }
310 }
311
312 /// Build a view over an explicit [`StreamSource`].
313 ///
314 /// The general constructor; [`DocumentView::new`] is the contiguous
315 /// special case. Used by
316 /// `EditSession::view` and by
317 /// [`DocumentView::clone_view`] to carry a source
318 /// through unchanged.
319 #[must_use]
320 pub const fn with_source(
321 graph: &'a dyn ObjectGraph,
322 source: StreamSource<'a>,
323 version: PdfVersion,
324 ) -> Self {
325 Self {
326 graph,
327 source,
328 version,
329 }
330 }
331
332 /// The object graph this view reads.
333 ///
334 /// Callers that already hold a `&DocumentView` should prefer the
335 /// [`ObjectGraph`] methods directly on the view (`view.resolve(…)`);
336 /// this accessor exists for the places that must pass a
337 /// `&dyn ObjectGraph` onward, such as `pageops`' copier.
338 #[must_use]
339 pub const fn graph(&self) -> &'a dyn ObjectGraph {
340 self.graph
341 }
342
343 /// The byte source this view's stream spans resolve against.
344 #[must_use]
345 pub const fn source(&self) -> StreamSource<'a> {
346 self.source
347 }
348
349 /// The bytes `span` covers in this view's source, or `None`.
350 ///
351 /// The replacement for the `span.slice(doc.bytes())` idiom. See
352 /// [`StreamSource::slice`] for what `None` means and why it is not a
353 /// panic.
354 #[must_use]
355 pub fn slice(&self, span: ByteSpan) -> Option<&'a [u8]> {
356 self.source.slice(span)
357 }
358
359 /// The single contiguous buffer this view's spans index, or `None`
360 /// when the view is over an editing session and therefore has two.
361 ///
362 /// Kept (per decision 018 §8) for callers that genuinely need a whole
363 /// buffer rather than one span's worth of it, but returning `Option`
364 /// rather than the pre-018 `&[u8]`: for a
365 /// [`StreamSource::Split`] view there is no such buffer, and any
366 /// answer other than "there isn't one" would be the X5 mis-slice
367 /// hazard wearing a plausible face. Prefer [`DocumentView::slice`],
368 /// which works for both shapes.
369 #[must_use]
370 pub const fn bytes(&self) -> Option<&'a [u8]> {
371 match self.source {
372 StreamSource::Contiguous(buf) => Some(buf),
373 StreamSource::Split { .. } => None,
374 }
375 }
376
377 /// The version this view's document declares (§7.5.2 / the catalog's
378 /// `/Version` override).
379 #[must_use]
380 pub const fn version(&self) -> PdfVersion {
381 self.version
382 }
383}
384
385/// Delegating impl — the mechanism that let decision 018 change 27
386/// function signatures without touching 45 call-site bodies (type docs).
387impl ObjectGraph for DocumentView<'_> {
388 fn value(&self, id: ObjId) -> Option<&Object> {
389 self.graph.value(id)
390 }
391
392 fn trailer_entry(&self, key: &[u8]) -> Option<&Object> {
393 self.graph.trailer_entry(key)
394 }
395}
396
397impl std::fmt::Debug for DocumentView<'_> {
398 /// Hand-written because `&dyn ObjectGraph` is not `Debug` and adding
399 /// that bound would infect every implementor for the sake of one
400 /// derive. Prints the facts a debugging session actually wants —
401 /// including which *shape* of source this is, since "why is my edit
402 /// invisible?" is answered by exactly that.
403 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
404 f.debug_struct("DocumentView")
405 .field("version", &self.version)
406 .field("source", &self.source)
407 .field("source_len", &self.source.len())
408 .finish()
409 }
410}
411
412impl DocumentView<'_> {
413 /// A second handle on the same borrowed document.
414 ///
415 /// `DocumentView` is a pair of shared borrows and is therefore
416 /// trivially copyable in principle; it is not `Clone`-derived because
417 /// `&dyn ObjectGraph` blocks the derive's bounds. This is the manual
418 /// equivalent, and exists so `pageops::insert` can put the same view into a
419 /// slice twice-shaped API without the caller pre-building one.
420 ///
421 /// Carries the [`crate::view::StreamSource`] through as-is rather than
422 /// going via `bytes()`, so a view over an editing session copies as a
423 /// session view (decision 018 §4); reconstructing it from a single
424 /// buffer would be the X5 mis-slice.
425 #[must_use]
426 pub const fn clone_view(&self) -> DocumentView<'_> {
427 DocumentView::with_source(self.graph(), self.source(), self.version())
428 }
429}
430
431#[cfg(test)]
432#[allow(
433 clippy::unwrap_used,
434 clippy::expect_used,
435 clippy::panic,
436 clippy::indexing_slicing
437)]
438mod tests {
439 use super::*;
440 use crate::object::{Dict, Name};
441 use std::collections::BTreeMap;
442
443 /// A hand-built graph, so the delegation is tested without dragging a
444 /// parsed file in (mirrors `graph.rs`'s own `TestGraph`).
445 struct TestGraph {
446 objects: BTreeMap<ObjId, Object>,
447 trailer: Dict,
448 }
449
450 impl ObjectGraph for TestGraph {
451 fn value(&self, id: ObjId) -> Option<&Object> {
452 self.objects.get(&id)
453 }
454 fn trailer_entry(&self, key: &[u8]) -> Option<&Object> {
455 self.trailer.get(key)
456 }
457 }
458
459 fn graph() -> TestGraph {
460 let mut objects = BTreeMap::new();
461 let mut catalog = Dict::new();
462 catalog.insert(Name::from(b"Type"), Object::Name(Name::from(b"Catalog")));
463 objects.insert(ObjId::new(1, 0), Object::Dict(catalog));
464 objects.insert(ObjId::new(2, 0), Object::Integer(7));
465 let mut trailer = Dict::new();
466 trailer.insert(Name::from(b"Root"), Object::Reference(ObjId::new(1, 0)));
467 TestGraph { objects, trailer }
468 }
469
470 #[test]
471 fn contiguous_source_slices_like_a_plain_buffer() {
472 let src = StreamSource::Contiguous(b"hello world");
473 assert_eq!(src.slice(ByteSpan::new(6, 5)), Some(&b"world"[..]));
474 assert_eq!(src.slice(ByteSpan::new(6, 99)), None);
475 assert_eq!(src.len(), 11);
476 }
477
478 #[test]
479 fn split_source_dispatches_on_the_base_length() {
480 let base = b"0123456789";
481 let staged = b"ABCDEF";
482 let src = StreamSource::Split { base, staged };
483
484 // Base half.
485 assert_eq!(src.slice(ByteSpan::new(2, 3)), Some(&b"234"[..]));
486 // Exactly the base half.
487 assert_eq!(src.slice(ByteSpan::new(0, 10)), Some(&base[..]));
488 // Staged half, in the R45 combined coordinate system.
489 assert_eq!(src.slice(ByteSpan::new(10, 6)), Some(&b"ABCDEF"[..]));
490 assert_eq!(src.slice(ByteSpan::new(13, 2)), Some(&b"DE"[..]));
491 // Past the staged half.
492 assert_eq!(src.slice(ByteSpan::new(14, 9)), None);
493 assert_eq!(src.len(), 16);
494 }
495
496 /// The invariant decision 018 §4 owes a test: no span may cross the
497 /// base/staging boundary, and one that does is REFUSED rather than
498 /// spliced out of two unrelated buffers.
499 ///
500 /// This exists so that a future change to
501 /// `EditSession::stage_bytes`' offset
502 /// scheme fails loudly here instead of silently producing a stream
503 /// payload with a seam in the middle of it.
504 #[test]
505 fn straddling_span_is_refused_not_spliced() {
506 let base = b"0123456789";
507 let staged = b"ABCDEF";
508 let src = StreamSource::Split { base, staged };
509
510 // Starts inside base, ends inside staged: impossible by
511 // construction, refused on principle.
512 assert_eq!(src.slice(ByteSpan::new(9, 3)), None);
513 assert_eq!(src.slice(ByteSpan::new(0, 16)), None);
514 // The two adjacent NON-straddling spans both resolve, so the
515 // refusal above is about crossing, not about the neighbourhood.
516 assert_eq!(src.slice(ByteSpan::new(9, 1)), Some(&b"9"[..]));
517 assert_eq!(src.slice(ByteSpan::new(10, 1)), Some(&b"A"[..]));
518 }
519
520 /// A zero-length span sitting exactly on the boundary is served by
521 /// the staged half (`start >= base.len()`) and yields the empty
522 /// slice — not `None`, because nothing is out of bounds about it.
523 #[test]
524 fn empty_span_at_the_boundary_is_served_not_refused() {
525 let src = StreamSource::Split {
526 base: b"0123456789",
527 staged: b"ABCDEF",
528 };
529 assert_eq!(src.slice(ByteSpan::new(10, 0)), Some(&b""[..]));
530 }
531
532 /// An empty staging buffer (a session that has authored nothing)
533 /// behaves exactly like the contiguous case over the base.
534 #[test]
535 fn split_with_empty_staging_matches_contiguous() {
536 let base = b"0123456789";
537 let split = StreamSource::Split { base, staged: b"" };
538 let contiguous = StreamSource::Contiguous(base);
539 for start in 0..base.len() {
540 for len in 0..=(base.len() - start) {
541 let span = ByteSpan::new(start, len);
542 assert_eq!(split.slice(span), contiguous.slice(span), "{span}");
543 }
544 }
545 }
546
547 #[test]
548 fn the_view_delegates_every_graph_question() {
549 let g = graph();
550 let view = DocumentView::new(&g, b"", PdfVersion { major: 1, minor: 7 });
551 assert_eq!(view.value(ObjId::new(2, 0)), Some(&Object::Integer(7)));
552 assert_eq!(view.resolved(ObjId::new(2, 0)), &Object::Integer(7));
553 assert_eq!(view.catalog_id(), Some(ObjId::new(1, 0)));
554 assert!(view.catalog_dict().is_some());
555 // §7.3.10 through the delegation: a dangling id is null, not an
556 // error, exactly as it is on the underlying graph.
557 assert_eq!(view.resolved(ObjId::new(99, 0)), &Object::Null);
558 }
559
560 #[test]
561 fn bytes_is_none_for_a_split_view() {
562 let g = graph();
563 let contiguous = DocumentView::new(&g, b"abc", PdfVersion { major: 1, minor: 7 });
564 assert_eq!(contiguous.bytes(), Some(&b"abc"[..]));
565
566 let split = DocumentView::with_source(
567 &g,
568 StreamSource::Split {
569 base: b"abc",
570 staged: b"de",
571 },
572 PdfVersion { major: 1, minor: 7 },
573 );
574 assert_eq!(
575 split.bytes(),
576 None,
577 "a split view has no single buffer; answering with one would be the X5 mis-slice"
578 );
579 assert_eq!(split.slice(ByteSpan::new(3, 2)), Some(&b"de"[..]));
580 }
581}