Skip to main content

laminapdf_syntax/
object.rs

1//! The PDF object model (ISO 32000-1 §7.3) and its exact serialization rules.
2
3use std::fmt;
4
5/// A reference to an indirect object: `num gen R`.
6///
7/// Added in 0.2.0.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
9pub struct ObjRef {
10    /// Object number.
11    pub num: u32,
12    /// Generation number.
13    pub gen_nr: u16,
14}
15
16impl ObjRef {
17    /// Creates a reference to object `num` with generation `gen_nr`.
18    ///
19    /// Added in 0.2.0.
20    #[must_use]
21    pub const fn new(num: u32, gen_nr: u16) -> Self {
22        Self { num, gen_nr }
23    }
24}
25
26impl fmt::Display for ObjRef {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        write!(f, "{} {} R", self.num, self.gen_nr)
29    }
30}
31
32/// How a string was (or should be) written: `(literal)` or `<hex>`.
33///
34/// Added in 0.2.0.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub enum StringFormat {
37    /// `( … )` with backslash escapes.
38    #[default]
39    Literal,
40    /// `< … >` uppercase hexadecimal.
41    Hex,
42}
43
44/// A PDF string: raw bytes plus the syntax it was written in.
45///
46/// Added in 0.2.0.
47#[derive(Debug, Clone, PartialEq, Eq, Default)]
48pub struct PdfString {
49    /// The decoded string bytes.
50    pub bytes: Vec<u8>,
51    /// Literal or hex form, remembered so that re-serialization round-trips.
52    pub format: StringFormat,
53}
54
55impl PdfString {
56    /// A literal string `( … )`.
57    ///
58    /// Added in 0.2.0.
59    #[must_use]
60    pub fn literal(bytes: impl Into<Vec<u8>>) -> Self {
61        Self {
62            bytes: bytes.into(),
63            format: StringFormat::Literal,
64        }
65    }
66
67    /// A hex string `< … >`.
68    ///
69    /// Added in 0.2.0.
70    #[must_use]
71    pub fn hex(bytes: impl Into<Vec<u8>>) -> Self {
72        Self {
73            bytes: bytes.into(),
74            format: StringFormat::Hex,
75        }
76    }
77}
78
79/// A PDF name, stored as its decoded bytes without the leading `/`.
80///
81/// Added in 0.2.0.
82#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, PartialOrd, Ord)]
83pub struct Name(pub Vec<u8>);
84
85impl Name {
86    /// Creates a name from its decoded bytes (no leading `/`).
87    ///
88    /// Added in 0.2.0.
89    #[must_use]
90    pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
91        Self(bytes.into())
92    }
93
94    /// The decoded bytes of the name.
95    ///
96    /// Added in 0.2.0.
97    #[must_use]
98    pub fn as_bytes(&self) -> &[u8] {
99        &self.0
100    }
101}
102
103impl From<&str> for Name {
104    fn from(s: &str) -> Self {
105        Self(s.as_bytes().to_vec())
106    }
107}
108
109/// An insertion-ordered dictionary. Lookups are linear, which is faster than hashing
110/// for the handful of keys real PDF dictionaries carry.
111///
112/// Added in 0.2.0.
113#[derive(Debug, Clone, PartialEq, Default)]
114pub struct Dict {
115    entries: Vec<(Name, Object)>,
116}
117
118impl Dict {
119    /// An empty dictionary.
120    ///
121    /// Added in 0.2.0.
122    #[must_use]
123    pub fn new() -> Self {
124        Self::default()
125    }
126
127    /// Looks up `key` (without the leading `/`).
128    ///
129    /// Added in 0.2.0.
130    #[must_use]
131    pub fn get(&self, key: &str) -> Option<&Object> {
132        self.entries.iter().find(|(k, _)| k.0 == key.as_bytes()).map(|(_, v)| v)
133    }
134
135    /// Mutable lookup of `key`.
136    ///
137    /// Added in 0.2.0.
138    pub fn get_mut(&mut self, key: &str) -> Option<&mut Object> {
139        self.entries
140            .iter_mut()
141            .find(|(k, _)| k.0 == key.as_bytes())
142            .map(|(_, v)| v)
143    }
144
145    /// True when `key` is present.
146    ///
147    /// Added in 0.2.0.
148    #[must_use]
149    pub fn contains_key(&self, key: &str) -> bool {
150        self.get(key).is_some()
151    }
152
153    /// Sets `key` to `value`. An existing key keeps its position; a new key is appended.
154    ///
155    /// Added in 0.2.0.
156    pub fn insert(&mut self, key: impl Into<Name>, value: impl Into<Object>) {
157        let key = key.into();
158        let value = value.into();
159        match self.entries.iter_mut().find(|(k, _)| *k == key) {
160            Some(slot) => slot.1 = value,
161            None => self.entries.push((key, value)),
162        }
163    }
164
165    /// Removes `key`, returning its value.
166    ///
167    /// Added in 0.2.0.
168    pub fn remove(&mut self, key: &str) -> Option<Object> {
169        let pos = self.entries.iter().position(|(k, _)| k.0 == key.as_bytes())?;
170        Some(self.entries.remove(pos).1)
171    }
172
173    /// Entries in insertion order.
174    ///
175    /// Added in 0.2.0.
176    pub fn iter(&self) -> impl Iterator<Item = (&Name, &Object)> {
177        self.entries.iter().map(|(k, v)| (k, v))
178    }
179
180    /// Entries in insertion order, with mutable values.
181    ///
182    /// Added in 0.2.0.
183    pub fn iter_mut(&mut self) -> impl Iterator<Item = (&Name, &mut Object)> {
184        self.entries.iter_mut().map(|(k, v)| (&*k, v))
185    }
186
187    /// Number of entries.
188    ///
189    /// Added in 0.2.0.
190    #[must_use]
191    pub fn len(&self) -> usize {
192        self.entries.len()
193    }
194
195    /// True when the dictionary has no entries.
196    ///
197    /// Added in 0.2.0.
198    #[must_use]
199    pub fn is_empty(&self) -> bool {
200        self.entries.is_empty()
201    }
202
203    /// `key` as a name, if present and a name.
204    ///
205    /// Added in 0.2.0.
206    #[must_use]
207    pub fn get_name(&self, key: &str) -> Option<&[u8]> {
208        match self.get(key) {
209            Some(Object::Name(n)) => Some(n.as_bytes()),
210            _ => None,
211        }
212    }
213
214    /// `key` as an integer, if present and an integer.
215    ///
216    /// Added in 0.2.0.
217    #[must_use]
218    pub fn get_int(&self, key: &str) -> Option<i64> {
219        self.get(key).and_then(Object::as_int)
220    }
221}
222
223impl<K: Into<Name>, V: Into<Object>> FromIterator<(K, V)> for Dict {
224    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
225        let mut dict = Self::new();
226        for (k, v) in iter {
227            dict.insert(k, v);
228        }
229        dict
230    }
231}
232
233/// A stream: its dictionary plus the raw (still encoded) bytes between `stream` and `endstream`.
234///
235/// Added in 0.2.0.
236#[derive(Debug, Clone, PartialEq, Default)]
237pub struct Stream {
238    /// The stream dictionary. `/Length` is managed by the writer.
239    pub dict: Dict,
240    /// Raw stream bytes as stored in the file (encoded by `/Filter`, if any).
241    pub data: Vec<u8>,
242}
243
244impl Stream {
245    /// A stream whose bytes are stored as-is.
246    ///
247    /// Added in 0.2.0.
248    #[must_use]
249    pub fn new(dict: Dict, data: impl Into<Vec<u8>>) -> Self {
250        Self {
251            dict,
252            data: data.into(),
253        }
254    }
255
256    /// A Flate-compressed stream: compresses `decoded` and sets `/Filter /FlateDecode`
257    /// (keeping the key's position if the caller already placed it).
258    ///
259    /// Added in 0.2.0.
260    #[must_use]
261    pub fn flate(mut dict: Dict, decoded: &[u8]) -> Self {
262        dict.insert("Filter", Name::from("FlateDecode"));
263        Self {
264            dict,
265            data: crate::filters::flate_encode(decoded),
266        }
267    }
268}
269
270/// A PDF object.
271///
272/// Added in 0.2.0.
273#[derive(Debug, Clone, PartialEq, Default)]
274pub enum Object {
275    /// `null`.
276    #[default]
277    Null,
278    /// `true` / `false`.
279    Bool(bool),
280    /// An integer.
281    Integer(i64),
282    /// A real number.
283    Real(f64),
284    /// A literal or hex string.
285    String(PdfString),
286    /// A name.
287    Name(Name),
288    /// An array.
289    Array(Vec<Object>),
290    /// A dictionary.
291    Dict(Dict),
292    /// A stream (only valid as the direct value of an indirect object).
293    Stream(Stream),
294    /// An indirect reference.
295    Ref(ObjRef),
296}
297
298impl Object {
299    /// `v` as a number: an integer when it is integral and below 10¹⁵ in magnitude (`612`,
300    /// not `612.0`), else a real. PDF has no NaN or infinity, so a non-finite `v` is 0.
301    ///
302    /// Added in 0.2.0.
303    #[must_use]
304    pub fn number(v: f64) -> Self {
305        if !v.is_finite() {
306            return Self::Integer(0);
307        }
308        #[expect(
309            clippy::cast_possible_truncation,
310            reason = "only integral values well inside i64 get here"
311        )]
312        if v.fract() == 0.0 && v.abs() < 1e15 {
313            Self::Integer(v as i64)
314        } else {
315            Self::Real(v)
316        }
317    }
318
319    /// `v` rounded to `decimals` decimal places (at most 15; more count as 15), then written
320    /// as [`Object::number`] writes it: `rounded(v, 0)` is the nearest integer.
321    ///
322    /// Added in 0.2.0.
323    #[must_use]
324    pub fn rounded(v: f64, decimals: u8) -> Self {
325        // Past 10¹⁵ every f64 is already whole, and scaling it could overflow to infinity.
326        if v.abs() >= 1e15 {
327            return Self::number(v);
328        }
329        let scale = 10f64.powi(i32::from(decimals.min(15)));
330        Self::number((v * scale).round() / scale)
331    }
332
333    /// A name object.
334    ///
335    /// Added in 0.2.0.
336    #[must_use]
337    pub fn name(s: &str) -> Self {
338        Self::Name(Name::from(s))
339    }
340
341    /// The integer value, if this is an integer.
342    ///
343    /// Added in 0.2.0.
344    #[must_use]
345    pub fn as_int(&self) -> Option<i64> {
346        match self {
347            Self::Integer(i) => Some(*i),
348            _ => None,
349        }
350    }
351
352    /// The numeric value of an integer or real.
353    ///
354    /// Added in 0.2.0.
355    #[must_use]
356    #[expect(clippy::cast_precision_loss, reason = "PDF numbers are approximate by definition")]
357    pub fn as_f64(&self) -> Option<f64> {
358        match self {
359            Self::Integer(i) => Some(*i as f64),
360            Self::Real(r) => Some(*r),
361            _ => None,
362        }
363    }
364
365    /// The dictionary, if this is a dictionary (or a stream's dictionary).
366    ///
367    /// Added in 0.2.0.
368    #[must_use]
369    pub fn as_dict(&self) -> Option<&Dict> {
370        match self {
371            Self::Dict(d) => Some(d),
372            Self::Stream(s) => Some(&s.dict),
373            _ => None,
374        }
375    }
376
377    /// The array, if this is an array.
378    ///
379    /// Added in 0.2.0.
380    #[must_use]
381    pub fn as_array(&self) -> Option<&[Object]> {
382        match self {
383            Self::Array(a) => Some(a),
384            _ => None,
385        }
386    }
387
388    /// The reference, if this is a reference.
389    ///
390    /// Added in 0.2.0.
391    #[must_use]
392    pub fn as_ref(&self) -> Option<ObjRef> {
393        match self {
394            Self::Ref(r) => Some(*r),
395            _ => None,
396        }
397    }
398
399    /// Serializes this object to a fresh buffer using the crate's exact formatting rules.
400    ///
401    /// Added in 0.2.0.
402    #[must_use]
403    pub fn to_bytes(&self) -> Vec<u8> {
404        let mut out = Vec::new();
405        self.write_to(&mut out);
406        out
407    }
408
409    /// Appends the serialization of this object to `out`.
410    ///
411    /// Streams are written as `<<dict>>\nstream\n…\nendstream` with `/Length` set to the
412    /// data length (kept in place if present, appended last otherwise).
413    ///
414    /// Added in 0.2.0.
415    pub fn write_to(&self, out: &mut Vec<u8>) {
416        match self {
417            Self::Null => out.extend_from_slice(b"null"),
418            Self::Bool(true) => out.extend_from_slice(b"true"),
419            Self::Bool(false) => out.extend_from_slice(b"false"),
420            Self::Integer(i) => out.extend_from_slice(i.to_string().as_bytes()),
421            Self::Real(r) => out.extend_from_slice(format_real(*r).as_bytes()),
422            Self::String(s) => write_string(s, out),
423            Self::Name(n) => write_name(n.as_bytes(), out),
424            Self::Array(items) => {
425                out.push(b'[');
426                for (i, item) in items.iter().enumerate() {
427                    if i > 0 {
428                        out.push(b' ');
429                    }
430                    item.write_to(out);
431                }
432                out.push(b']');
433            }
434            Self::Dict(d) => write_dict(d, out),
435            Self::Stream(s) => {
436                let mut dict = s.dict.clone();
437                let len = i64::try_from(s.data.len()).unwrap_or(i64::MAX);
438                dict.insert("Length", len);
439                write_dict(&dict, out);
440                out.extend_from_slice(b"\nstream\n");
441                out.extend_from_slice(&s.data);
442                out.extend_from_slice(b"\nendstream");
443            }
444            Self::Ref(r) => out.extend_from_slice(r.to_string().as_bytes()),
445        }
446    }
447}
448
449macro_rules! impl_from {
450    ($($t:ty => $variant:ident),* $(,)?) => {
451        $(impl From<$t> for Object {
452            fn from(v: $t) -> Self { Self::$variant(v.into()) }
453        })*
454    };
455}
456
457impl_from! {
458    bool => Bool, i64 => Integer, i32 => Integer, u32 => Integer, f64 => Real,
459    PdfString => String, Name => Name, Vec<Object> => Array, Dict => Dict,
460    Stream => Stream, ObjRef => Ref,
461}
462
463/// Formats a real: never an exponent, at most 6 fractional digits, trailing zeros and a
464/// trailing `.` trimmed, `-0` becomes `0`. Non-finite values (which PDF cannot express)
465/// are written as `0`.
466///
467/// Added in 0.2.0.
468#[must_use]
469pub fn format_real(value: f64) -> String {
470    if !value.is_finite() {
471        return "0".to_owned();
472    }
473    let mut s = format!("{value:.6}");
474    if s.contains('.') {
475        let trimmed = s.trim_end_matches('0').trim_end_matches('.').len();
476        s.truncate(trimmed);
477    }
478    if s == "-0" {
479        s.clear();
480        s.push('0');
481    }
482    s
483}
484
485/// Bytes that must be `#xx`-escaped inside a name besides those outside `!`..`~`.
486fn name_needs_escape(b: u8) -> bool {
487    !(b'!'..=b'~').contains(&b) || b"#()<>[]{}/%".contains(&b)
488}
489
490const HEX_UPPER: &[u8; 16] = b"0123456789ABCDEF";
491
492fn push_hex(b: u8, out: &mut Vec<u8>) {
493    let digit = |nibble: u8| HEX_UPPER.get(usize::from(nibble)).copied().unwrap_or(b'0');
494    out.push(digit(b >> 4));
495    out.push(digit(b & 0x0F));
496}
497
498pub(crate) fn write_name(bytes: &[u8], out: &mut Vec<u8>) {
499    out.push(b'/');
500    for &b in bytes {
501        if name_needs_escape(b) {
502            out.push(b'#');
503            push_hex(b, out);
504        } else {
505            out.push(b);
506        }
507    }
508}
509
510pub(crate) fn write_literal_string(bytes: &[u8], out: &mut Vec<u8>) {
511    out.push(b'(');
512    for &b in bytes {
513        match b {
514            b'\\' | b'(' | b')' => {
515                out.push(b'\\');
516                out.push(b);
517            }
518            b'\r' => out.extend_from_slice(b"\\r"),
519            _ => out.push(b),
520        }
521    }
522    out.push(b')');
523}
524
525fn write_string(s: &PdfString, out: &mut Vec<u8>) {
526    match s.format {
527        StringFormat::Literal => write_literal_string(&s.bytes, out),
528        StringFormat::Hex => {
529            out.push(b'<');
530            for &b in &s.bytes {
531                push_hex(b, out);
532            }
533            out.push(b'>');
534        }
535    }
536}
537
538fn write_dict(d: &Dict, out: &mut Vec<u8>) {
539    out.extend_from_slice(b"<<");
540    for (k, v) in d.iter() {
541        out.push(b' ');
542        write_name(k.as_bytes(), out);
543        out.push(b' ');
544        v.write_to(out);
545    }
546    out.extend_from_slice(b" >>");
547}
548
549#[cfg(test)]
550mod tests {
551    use super::*;
552
553    fn ser(o: &Object) -> String {
554        String::from_utf8_lossy(&o.to_bytes()).into_owned()
555    }
556
557    #[test]
558    fn number_writes_integral_values_as_integers() {
559        assert_eq!(
560            (Object::number(612.0), Object::number(0.5), Object::number(-3.0)),
561            (Object::Integer(612), Object::Real(0.5), Object::Integer(-3))
562        );
563    }
564
565    #[test]
566    fn number_writes_a_non_finite_value_as_zero() {
567        assert_eq!(
568            [f64::NAN, f64::INFINITY].map(Object::number),
569            [Object::Integer(0), Object::Integer(0)]
570        );
571    }
572
573    #[test]
574    fn rounded_leaves_a_huge_value_as_it_is() {
575        assert_eq!(Object::rounded(1e300, 15), Object::Real(1e300));
576    }
577
578    #[test]
579    fn rounded_to_no_decimals_is_the_nearest_integer() {
580        assert_eq!(
581            (Object::rounded(95.5, 0), Object::rounded(-292.6, 0)),
582            (Object::Integer(96), Object::Integer(-293))
583        );
584    }
585
586    #[test]
587    fn rounded_rounds_then_writes_a_whole_result_as_an_integer() {
588        assert_eq!(
589            (
590                Object::rounded(-12.004, 2),
591                Object::rounded(-12.345, 2),
592                Object::rounded(600.098, 3)
593            ),
594            (Object::Integer(-12), Object::Real(-12.35), Object::Real(600.098))
595        );
596    }
597
598    #[test]
599    fn format_real_trims_trailing_zeros() {
600        assert_eq!(format_real(0.5), "0.5");
601    }
602
603    #[test]
604    fn format_real_drops_trailing_dot_for_whole_numbers() {
605        assert_eq!(format_real(1.0), "1");
606    }
607
608    #[test]
609    fn format_real_keeps_sign_of_negative_fraction() {
610        assert_eq!(format_real(-0.25), "-0.25");
611    }
612
613    #[test]
614    fn format_real_turns_negative_zero_into_zero() {
615        assert_eq!(format_real(-0.0), "0");
616    }
617
618    #[test]
619    fn format_real_turns_tiny_negative_rounding_to_zero_into_zero() {
620        assert_eq!(format_real(-0.000_000_1), "0");
621    }
622
623    #[test]
624    fn format_real_never_uses_an_exponent() {
625        assert_eq!(format_real(1e20), "100000000000000000000");
626    }
627
628    #[test]
629    fn format_real_rounds_exact_tie_half_to_even() {
630        // 2^-7 = 0.0078125 is exactly representable: a true tie at 6 decimals.
631        assert_eq!(format_real(0.007_812_5), "0.007812");
632    }
633
634    #[test]
635    fn format_real_rounds_to_six_digits() {
636        assert_eq!(format_real(1.0 / 3.0), "0.333333");
637    }
638
639    #[test]
640    fn name_escapes_delimiters_space_and_hash() {
641        assert_eq!(
642            ser(&Object::Name(Name::new(&b"a b#(c)/%"[..]))),
643            "/a#20b#23#28c#29#2F#25"
644        );
645    }
646
647    #[test]
648    fn name_escapes_non_ascii_with_uppercase_hex() {
649        assert_eq!(ser(&Object::Name(Name::new(vec![0xE9, b'x']))), "/#E9x");
650    }
651
652    #[test]
653    fn literal_string_escapes_parens_backslash_and_cr() {
654        assert_eq!(
655            ser(&PdfString::literal(&b"a(b)c\\d\re\n"[..]).into()),
656            "(a\\(b\\)c\\\\d\\re\n)"
657        );
658    }
659
660    #[test]
661    fn hex_string_is_uppercase() {
662        assert_eq!(ser(&PdfString::hex(vec![0xAB, 0x01]).into()), "<AB01>");
663    }
664
665    #[test]
666    fn dict_uses_single_spaces() {
667        let d: Dict = [
668            ("K", Object::from(1)),
669            ("K2", Object::Array(vec![Object::Null, true.into()])),
670        ]
671        .into_iter()
672        .collect();
673        assert_eq!(ser(&d.into()), "<< /K 1 /K2 [null true] >>");
674    }
675
676    #[test]
677    fn empty_dict_serializes_as_double_brackets_with_space() {
678        assert_eq!(ser(&Dict::new().into()), "<< >>");
679    }
680
681    #[test]
682    fn stream_appends_length_last_when_absent() {
683        let s = Stream::new([("Type", Object::name("X"))].into_iter().collect(), b"abc".to_vec());
684        assert_eq!(ser(&s.into()), "<< /Type /X /Length 3 >>\nstream\nabc\nendstream");
685    }
686
687    #[test]
688    fn stream_keeps_caller_length_position() {
689        let d: Dict = [("Length", Object::from(99)), ("Filter", Object::name("F"))]
690            .into_iter()
691            .collect();
692        assert_eq!(
693            ser(&Stream::new(d, b"ab".to_vec()).into()),
694            "<< /Length 2 /Filter /F >>\nstream\nab\nendstream"
695        );
696    }
697
698    #[test]
699    fn dict_insert_keeps_existing_key_position() {
700        let mut d: Dict = [("A", 1), ("B", 2)].into_iter().collect();
701        d.insert("A", 3);
702        assert_eq!(ser(&d.into()), "<< /A 3 /B 2 >>");
703    }
704}