Skip to main content

pdfcer_model/
object.rs

1//! # COS object model (ISO 32000-1 §7.3)
2//!
3//! The value types of the Carousel Object System — the tree every PDF
4//! is made of. Spec sources: `iso32000__s__7.3.md` (the eight basic
5//! types, dictionary semantics, null), `iso32000__s__7.3.10.md`
6//! (indirect objects and references), `iso32000__s__7.3.8.md` (streams)
7//! in the PDF-spec RAG. Clause numbers are ISO 32000-1:2008.
8//!
9//! ## ONE object model (named invariant)
10//!
11//! This is the **only** object representation in pdfcer-core: the parse
12//! result and the write source are the same types
13//! (docs/decisions/001-oxidize-pdf-adopt-vs-build.md §6.1 item 3,
14//! recorded in ARCHITECTURE.md §12). The audited failure mode this
15//! prevents: a read-only parser model plus a separate builder-only
16//! generation model whose bridge never gets built, making round-trip
17//! structurally impossible. Any future "builder" convenience API must
18//! construct *these* types.
19//!
20//! ## Value semantics vs provenance
21//!
22//! `Object` is a plain value tree — no spans inside it. Provenance
23//! lives one level up: an [`IndirectObject`] records *where its
24//! definition physically lives* as a [`Provenance`], and re-emission of
25//! logically-untouched objects works from that (`crate::span`;
26//! ARCHITECTURE.md §5). Within an object the operator *did* modify,
27//! re-serialization from values is correct — §5 demands byte-identity
28//! only for what was NOT touched. (Content streams get a finer-grained
29//! span-per-token model in their own module, per decision 001 §6.1
30//! item 2 — that is deliberately NOT this tree.)
31//!
32//! Provenance is an **enum, not a span**, because PDF 1.5's object
33//! streams (§7.5.7) create objects that have no byte range of their own
34//! in the file — see [`Provenance`] for the full reasoning.
35//!
36//! ## Normative behaviors encoded here
37//!
38//! - **`null`-valued dictionary entry ≡ absent entry** (§7.3.7/§7.3.9):
39//!   collapsed in [`Dict::get`] — one accessor, not a check at every
40//!   call site.
41//! - **Duplicate keys are malformed** (§7.3.7 "shall not") — the parser
42//!   rejects them at parse time (fail-clean), so `Dict` never holds
43//!   duplicates from a parsed file.
44//! - **Integer vs real is preserved** (§7.3.3): two variants, never
45//!   collapsed to f64 — `4` and `4.0` are different tokens with
46//!   different re-serializations.
47//! - **Generation numbers are part of object identity** (§7.3.10):
48//!   [`ObjId`] carries both.
49
50use std::fmt;
51
52use crate::span::ByteSpan;
53
54/// An indirect-object identifier: object number + generation number
55/// (§7.3.10 — "together … shall uniquely identify an indirect object").
56///
57/// Object numbers are positive (0 is reserved for the free-list head,
58/// §7.5.4); generations run 0–65,535 (65,535 marks a never-reusable
59/// entry). `u32`/`u16` cover the spec ranges exactly (Annex C caps
60/// object numbers well inside `u32`).
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
62pub struct ObjId {
63    /// Object number (positive; 0 never identifies a real object).
64    pub num: u32,
65    /// Generation number (0–65,535).
66    pub generation: u16,
67}
68
69impl ObjId {
70    /// Construct an identifier.
71    #[must_use]
72    pub const fn new(num: u32, generation: u16) -> Self {
73        Self { num, generation }
74    }
75}
76
77impl fmt::Display for ObjId {
78    /// Renders as `num gen` — the order used by both `obj` definitions
79    /// and `R` references.
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        write!(f, "{} {}", self.num, self.generation)
82    }
83}
84
85/// A PDF name (§7.3.5): the decoded byte sequence, `#`-escapes already
86/// expanded, without the introducing `/`.
87///
88/// Stored decoded so `/Type` and `/Ty#70e` (same name, §7.3.5 NOTE 1)
89/// compare and hash identically. Names are raw bytes, not guaranteed
90/// UTF-8 (§7.3.5: interpretation as UTF-8 applies only where a name is
91/// *used as text*).
92#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
93pub struct Name(pub Vec<u8>);
94
95impl Name {
96    /// The decoded name bytes.
97    #[must_use]
98    pub fn as_bytes(&self) -> &[u8] {
99        &self.0
100    }
101}
102
103impl fmt::Display for Name {
104    /// `/PageMode` — **with** the slash, non-graphic bytes `#`-escaped
105    /// (`Pass 296.2`).
106    ///
107    /// # Why the slash is part of the rendering
108    ///
109    /// Because `/` is how a name is spelled everywhere an operator can check
110    /// it: in the file's own bytes, in the standard's tables, and in every
111    /// message this crate already writes. A consumer rendering `PageMode` and
112    /// a consumer rendering `/PageMode` are describing the same value and
113    /// their users cannot tell. The engine has a view — the files it writes
114    /// carry the slash — and the consuming shell was, in its own words,
115    /// guessing it.
116    ///
117    /// # Same bytes as `Debug`, deliberately
118    ///
119    /// `Debug` for [`Name`] already produced exactly this, so `Display`
120    /// delegates rather than defining a second spelling. Two renderings of one
121    /// name is precisely the drift this impl exists to stop, and it would be a
122    /// poor joke to introduce it here.
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        fmt::Debug::fmt(self, f)
125    }
126}
127
128impl fmt::Display for Object {
129    /// One unstyled line, sentence-sized: **scalars exact, containers named
130    /// rather than expanded** (`Pass 296.2`).
131    ///
132    /// | variant | renders as |
133    /// |---|---|
134    /// | `Null` | `null` |
135    /// | `Boolean` | `true` / `false` |
136    /// | `Integer` | `12` |
137    /// | `Real` | `1.5` |
138    /// | `String` | `(Hello)`, or `<0102FF>` when it is not printable text |
139    /// | `Name` | `/PageMode` |
140    /// | `Array` | `an array of 3 items` |
141    /// | `Dict` | `a dictionary of 14 entries` |
142    /// | `Stream` | `a stream of 14 entries` |
143    /// | `Reference` | `12 0 R` |
144    ///
145    /// # Why containers are NAMED and not expanded
146    ///
147    /// The request this answers put it better than a restatement would: the
148    /// pair being shown is `kept` versus `discarded` and the operator's
149    /// question is *"did pdfcer pick the right one?"*. **A graph dumped into a
150    /// status-bar sentence makes the readable case unreadable too** — one
151    /// enormous value destroys the line that the small value beside it was
152    /// going to fit on.
153    ///
154    /// So this is not a serialiser and must not become one. `Debug` remains
155    /// the full graph and has not changed; [`crate::writer`] remains the way
156    /// to produce bytes. This is the operator's sentence, and a caller that
157    /// wants a container's contents should ask for them.
158    ///
159    /// # Why the engine owns this at all
160    ///
161    /// Three things were diverging across consumers, none of which fails a
162    /// test: the slash on a name, whether a container expands, and — the one
163    /// that bites silently — the `#[non_exhaustive]` wildcard. A shell's
164    /// catch-all arm renders *"a value this build does not recognise"*, so
165    /// **adding a variant here would quietly make every shell say that about
166    /// it**. Owning `Display` means the arm is added in the same commit as the
167    /// variant, by the person who knows what it is.
168    ///
169    /// The precedent was already set by [`ObjId`], which is `Display` and
170    /// renders `12 0` — the form found in the bytes. The absence of the same
171    /// on `Object` read as an oversight because it was one.
172    ///
173    /// # Not in scope
174    ///
175    /// Localisation, wrapping, truncation, width awareness. Those belong to
176    /// whoever is drawing the line.
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        match self {
179            Self::Null => f.write_str("null"),
180            Self::Boolean(b) => write!(f, "{b}"),
181            Self::Integer(i) => write!(f, "{i}"),
182            Self::Real(r) => write!(f, "{r}"),
183            // §7.3.4.2 vs §7.3.4.3: a PDF string is BYTES, and the two source
184            // spellings are a presentation choice the format itself makes on
185            // the same grounds used here -- printable text reads as text,
186            // anything else reads as hex. Rendering arbitrary bytes through
187            // `from_utf8_lossy` would put replacement characters in front of
188            // an operator and call it the value.
189            Self::String(bytes) => {
190                if bytes.iter().all(|&b| b.is_ascii_graphic() || b == b' ') {
191                    write!(f, "({})", String::from_utf8_lossy(bytes))
192                } else {
193                    f.write_str("<")?;
194                    for &b in bytes {
195                        write!(f, "{b:02X}")?;
196                    }
197                    f.write_str(">")
198                }
199            }
200            Self::Name(n) => write!(f, "{n}"),
201            Self::Array(items) => write!(f, "an array of {}", plural(items.len(), "item")),
202            Self::Dict(d) => write!(f, "a dictionary of {}", plural(d.len(), "entry")),
203            // The dictionary's size, not the data's: `data_span` is a span in
204            // a buffer this type does not hold, and a byte count nobody can
205            // check is worse than the count of the thing being compared.
206            Self::Stream(st) => write!(f, "a stream of {}", plural(st.dict.len(), "entry")),
207            Self::Reference(id) => write!(f, "{id} R"),
208        }
209    }
210}
211
212/// `1 entry` / `14 entries` — English pluralisation for the two container
213/// nouns [`Object`]'s `Display` uses.
214///
215/// Spelled out rather than pulled in, because the alternative is a dependency
216/// for two words, and `"1 entries"` in front of an operator is the kind of
217/// detail that makes a tool look careless about everything else.
218fn plural(n: usize, noun: &str) -> String {
219    if n == 1 {
220        format!("1 {noun}")
221    } else if noun == "entry" {
222        format!("{n} entries")
223    } else {
224        format!("{n} {noun}s")
225    }
226}
227
228impl fmt::Debug for Name {
229    /// Debug form is `/Name` with non-ASCII bytes hex-escaped —
230    /// mirrors how the name would be discussed, not its exact source
231    /// encoding (which is non-unique anyway).
232    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233        write!(f, "/")?;
234        for &b in &self.0 {
235            if b.is_ascii_graphic() && b != b'#' {
236                write!(f, "{}", b as char)?;
237            } else {
238                write!(f, "#{b:02X}")?;
239            }
240        }
241        Ok(())
242    }
243}
244
245impl From<&[u8]> for Name {
246    fn from(bytes: &[u8]) -> Self {
247        Self(bytes.to_vec())
248    }
249}
250
251impl<const N: usize> From<&[u8; N]> for Name {
252    fn from(bytes: &[u8; N]) -> Self {
253        Self(bytes.to_vec())
254    }
255}
256
257/// A dictionary (§7.3.7): name-keyed, unordered per spec — but pdfcer
258/// preserves the parsed entry order so that re-serializing a *modified*
259/// dictionary perturbs sibling entries as little as possible (smaller
260/// diffs; the spec says written order "shall be ignored", so preserving
261/// it is always safe).
262///
263/// Backed by an ordered `Vec` with linear-scan lookup: PDF dictionaries
264/// are small (a handful to a few dozen entries), where a `Vec` beats a
265/// hash map on both speed and memory, and it keeps deterministic order
266/// for free.
267#[derive(Debug, Clone, PartialEq, Default)]
268pub struct Dict(pub Vec<(Name, Object)>);
269
270impl Dict {
271    /// Empty dictionary.
272    #[must_use]
273    pub const fn new() -> Self {
274        Self(Vec::new())
275    }
276
277    /// Look up `key`, applying the §7.3.7/§7.3.9 rule: **an entry whose
278    /// value is `null` is treated as if absent** — this returns `None`
279    /// for it. Implemented here, once, so no call site ever needs a
280    /// second "is it null?" check (see the spec RAG's API note).
281    #[must_use]
282    pub fn get(&self, key: &[u8]) -> Option<&Object> {
283        self.0
284            .iter()
285            .find(|(k, _)| k.as_bytes() == key)
286            .map(|(_, v)| v)
287            .filter(|v| !matches!(v, Object::Null))
288    }
289
290    /// Whether `key` is present with a non-null value (same collapse
291    /// rule as [`Dict::get`]).
292    #[must_use]
293    pub fn contains_key(&self, key: &[u8]) -> bool {
294        self.get(key).is_some()
295    }
296
297    /// Number of stored entries (including any explicit-null entries —
298    /// this is the physical count, used by serialization; semantic
299    /// presence goes through [`Dict::get`]).
300    #[must_use]
301    pub fn len(&self) -> usize {
302        self.0.len()
303    }
304
305    /// Whether the dictionary stores no entries at all.
306    #[must_use]
307    pub fn is_empty(&self) -> bool {
308        self.0.is_empty()
309    }
310
311    /// Iterate entries in preserved (parsed/inserted) order.
312    pub fn iter(&self) -> impl Iterator<Item = (&Name, &Object)> {
313        self.0.iter().map(|(k, v)| (k, v))
314    }
315
316    /// Insert or replace `key` → `value`, preserving position on
317    /// replace (append on fresh insert). The write-side primitive the
318    /// editing Passes build on.
319    pub fn insert(&mut self, key: Name, value: Object) {
320        match self.0.iter_mut().find(|(k, _)| *k == key) {
321            Some(slot) => slot.1 = value,
322            None => self.0.push((key, value)),
323        }
324    }
325
326    /// Remove `key` entirely, returning its stored value if there was
327    /// one.
328    ///
329    /// ## Why removal, and not "set it to `null`"
330    ///
331    /// §7.3.7 makes a `null`-valued entry semantically identical to an
332    /// absent one, so `insert(key, Object::Null)` would be *correct*.
333    /// It would also leave a physical entry behind, which means a
334    /// re-serialized dictionary carries a visible `/Title null` the
335    /// operator never asked for, and a later reader cannot tell "pdfcer
336    /// cleared this" from "the producer wrote an explicit null". Under
337    /// the minimal-diff discipline the honest form of *clear this field*
338    /// is for the field not to be there.
339    ///
340    /// Removes **all** entries with this key, not just the first.
341    /// Duplicate keys are malformed per §7.3.7 ("shall not") and the
342    /// parser rejects them, so a parsed dictionary never has any — but a
343    /// `Dict` built programmatically could, and leaving a shadowed
344    /// duplicate behind would make removal look like it did nothing.
345    pub fn remove(&mut self, key: &[u8]) -> Option<Object> {
346        let mut removed = None;
347        self.0.retain(|(k, v)| {
348            if k.as_bytes() == key {
349                if removed.is_none() {
350                    removed = Some(v.clone());
351                }
352                false
353            } else {
354                true
355            }
356        });
357        removed
358    }
359}
360
361/// A stream object (§7.3.8): its dictionary plus the span of its
362/// **encoded** data bytes in the retained source buffer.
363///
364/// The data is *not* copied out at parse time — the span points into
365/// the retained buffer (`crate::span`'s model), and decoding through
366/// the `/Filter` chain is a separate, on-demand step with its own
367/// resource ceilings (ARCHITECTURE.md §10.1). `data_span` is the exact
368/// `/Length`-byte region beginning after the `stream` keyword's EOL
369/// (§7.3.8.1's framing rules, including the CR-alone prohibition).
370#[derive(Debug, Clone, PartialEq)]
371pub struct Stream {
372    /// The stream dictionary (`/Length`, `/Filter`, …). Always a
373    /// direct dictionary per §7.3.8.1 (its *entries* may be indirect).
374    pub dict: Dict,
375    /// Exact span of the raw (still-encoded) stream data in the source
376    /// buffer.
377    pub data_span: ByteSpan,
378}
379
380/// A COS object (§7.3.1's eight basic types, plus the indirect
381/// reference, which is a value position in its own right per §7.3.10's
382/// substitutability rule).
383///
384/// Exhaustive on purpose: §7.3.1 closes the set, and matches over it in
385/// other crates (the structure dump) rely on a new variant being a compile
386/// error rather than a wildcard.
387#[derive(Debug, Clone, PartialEq)]
388pub enum Object {
389    /// `null` (§7.3.9). Also the resolution of any dangling reference
390    /// (§7.3.10 — "shall not be considered an error").
391    Null,
392    /// `true` / `false` (§7.3.2).
393    Boolean(bool),
394    /// Integer (§7.3.3). Kept distinct from `Real` — see module docs.
395    Integer(i64),
396    /// Real (§7.3.3).
397    Real(f64),
398    /// String (§7.3.4), decoded to raw bytes (escapes/hex applied).
399    /// Interpretation as text (§7.9.2) is a later layer's concern.
400    String(Vec<u8>),
401    /// Name (§7.3.5), decoded.
402    Name(Name),
403    /// Array (§7.3.6) — heterogeneous, possibly empty.
404    Array(Vec<Object>),
405    /// Dictionary (§7.3.7).
406    Dict(Dict),
407    /// Stream (§7.3.8). Streams only occur as the body of an indirect
408    /// object (§7.3.8.1 "all streams shall be indirect objects"); the
409    /// parser enforces that.
410    Stream(Stream),
411    /// An indirect reference `N G R` (§7.3.10) — a *pointer*, resolved
412    /// on demand by the document layer (dangling → `Null`, generation
413    /// mismatch → `Null`, cycle-guarded).
414    Reference(ObjId),
415}
416
417impl Object {
418    /// This object as an integer, if it is one.
419    #[must_use]
420    pub const fn as_int(&self) -> Option<i64> {
421        match self {
422            Self::Integer(v) => Some(*v),
423            _ => None,
424        }
425    }
426
427    /// This object as a number, widening integer to f64 — the §7.3.3
428    /// NOTE 2 rule ("wherever a real number is expected, an integer may
429    /// be used instead"). The converse direction is deliberately NOT
430    /// offered.
431    #[must_use]
432    pub const fn as_number(&self) -> Option<f64> {
433        match self {
434            Self::Integer(v) => Some(*v as f64),
435            Self::Real(v) => Some(*v),
436            _ => None,
437        }
438    }
439
440    /// This object as a name, if it is one.
441    #[must_use]
442    pub fn as_name(&self) -> Option<&Name> {
443        match self {
444            Self::Name(n) => Some(n),
445            _ => None,
446        }
447    }
448
449    /// This object as a dictionary, if it is one — a plain dict OR a
450    /// stream's dict (a stream is usable anywhere its dictionary
451    /// content is what matters).
452    #[must_use]
453    pub fn as_dict(&self) -> Option<&Dict> {
454        match self {
455            Self::Dict(d) => Some(d),
456            Self::Stream(s) => Some(&s.dict),
457            _ => None,
458        }
459    }
460
461    /// This object as an array, if it is one.
462    #[must_use]
463    pub fn as_array(&self) -> Option<&[Object]> {
464        match self {
465            Self::Array(a) => Some(a),
466            _ => None,
467        }
468    }
469
470    /// This object as an indirect reference, if it is one.
471    #[must_use]
472    pub const fn as_reference(&self) -> Option<ObjId> {
473        match self {
474            Self::Reference(id) => Some(*id),
475            _ => None,
476        }
477    }
478}
479
480/// Compare two objects that were parsed from **different source
481/// buffers**, ignoring where their stream data physically sits.
482///
483/// ## Why the derived `PartialEq` is the wrong tool here, and is a trap
484///
485/// [`Stream`] stores a [`ByteSpan`] rather than the bytes themselves
486/// (that is the whole point — see the type's docs), and `#[derive(
487/// PartialEq)]` therefore compares **offsets**. Two structurally
488/// identical documents whose streams sit at different byte positions
489/// compare *unequal*, and — worse — two *different* streams that happen
490/// to occupy the same span in two unrelated buffers compare *equal*.
491///
492/// That makes derived equality actively misleading for exactly the
493/// comparison a round-trip harness needs: "did this document survive a
494/// save?" A save legitimately moves objects (a full rewrite renumbers
495/// every offset; an incremental append puts a second copy at the end),
496/// so a span-sensitive comparison reports a false failure on every
497/// stream in the corpus. This function was added in Pass 3.0 after
498/// exactly that false red appeared across ~1,600 corpus files.
499///
500/// Within a single buffer the derived `PartialEq` remains correct and
501/// cheaper, so it is deliberately left in place; this is the
502/// cross-buffer counterpart, not a replacement.
503///
504/// ## What "equivalent" means precisely
505///
506/// - Streams: their **dictionaries** are compared recursively, and
507///   their **raw (still filter-encoded) data bytes** are compared for
508///   equality. Filters are not run — this is a structural comparison,
509///   and decoding would both cost far more and hide a real difference
510///   between two streams that decode alike.
511/// - A stream whose span lies outside its buffer is treated as empty,
512///   consistent with `crate::writer::serialize`'s degradation rule.
513/// - Everything else is ordinary structural equality, recursing through
514///   arrays and dictionaries so a nested difference cannot hide.
515///
516/// # Examples
517///
518/// ```
519/// use pdfcer_model::object::{equivalent_across_buffers, Dict, Name, Object, Stream};
520/// use pdfcer_model::span::ByteSpan;
521///
522/// // The same stream content at two different offsets.
523/// let a = Object::Stream(Stream { dict: Dict::new(), data_span: ByteSpan::new(0, 2) });
524/// let b = Object::Stream(Stream { dict: Dict::new(), data_span: ByteSpan::new(3, 2) });
525/// assert_ne!(a, b);                                        // derived: offsets differ
526/// assert!(equivalent_across_buffers(&a, b"hi", &b, b"xxxhi")); // content matches
527/// ```
528#[must_use]
529pub fn equivalent_across_buffers(a: &Object, a_source: &[u8], b: &Object, b_source: &[u8]) -> bool {
530    match (a, b) {
531        (Object::Stream(x), Object::Stream(y)) => {
532            let xd = x.data_span.slice(a_source).unwrap_or(&[]);
533            let yd = y.data_span.slice(b_source).unwrap_or(&[]);
534            xd == yd && dicts_equivalent(&x.dict, a_source, &y.dict, b_source)
535        }
536        (Object::Dict(x), Object::Dict(y)) => dicts_equivalent(x, a_source, y, b_source),
537        (Object::Array(x), Object::Array(y)) => {
538            x.len() == y.len()
539                && x.iter()
540                    .zip(y.iter())
541                    .all(|(i, j)| equivalent_across_buffers(i, a_source, j, b_source))
542        }
543        // No stream can hide inside any other variant (§7.3.8.1: "all
544        // streams shall be indirect objects"), so plain equality is
545        // exact for the rest.
546        _ => a == b,
547    }
548}
549
550/// Recursive helper for [`equivalent_across_buffers`]: dictionaries
551/// compare by entry order and content.
552///
553/// Order-sensitive on purpose. §7.3.7 says written order *"shall be
554/// ignored"* semantically, but `crate::object::Dict` deliberately
555/// **preserves** parsed order so a re-serialized dictionary diffs
556/// minimally — so a round-trip that reordered entries would be a
557/// minimal-diff regression this comparison should catch, not excuse.
558fn dicts_equivalent(a: &Dict, a_source: &[u8], b: &Dict, b_source: &[u8]) -> bool {
559    a.len() == b.len()
560        && a.iter().zip(b.iter()).all(|((ak, av), (bk, bv))| {
561            ak == bk && equivalent_across_buffers(av, a_source, bv, b_source)
562        })
563}
564
565/// Where an indirect object's definition physically lives in the loaded
566/// file — the provenance discriminator the minimal-diff writer needs
567/// (ARCHITECTURE.md §5; decision 001 §6.1 item 1).
568///
569/// ## Why this is an enum and not a `ByteSpan`
570///
571/// §5's contract — "an object pdfcer did not logically modify re-emits
572/// its source bytes verbatim, or is omitted entirely" — is only
573/// *expressible* for an object defined at file level as
574/// `N G obj … endobj`. A PDF 1.5 object **compressed inside an object
575/// stream** (§7.5.7) has no byte range of its own in the file at all:
576/// its bytes exist only inside its container's *encoded* stream data,
577/// interleaved with the other objects of that container, and are not
578/// even recoverable without running the container's filter chain.
579///
580/// Modelling that as "a span that happens to be wrong/absent" would be
581/// a lie the writer could not detect. Making it a type-level
582/// distinction forces every future save path to decide **consciously**
583/// what a compressed object means for it:
584///
585/// - *Incremental save, object untouched* — emit nothing. The
586///   container object is itself span-backed and untouched, so the whole
587///   prior revision stays byte-identical. No decision needed.
588/// - *Incremental save, object modified* — the object cannot be patched
589///   in place; the writer must either re-emit it as a new file-level
590///   object in the update section (legal: an object may move out of an
591///   object stream between revisions) or write a whole new container.
592///   Both are correct; the choice is the writer's, and it must be made
593///   knowingly.
594/// - *Full rewrite* — re-serialize from values; there is nothing
595///   verbatim to preserve.
596///
597/// The [`ObjectStream`](Provenance::ObjectStream) variant carries the
598/// container id and the index within it precisely so the writer has the
599/// facts to make that choice without re-deriving them from the xref.
600#[derive(Debug, Clone, Copy, PartialEq, Eq)]
601#[non_exhaustive]
602pub enum Provenance {
603    /// Defined at file level. The span covers the **complete
604    /// definition** — from the first byte of the object number through
605    /// the last byte of `endobj` — so an untouched object re-emits (or,
606    /// in incremental save, retains) exactly its source bytes.
607    File(ByteSpan),
608    /// Defined at file level at this span, but the retained bytes are
609    /// **internally inconsistent** and therefore must NOT be re-emitted
610    /// verbatim — the parsed value is authoritative, not the source bytes.
611    ///
612    /// Set in exactly one situation: cross-reference recovery re-derived a
613    /// stream's extent from its `endstream` keyword because the stored
614    /// `/Length` was unusable
615    /// ([`StreamLengthPolicy::RecoverFromEndstream`](crate::parser::StreamLengthPolicy::RecoverFromEndstream)).
616    /// The span's bytes then say one length while the parsed
617    /// [`Stream::data_span`] says another, and copying them through would
618    /// make pdfcer *write out* the very inconsistency it just recovered
619    /// from — producing a file pdfcer itself would refuse to reload. The
620    /// writer re-serializes instead, which regenerates `/Length` from the
621    /// actual data (`writer::serialize`'s "`/Length` is always recomputed,
622    /// never trusted").
623    ///
624    /// This is a third state rather than a flag on
625    /// [`File`](Provenance::File) for the same reason
626    /// [`ObjectStream`](Provenance::ObjectStream) is: it forces every save
627    /// path to decide **consciously** what it means, instead of leaving a
628    /// "span that happens to be untrustworthy" the writer cannot detect.
629    /// [`file_span`](Provenance::file_span) still returns the span — the
630    /// bytes are genuinely there, and a consumer that wants to *show* the
631    /// definition's location (the CLI's object listing) is still right to
632    /// ask. Only *re-emission* is affected.
633    RecoveredFile(ByteSpan),
634    /// Compressed inside an object stream (§7.5.7); reached through a
635    /// type-2 cross-reference entry (§7.5.8.3 Table 18). There is no
636    /// file-level span — see the type docs.
637    ObjectStream {
638        /// The object stream object that holds this object. Its own
639        /// generation is always 0 (§7.5.7).
640        container: ObjId,
641        /// 0-based index of this object within the container's
642        /// pair table (the type-2 entry's field 3).
643        index: u32,
644    },
645}
646
647impl Provenance {
648    /// The object's verbatim byte range in the retained source buffer,
649    /// or `None` for a compressed object (which has none).
650    ///
651    /// This is the accessor the writer uses; returning `Option` rather
652    /// than a sentinel is the whole point of the enum (type docs).
653    #[must_use]
654    pub const fn file_span(self) -> Option<ByteSpan> {
655        match self {
656            // `RecoveredFile` answers `Some` deliberately: its bytes DO
657            // exist at that span. What is untrustworthy is re-emitting
658            // them, which is [`Provenance::is_verbatim_safe`]'s question,
659            // not this one.
660            Self::File(span) | Self::RecoveredFile(span) => Some(span),
661            Self::ObjectStream { .. } => None,
662        }
663    }
664
665    /// Whether this object's retained bytes may be copied through to a
666    /// saved file **verbatim**.
667    ///
668    /// True only for [`File`](Provenance::File). A
669    /// [`RecoveredFile`](Provenance::RecoveredFile) object has bytes but
670    /// they contradict the parsed value, and an
671    /// [`ObjectStream`](Provenance::ObjectStream) object has no file-level
672    /// bytes at all — both must be re-serialized from values.
673    ///
674    /// Exists so the writer asks the question it actually means. Testing
675    /// `file_span().is_some()` would silently start copying
676    /// self-contradictory bytes the day the third variant appeared, which
677    /// is precisely the "span that happens to be wrong" failure mode this
678    /// enum was designed to make impossible.
679    #[must_use]
680    pub const fn is_verbatim_safe(self) -> bool {
681        matches!(self, Self::File(_))
682    }
683
684    /// The containing object stream, or `None` for a file-level object.
685    #[must_use]
686    pub const fn container(self) -> Option<ObjId> {
687        match self {
688            Self::File(_) | Self::RecoveredFile(_) => None,
689            Self::ObjectStream { container, .. } => Some(container),
690        }
691    }
692}
693
694/// A parsed indirect object: identifier, value, and the provenance that
695/// makes minimal-diff re-emission possible.
696///
697/// See [`Provenance`] for why the location is a discriminated union
698/// rather than a plain span.
699#[derive(Debug, Clone, PartialEq)]
700pub struct IndirectObject {
701    /// The `(num, gen)` identity.
702    pub id: ObjId,
703    /// The parsed value between `obj` and `endobj` (or, for a
704    /// compressed object, the bare value stored in its container —
705    /// §7.5.7: "the `obj` and `endobj` keywords shall not be used").
706    pub value: Object,
707    /// Where this object's definition physically lives.
708    pub provenance: Provenance,
709}
710
711impl IndirectObject {
712    /// Shorthand for `self.provenance.file_span()`: the object's
713    /// verbatim `N G obj … endobj` bytes in the retained buffer, or
714    /// `None` when it is compressed inside an object stream.
715    #[must_use]
716    pub const fn file_span(&self) -> Option<ByteSpan> {
717        self.provenance.file_span()
718    }
719}
720
721#[cfg(test)]
722#[allow(
723    clippy::unwrap_used,
724    clippy::expect_used,
725    clippy::panic,
726    clippy::indexing_slicing
727)]
728mod tests {
729    use super::*;
730
731    /// The three provenance states answer the two questions independently:
732    /// "are there file-level bytes?" and "may they be copied verbatim?".
733    ///
734    /// `RecoveredFile` is the case that makes the distinction necessary —
735    /// it is the only state that answers YES to the first and NO to the
736    /// second. A consumer that conflated them (testing
737    /// `file_span().is_some()` to decide re-emission) would copy
738    /// self-contradictory bytes into a saved file.
739    #[test]
740    fn provenance_separates_having_bytes_from_trusting_them() {
741        let span = ByteSpan::from_range(0..10);
742        let file = Provenance::File(span);
743        let recovered = Provenance::RecoveredFile(span);
744        let compressed = Provenance::ObjectStream {
745            container: ObjId::new(7, 0),
746            index: 2,
747        };
748
749        assert_eq!(file.file_span(), Some(span));
750        assert_eq!(recovered.file_span(), Some(span));
751        assert_eq!(compressed.file_span(), None);
752
753        assert!(file.is_verbatim_safe());
754        assert!(!recovered.is_verbatim_safe());
755        assert!(!compressed.is_verbatim_safe());
756
757        // Only a compressed object names a container; a recovered object
758        // is still file-level.
759        assert_eq!(file.container(), None);
760        assert_eq!(recovered.container(), None);
761        assert_eq!(compressed.container(), Some(ObjId::new(7, 0)));
762    }
763
764    #[test]
765    fn dict_null_value_collapses_to_absent() {
766        // §7.3.7/§7.3.9: present-with-null ≡ absent.
767        let mut d = Dict::new();
768        d.insert(Name::from(b"Alive"), Object::Integer(1));
769        d.insert(Name::from(b"Ghost"), Object::Null);
770        assert!(d.get(b"Alive").is_some());
771        assert!(d.get(b"Ghost").is_none());
772        assert!(!d.contains_key(b"Ghost"));
773        // ...but the physical entry still exists for serialization.
774        assert_eq!(d.len(), 2);
775    }
776
777    #[test]
778    fn dict_insert_replaces_in_place_preserving_order() {
779        let mut d = Dict::new();
780        d.insert(Name::from(b"A"), Object::Integer(1));
781        d.insert(Name::from(b"B"), Object::Integer(2));
782        d.insert(Name::from(b"A"), Object::Integer(9));
783        let keys: Vec<&[u8]> = d.iter().map(|(k, _)| k.as_bytes()).collect();
784        assert_eq!(keys, vec![&b"A"[..], b"B"]);
785        assert_eq!(d.get(b"A").unwrap().as_int(), Some(9));
786    }
787
788    #[test]
789    fn as_number_widens_integer_only() {
790        // §7.3.3 NOTE 2 is one-directional.
791        assert_eq!(Object::Integer(4).as_number(), Some(4.0));
792        assert_eq!(Object::Real(4.5).as_number(), Some(4.5));
793        assert_eq!(Object::Real(4.5).as_int(), None);
794    }
795
796    #[test]
797    fn stream_exposes_its_dict_via_as_dict() {
798        let s = Object::Stream(Stream {
799            dict: {
800                let mut d = Dict::new();
801                d.insert(Name::from(b"Length"), Object::Integer(0));
802                d
803            },
804            data_span: ByteSpan::new(0, 0),
805        });
806        assert!(s.as_dict().unwrap().contains_key(b"Length"));
807    }
808
809    #[test]
810    fn name_debug_form_is_readable() {
811        assert_eq!(format!("{:?}", Name::from(b"Type")), "/Type");
812        assert_eq!(format!("{:?}", Name::from(b"lime Green")), "/lime#20Green");
813    }
814
815    #[test]
816    fn objid_display_matches_reference_order() {
817        assert_eq!(ObjId::new(12, 3).to_string(), "12 3");
818    }
819
820    #[test]
821    fn cross_buffer_equivalence_ignores_stream_position() {
822        // The false red this function exists to prevent: a save moves a
823        // stream, the derived PartialEq compares spans, and every
824        // stream-bearing file in the corpus reports a phantom change.
825        let mut dict = Dict::new();
826        dict.insert(Name::from(b"Length"), Object::Integer(2));
827        let a = Object::Stream(Stream {
828            dict: dict.clone(),
829            data_span: ByteSpan::new(0, 2),
830        });
831        let b = Object::Stream(Stream {
832            dict,
833            data_span: ByteSpan::new(5, 2),
834        });
835        assert_ne!(
836            a, b,
837            "derived equality is span-sensitive (that is the trap)"
838        );
839        assert!(equivalent_across_buffers(&a, b"hi", &b, b"xxxxxhi"));
840    }
841
842    #[test]
843    fn cross_buffer_equivalence_still_catches_real_differences() {
844        // The other half: it must not become a comparison that always
845        // says yes. Different data, and different dictionaries, both
846        // have to fail.
847        let a = Object::Stream(Stream {
848            dict: Dict::new(),
849            data_span: ByteSpan::new(0, 2),
850        });
851        let b = Object::Stream(Stream {
852            dict: Dict::new(),
853            data_span: ByteSpan::new(0, 2),
854        });
855        assert!(!equivalent_across_buffers(&a, b"hi", &b, b"ho"));
856
857        let mut d = Dict::new();
858        d.insert(Name::from(b"K"), Object::Integer(1));
859        let c = Object::Stream(Stream {
860            dict: d,
861            data_span: ByteSpan::new(0, 2),
862        });
863        assert!(!equivalent_across_buffers(&a, b"hi", &c, b"hi"));
864    }
865
866    #[test]
867    fn cross_buffer_equivalence_recurses_and_is_order_sensitive() {
868        let mut x = Dict::new();
869        x.insert(Name::from(b"A"), Object::Integer(1));
870        x.insert(Name::from(b"B"), Object::Integer(2));
871        let mut y = Dict::new();
872        y.insert(Name::from(b"B"), Object::Integer(2));
873        y.insert(Name::from(b"A"), Object::Integer(1));
874        // Dict order is preserved by design (minimal diff), so a
875        // reordering IS a regression worth catching.
876        assert!(!equivalent_across_buffers(
877            &Object::Dict(x.clone()),
878            b"",
879            &Object::Dict(y),
880            b""
881        ));
882        assert!(equivalent_across_buffers(
883            &Object::Array(vec![Object::Dict(x.clone())]),
884            b"",
885            &Object::Array(vec![Object::Dict(x)]),
886            b""
887        ));
888        // Length mismatch in an array is caught before indexing.
889        assert!(!equivalent_across_buffers(
890            &Object::Array(vec![Object::Null]),
891            b"",
892            &Object::Array(vec![]),
893            b""
894        ));
895    }
896
897    #[test]
898    fn provenance_distinguishes_file_backed_from_compressed_objects() {
899        // The §5 writer contract in one assertion: only a file-level
900        // object can offer verbatim bytes, and a compressed one names
901        // the container instead of pretending to have a span.
902        let file = Provenance::File(ByteSpan::new(10, 20));
903        assert_eq!(file.file_span(), Some(ByteSpan::new(10, 20)));
904        assert_eq!(file.container(), None);
905
906        let compressed = Provenance::ObjectStream {
907            container: ObjId::new(7, 0),
908            index: 3,
909        };
910        assert_eq!(compressed.file_span(), None);
911        assert_eq!(compressed.container(), Some(ObjId::new(7, 0)));
912    }
913}