Skip to main content

pdf/read/
object.rs

1// The objects of a PDF file as the reader gives them (ISO 32000-1, 7.3): null, booleans,
2// integers, reals, strings (bytes; text strings are decoded by text_string), names, arrays,
3// dictionaries, streams and references to indirect objects.  A stream holds its dictionary and
4// where its data lies in the file; Document::decode gives the data with the filters applied.
5
6use alloc::collections::BTreeMap;
7use alloc::string::String;
8use alloc::sync::Arc;
9use alloc::vec::Vec;
10use core::borrow::Borrow;
11
12/// a reference to an indirect object: its number and generation
13#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct Ref {
15    pub num: u32,
16    pub generation: u16,
17}
18
19/// as PDF writes it: 12 0 R
20impl core::fmt::Debug for Ref {
21    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
22        write!(f, "{} {} R", self.num, self.generation)
23    }
24}
25
26/// a name (/Type): its bytes with #xx escapes resolved
27#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
28pub struct Name(pub Vec<u8>);
29
30/// as PDF writes it: /Type, with #xx for bytes outside the printable ASCII range and delimiters
31impl core::fmt::Debug for Name {
32    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
33        f.write_str("/")?;
34        for &c in &self.0 {
35            if c.is_ascii_graphic() && !super::lex::is_delim(c) && c != b'#' {
36                write!(f, "{}", c as char)?;
37            } else {
38                write!(f, "#{c:02X}")?;
39            }
40        }
41        Ok(())
42    }
43}
44
45impl Name {
46    pub fn as_bytes(&self) -> &[u8] {
47        &self.0
48    }
49    /// the name as text (bytes that are not UTF-8 become U+FFFD)
50    pub fn to_text(&self) -> String {
51        String::from_utf8_lossy(&self.0).into_owned()
52    }
53}
54
55impl Borrow<[u8]> for Name {
56    fn borrow(&self) -> &[u8] {
57        &self.0
58    }
59}
60
61impl PartialEq<str> for Name {
62    fn eq(&self, o: &str) -> bool {
63        self.0 == o.as_bytes()
64    }
65}
66
67impl PartialEq<&str> for Name {
68    fn eq(&self, o: &&str) -> bool {
69        self.0 == o.as_bytes()
70    }
71}
72
73/// a dictionary; a key given twice keeps its last value.  Copies share their entries until one
74/// of them changes (inherited resources, the pages of a tree and the caches of drawing copy
75/// dictionaries freely; a hostile file must not turn that into memory without end)
76#[derive(Clone, Debug, PartialEq, Default)]
77pub struct Dict(pub(crate) Arc<BTreeMap<Name, Object>>);
78
79impl Dict {
80    pub fn new() -> Dict {
81        Dict(Arc::new(BTreeMap::new()))
82    }
83    pub(crate) fn from_map(m: BTreeMap<Name, Object>) -> Dict {
84        Dict(Arc::new(m))
85    }
86    /// the entries to change (copied first when another Dict shares them)
87    pub(crate) fn map_mut(&mut self) -> &mut BTreeMap<Name, Object> {
88        Arc::make_mut(&mut self.0)
89    }
90    /// the value of a key (without the slash: "Type")
91    pub fn get(&self, key: &str) -> Option<&Object> {
92        self.0.get(key.as_bytes())
93    }
94    pub fn get_bytes(&self, key: &[u8]) -> Option<&Object> {
95        self.0.get(key)
96    }
97    pub fn contains(&self, key: &str) -> bool {
98        self.0.contains_key(key.as_bytes())
99    }
100    pub fn insert(&mut self, key: &str, value: Object) {
101        self.map_mut().insert(Name(key.as_bytes().to_vec()), value);
102    }
103    /// the value of a key, taken out
104    pub fn remove(&mut self, key: &str) -> Option<Object> {
105        self.map_mut().remove(key.as_bytes())
106    }
107    pub fn len(&self) -> usize {
108        self.0.len()
109    }
110    pub fn is_empty(&self) -> bool {
111        self.0.is_empty()
112    }
113    pub fn iter(&self) -> impl Iterator<Item = (&Name, &Object)> {
114        self.0.iter()
115    }
116    /// the name under a key (Type, Subtype, ...), if it is one
117    pub fn name(&self, key: &str) -> Option<&[u8]> {
118        self.get(key).and_then(Object::as_name)
119    }
120    /// a key whose value is the name `v`
121    pub fn is(&self, key: &str, v: &str) -> bool {
122        self.name(key) == Some(v.as_bytes())
123    }
124    pub fn int(&self, key: &str) -> Option<i64> {
125        self.get(key).and_then(Object::as_int)
126    }
127    pub fn num(&self, key: &str) -> Option<f64> {
128        self.get(key).and_then(Object::as_f64)
129    }
130}
131
132/// a stream: its dictionary, and where its (still encoded) data lies in the file
133#[derive(Clone, Debug, PartialEq)]
134pub struct Stream {
135    pub dict: Dict,
136    pub(crate) start: usize,
137    pub(crate) end: usize,
138    /// the object it is (its key when the file is encrypted)
139    pub(crate) owner: Option<Ref>,
140}
141
142impl Stream {
143    /// the number of encoded bytes
144    pub fn raw_len(&self) -> usize {
145        self.end - self.start
146    }
147}
148
149/// one object of a PDF file
150#[derive(Clone, Debug, PartialEq, Default)]
151pub enum Object {
152    #[default]
153    Null,
154    Bool(bool),
155    Int(i64),
156    Real(f64),
157    /// a string's bytes (decrypted); text strings decode with text_string
158    String(Vec<u8>),
159    Name(Name),
160    Array(Vec<Object>),
161    Dict(Dict),
162    /// boxed: keeps every object at 32 bytes
163    Stream(alloc::boxed::Box<Stream>),
164    Ref(Ref),
165}
166
167impl Object {
168    pub fn name(s: &str) -> Object {
169        Object::Name(Name(s.as_bytes().to_vec()))
170    }
171    pub fn is_null(&self) -> bool {
172        matches!(self, Object::Null)
173    }
174    pub fn as_bool(&self) -> Option<bool> {
175        match self {
176            Object::Bool(b) => Some(*b),
177            _ => None,
178        }
179    }
180    /// an integer, or a real that is one (some writers put 1.0 where an integer belongs)
181    pub fn as_int(&self) -> Option<i64> {
182        match *self {
183            Object::Int(i) => Some(i),
184            Object::Real(r) if r.is_finite() && r == (r as i64) as f64 => Some(r as i64),
185            _ => None,
186        }
187    }
188    /// a number
189    pub fn as_f64(&self) -> Option<f64> {
190        match *self {
191            Object::Int(i) => Some(i as f64),
192            Object::Real(r) if r.is_finite() => Some(r),
193            _ => None,
194        }
195    }
196    pub fn as_name(&self) -> Option<&[u8]> {
197        match self {
198            Object::Name(n) => Some(&n.0),
199            _ => None,
200        }
201    }
202    /// a string's bytes
203    pub fn as_bytes(&self) -> Option<&[u8]> {
204        match self {
205            Object::String(s) => Some(s),
206            _ => None,
207        }
208    }
209    pub fn as_array(&self) -> Option<&[Object]> {
210        match self {
211            Object::Array(a) => Some(a),
212            _ => None,
213        }
214    }
215    /// a dictionary, or a stream's dictionary
216    pub fn as_dict(&self) -> Option<&Dict> {
217        match self {
218            Object::Dict(d) => Some(d),
219            Object::Stream(s) => Some(&s.dict),
220            _ => None,
221        }
222    }
223    pub fn as_stream(&self) -> Option<&Stream> {
224        match self {
225            Object::Stream(s) => Some(s),
226            _ => None,
227        }
228    }
229    pub fn as_ref(&self) -> Option<Ref> {
230        match self {
231            Object::Ref(r) => Some(*r),
232            _ => None,
233        }
234    }
235    /// a rectangle [x0 y0 x1 y1], normalized so that x0 <= x1 and y0 <= y1
236    pub fn as_rect(&self) -> Option<[f64; 4]> {
237        let a = self.as_array()?;
238        if a.len() < 4 {
239            return None;
240        }
241        let v = [a[0].as_f64()?, a[1].as_f64()?, a[2].as_f64()?, a[3].as_f64()?];
242        Some([v[0].min(v[2]), v[1].min(v[3]), v[0].max(v[2]), v[1].max(v[3])])
243    }
244}
245
246/// a text string (7.9.2.2) as text: UTF-16BE after FE FF, UTF-16LE after FF FE (seen in the
247/// wild), UTF-8 after EF BB BF (PDF 2.0), else PDFDocEncoding
248pub fn text_string(b: &[u8]) -> String {
249    if b.len() >= 2 && (b[0] == 0xFE && b[1] == 0xFF || b[0] == 0xFF && b[1] == 0xFE) {
250        let be = b[0] == 0xFE;
251        let units = b[2..].chunks_exact(2).map(|c| if be { u16::from_be_bytes([c[0], c[1]]) } else { u16::from_le_bytes([c[0], c[1]]) });
252        let s: String = char::decode_utf16(units).map(|r| r.unwrap_or('\u{FFFD}')).collect();
253        // a language escape (ESC code ESC) inside UTF-16 is dropped; an ESC without a second one
254        // stays with what follows.  One pass: a find and replace for each escape took quadratic
255        // time for a string of escapes
256        let Some(last) = s.rfind('\u{1B}') else { return s };
257        let mut out = String::with_capacity(s.len());
258        let mut skip = false;
259        for (i, ch) in s.char_indices() {
260            if ch == '\u{1B}' && (skip || i < last) {
261                skip = !skip;
262                continue;
263            }
264            if !skip {
265                out.push(ch);
266            }
267        }
268        return out;
269    }
270    if b.len() >= 3 && b[..3] == [0xEF, 0xBB, 0xBF] {
271        return String::from_utf8_lossy(&b[3..]).into_owned();
272    }
273    b.iter().filter_map(|&c| char::from_u32(super::tables::PDFDOC[c as usize] as u32).filter(|&ch| ch != '\0' || c == 0)).collect()
274}