Skip to main content

pdfcer_model/
span.rs

1//! # Byte-span provenance — the foundation of round-trip / minimal-diff
2//!
3//! This module exists because of the single most important architecture
4//! decision in pdfcer: **provenance is a first-class field, not an
5//! optimization** (`docs/decisions/001-oxidize-pdf-adopt-vs-build.md`
6//! §6.1 item 1, enacting `docs/ARCHITECTURE.md` §5).
7//!
8//! ## The contract
9//!
10//! Every syntactic entity parsed out of a PDF buffer — every token, every
11//! COS object, every content-stream operator — records the exact byte
12//! range of the source buffer it was parsed from, as a [`ByteSpan`]. The
13//! source buffer itself is retained for the lifetime of the loaded
14//! document. At save time the rule is:
15//!
16//! > An entity that is span-backed and structurally unmodified since the
17//! > base revision re-emits its **source bytes verbatim** (full rewrite)
18//! > or is **omitted entirely** (incremental save — the default mode).
19//!
20//! This is what makes pdfcer's editing signature-safe: an incremental save
21//! appends a new revision and leaves every prior byte untouched, so a
22//! digital signature's `/ByteRange` over the earlier revision stays
23//! valid (ISO 32000-1 §7.5.6; see `iso32000__s__7.5.6.md` in the spec
24//! RAG).
25//!
26//! ## Why re-encoding is NOT equivalent — concrete spec cases
27//!
28//! PDF syntax is deliberately non-canonical; a decoded value does not
29//! determine its source bytes. Cases the spec RAG documents explicitly:
30//!
31//! - **Names** (§7.3.5 NOTE 1): `/A#42` and `/AB` are the *same name*.
32//!   Re-emitting the decoded value changes bytes.
33//! - **Literal strings** (§7.3.4.2): a bare CRLF inside a literal string
34//!   decodes to a single 0Ah byte — decode-then-re-encode is lossy by
35//!   specification.
36//! - **Numerics** (§7.3.3): `4.`, `+17`, `0.40` all carry formatting a
37//!   parsed value can't reproduce.
38//!
39//! Hence every lossy-decoded entity keeps its span, and the span — not
40//! the decoded value — is the unit of re-emission for untouched content.
41//!
42//! ## Offsets are absolute
43//!
44//! Spans are offsets into **the retained source buffer, from byte 0 of
45//! that buffer** — not relative to the `%PDF-` header (which may not be
46//! at byte 0; see the header-offset open question in `lib.rs`). One
47//! buffer, one coordinate system, no ambiguity.
48
49use std::fmt;
50use std::ops::Range;
51
52/// A half-open byte range `[start, start + len)` into a retained source
53/// buffer.
54///
55/// See the module docs for why this type is load-bearing rather than a
56/// convenience. It is deliberately a plain value type (`Copy`, ordered,
57/// hashable) so it can be embedded in every token and object without
58/// ceremony.
59///
60/// # Examples
61///
62/// ```
63/// use pdfcer_model::span::ByteSpan;
64///
65/// let buf = b"12 0 obj";
66/// let span = ByteSpan::new(0, 2); // the "12" token
67/// assert_eq!(span.slice(buf), Some(&b"12"[..]));
68/// assert_eq!(span.end(), 2);
69/// ```
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
71pub struct ByteSpan {
72    /// Offset of the first byte, from byte 0 of the retained buffer.
73    pub start: usize,
74    /// Number of bytes covered. May be 0 (e.g. the empty name `/`
75    /// has a 1-byte span for its solidus, but an empty *decoded* value —
76    /// zero-length spans arise in synthesized entities).
77    pub len: usize,
78}
79
80impl ByteSpan {
81    /// Construct a span from a start offset and length.
82    #[must_use]
83    pub const fn new(start: usize, len: usize) -> Self {
84        Self { start, len }
85    }
86
87    /// Construct a span covering `range` (`start..end`).
88    ///
89    /// Returns a zero-length span at `range.start` if the range is
90    /// inverted (`end < start`) — inverted ranges are always a caller
91    /// bug, but this type is used in paths that must not panic
92    /// (`pdfcer-core`'s crate-level panic-free policy), so it degrades to
93    /// the least-harmful value instead.
94    #[must_use]
95    pub const fn from_range(range: Range<usize>) -> Self {
96        Self {
97            start: range.start,
98            len: range.end.saturating_sub(range.start),
99        }
100    }
101
102    /// The offset one past the last byte (`start + len`), saturating.
103    #[must_use]
104    pub const fn end(self) -> usize {
105        self.start.saturating_add(self.len)
106    }
107
108    /// This span as a `Range<usize>` for slicing.
109    #[must_use]
110    pub const fn range(self) -> Range<usize> {
111        self.start..self.end()
112    }
113
114    /// The bytes this span covers in `buf`, or `None` if the span is out
115    /// of bounds for `buf`.
116    ///
117    /// `None` here always indicates a logic error (a span applied to a
118    /// buffer it wasn't produced from); it is surfaced as an `Option`
119    /// rather than a panic per the crate's panic-free policy, so callers
120    /// convert it into a proper structural error.
121    #[must_use]
122    pub fn slice(self, buf: &[u8]) -> Option<&[u8]> {
123        buf.get(self.range())
124    }
125
126    /// Whether this span covers zero bytes.
127    #[must_use]
128    pub const fn is_empty(self) -> bool {
129        self.len == 0
130    }
131}
132
133impl fmt::Display for ByteSpan {
134    /// Renders as `start..end` (the half-open range), the form used in
135    /// diagnostics.
136    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137        write!(f, "{}..{}", self.start, self.end())
138    }
139}
140
141impl From<Range<usize>> for ByteSpan {
142    fn from(range: Range<usize>) -> Self {
143        Self::from_range(range)
144    }
145}
146
147#[cfg(test)]
148#[allow(
149    clippy::unwrap_used,
150    clippy::expect_used,
151    clippy::panic,
152    clippy::indexing_slicing
153)]
154mod tests {
155    use super::*;
156
157    #[test]
158    fn slice_returns_covered_bytes() {
159        let buf = b"hello world";
160        assert_eq!(ByteSpan::new(6, 5).slice(buf), Some(&b"world"[..]));
161    }
162
163    #[test]
164    fn slice_out_of_bounds_is_none_not_panic() {
165        let buf = b"short";
166        assert_eq!(ByteSpan::new(3, 10).slice(buf), None);
167        assert_eq!(ByteSpan::new(99, 1).slice(buf), None);
168    }
169
170    #[test]
171    fn from_inverted_range_degrades_to_empty() {
172        #[allow(clippy::reversed_empty_ranges)]
173        let s = ByteSpan::from_range(5..2);
174        assert_eq!(s.start, 5);
175        assert!(s.is_empty());
176    }
177
178    #[test]
179    fn display_is_half_open() {
180        assert_eq!(ByteSpan::new(3, 4).to_string(), "3..7");
181    }
182}