Skip to main content

rustium_pdf/
object.rs

1//! The COS object model: everything a PDF body is made of.
2
3use std::collections::HashMap;
4use std::sync::Arc;
5
6/// An indirect object reference: object number and generation.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub struct ObjRef {
9    pub num: u32,
10    pub gen: u16,
11}
12
13impl ObjRef {
14    pub const fn new(num: u32, gen: u16) -> Self {
15        Self { num, gen }
16    }
17}
18
19/// A dictionary. Keys are names with the leading `/` and `#xx` escapes already resolved.
20#[derive(Debug, Clone, Default, PartialEq)]
21pub struct Dict(pub HashMap<String, Object>);
22
23impl Dict {
24    pub fn new() -> Self {
25        Self::default()
26    }
27
28    pub fn get(&self, key: &str) -> Option<&Object> {
29        self.0.get(key)
30    }
31
32    pub fn insert(&mut self, key: impl Into<String>, value: Object) {
33        self.0.insert(key.into(), value);
34    }
35
36    pub fn contains(&self, key: &str) -> bool {
37        self.0.contains_key(key)
38    }
39}
40
41/// A stream: its dictionary plus the raw (still filtered, possibly encrypted) bytes.
42///
43/// The bytes are behind an `Arc` so cloning the containing [`Object`] does not copy stream
44/// payloads; document loading hands out clones freely.
45#[derive(Debug, Clone, PartialEq)]
46pub struct Stream {
47    pub dict: Dict,
48    pub raw: Arc<[u8]>,
49}
50
51#[derive(Debug, Clone, PartialEq, Default)]
52pub enum Object {
53    #[default]
54    Null,
55    Bool(bool),
56    Int(i64),
57    Real(f64),
58    /// A string's decoded bytes. Interpretation (PDFDocEncoding, UTF-16BE) is the caller's.
59    String(Vec<u8>),
60    Name(String),
61    Array(Vec<Object>),
62    Dict(Dict),
63    Stream(Stream),
64    Ref(ObjRef),
65}
66
67impl Object {
68    pub fn as_int(&self) -> Option<i64> {
69        match self {
70            Object::Int(i) => Some(*i),
71            Object::Real(r) => Some(*r as i64),
72            _ => None,
73        }
74    }
75
76    pub fn as_f32(&self) -> Option<f32> {
77        match self {
78            Object::Int(i) => Some(*i as f32),
79            Object::Real(r) => Some(*r as f32),
80            _ => None,
81        }
82    }
83
84    pub fn as_bool(&self) -> Option<bool> {
85        match self {
86            Object::Bool(b) => Some(*b),
87            _ => None,
88        }
89    }
90
91    pub fn as_name(&self) -> Option<&str> {
92        match self {
93            Object::Name(n) => Some(n),
94            _ => None,
95        }
96    }
97
98    pub fn as_string(&self) -> Option<&[u8]> {
99        match self {
100            Object::String(s) => Some(s),
101            _ => None,
102        }
103    }
104
105    pub fn as_array(&self) -> Option<&[Object]> {
106        match self {
107            Object::Array(a) => Some(a),
108            _ => None,
109        }
110    }
111
112    /// The dictionary of a dict *or* a stream: many entries (`/Resources`, `/Font`) may be
113    /// either, and callers almost never care which.
114    pub fn as_dict(&self) -> Option<&Dict> {
115        match self {
116            Object::Dict(d) => Some(d),
117            Object::Stream(s) => Some(&s.dict),
118            _ => None,
119        }
120    }
121
122    pub fn as_stream(&self) -> Option<&Stream> {
123        match self {
124            Object::Stream(s) => Some(s),
125            _ => None,
126        }
127    }
128
129    pub fn as_ref_id(&self) -> Option<ObjRef> {
130        match self {
131            Object::Ref(r) => Some(*r),
132            _ => None,
133        }
134    }
135
136    pub fn is_null(&self) -> bool {
137        matches!(self, Object::Null)
138    }
139}
140
141/// Decodes a PDF *text string* (ISO 32000 ยง7.9.2.2): UTF-16 when it opens with a byte-order
142/// mark, UTF-8 when it opens with that encoding's mark (PDF 2.0), PDFDocEncoding otherwise.
143///
144/// Bytes PDFDocEncoding leaves undefined are dropped rather than guessed at.
145pub(crate) fn text_string(bytes: &[u8]) -> String {
146    let utf16 = |rest: &[u8], big_endian: bool| {
147        // A dangling odd byte is left in the remainder and ignored.
148        let (pairs, _) = rest.as_chunks::<2>();
149        let units: Vec<u16> = pairs
150            .iter()
151            .map(|&pair| {
152                if big_endian {
153                    u16::from_be_bytes(pair)
154                } else {
155                    u16::from_le_bytes(pair)
156                }
157            })
158            .collect();
159        String::from_utf16_lossy(&units)
160    };
161    match bytes {
162        [0xFE, 0xFF, rest @ ..] => utf16(rest, true),
163        // Not in the standard, but written by enough producers that every reader accepts it.
164        [0xFF, 0xFE, rest @ ..] => utf16(rest, false),
165        [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(),
166        _ => bytes.iter().filter_map(|&b| pdf_doc_char(b)).collect(),
167    }
168}
169
170/// One PDFDocEncoding byte as a character (ISO 32000 Annex D.3).
171fn pdf_doc_char(byte: u8) -> Option<char> {
172    /// Codes 0x18..=0x1F: the spacing diacritics.
173    const ACCENTS: [char; 8] = [
174        '\u{02D8}', '\u{02C7}', '\u{02C6}', '\u{02D9}', '\u{02DD}', '\u{02DB}', '\u{02DA}',
175        '\u{02DC}',
176    ];
177    /// Codes 0x80..=0x9E: typographic punctuation, ligatures and a few Latin Extended letters.
178    const HIGH: [char; 31] = [
179        '\u{2022}', '\u{2020}', '\u{2021}', '\u{2026}', '\u{2014}', '\u{2013}', '\u{0192}',
180        '\u{2044}', '\u{2039}', '\u{203A}', '\u{2212}', '\u{2030}', '\u{201E}', '\u{201C}',
181        '\u{201D}', '\u{2018}', '\u{2019}', '\u{201A}', '\u{2122}', '\u{FB01}', '\u{FB02}',
182        '\u{0141}', '\u{0152}', '\u{0160}', '\u{0178}', '\u{017D}', '\u{0131}', '\u{0142}',
183        '\u{0153}', '\u{0161}', '\u{017E}',
184    ];
185    match byte {
186        0x09 | 0x0A | 0x0D | 0x20..=0x7E => Some(byte as char),
187        0x18..=0x1F => Some(ACCENTS[(byte - 0x18) as usize]),
188        0x80..=0x9E => Some(HIGH[(byte - 0x80) as usize]),
189        0xA0 => Some('\u{20AC}'),
190        // The rest of the upper half is Latin-1, less the soft hyphen's slot.
191        0xA1..=0xAC | 0xAE..=0xFF => Some(byte as char),
192        _ => None,
193    }
194}
195
196#[cfg(test)]
197mod tests {
198    use super::text_string;
199
200    #[test]
201    fn a_text_string_is_utf16_only_behind_a_byte_order_mark() {
202        assert_eq!(text_string(b"\xFE\xFF\x00f\x00i"), "fi");
203        assert_eq!(text_string(b"\xFF\xFEf\x00i\x00"), "fi");
204        // A surrogate pair, and a dangling odd byte that is ignored rather than misread.
205        assert_eq!(text_string(b"\xFE\xFF\xD8\x35\xDC\x00\x00"), "\u{1D400}");
206        assert_eq!(text_string(b"\xEF\xBB\xBF\xC3\xA9"), "\u{e9}");
207        assert_eq!(text_string(b""), "");
208    }
209
210    #[test]
211    fn a_text_string_without_a_mark_is_pdf_doc_encoding() {
212        assert_eq!(text_string(b"fi 68"), "fi 68");
213        // Where PDFDocEncoding parts from Latin-1: 0x93 is the fi ligature, 0x85 an en dash,
214        // 0xA0 the euro sign. 0xE9 is where the two agree.
215        assert_eq!(
216            text_string(b"\x93\x85\xA0\xE9"),
217            "\u{FB01}\u{2013}\u{20AC}\u{e9}"
218        );
219        // Undefined codes vanish instead of becoming control characters.
220        assert_eq!(text_string(b"a\x7F\x9F\xADb\x01"), "ab");
221    }
222}