rusty_pdf_core 0.2.0

Pure-Rust PDF reader core: objects, classic and stream cross-reference tables, object streams, incremental updates, broken-xref repair, RC4 and AES-128/256 decryption, stream filters, page tree, content streams, editing and save. Hostile input errors or stays bounded. No C, no unsafe.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! The PDF object model: the eight basic types, plus streams and references.

use crate::error::{Error, Result};
use std::collections::BTreeMap;
use std::fmt;
use std::ops::Range;
use std::sync::Arc;

/// An indirect object's identity: object number and generation.
pub type ObjectId = (u32, u16);

/// How a string was (or should be) written. It does not change the bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StringFormat {
    /// `(literal)`
    #[default]
    Literal,
    /// `<hex>`
    Hex,
}

/// A PDF object.
#[derive(Clone, PartialEq)]
pub enum Object {
    /// `null`, and what a reference to a missing object resolves to.
    Null,
    /// `true` or `false`.
    Boolean(bool),
    /// An integer.
    Integer(i64),
    /// A real number.
    Real(f64),
    /// A name, without the leading `/`, with `#xx` escapes decoded.
    Name(Vec<u8>),
    /// A string's bytes, after unescaping (and after decryption).
    String(Vec<u8>, StringFormat),
    /// An array.
    Array(Vec<Object>),
    /// A dictionary.
    Dictionary(Dictionary),
    /// A stream: a dictionary and bytes.
    Stream(Stream),
    /// A reference to an indirect object.
    Reference(ObjectId),
}

/// The shared `null` that missing objects resolve to.
pub(crate) static NULL: Object = Object::Null;

fn type_error<T>(expected: &'static str, found: &Object) -> Result<T> {
    Err(Error::Type { expected, found: found.type_name() })
}

impl Object {
    /// A literal string object.
    pub fn string(bytes: impl Into<Vec<u8>>) -> Self {
        Self::String(bytes.into(), StringFormat::Literal)
    }

    /// A name object.
    pub fn name(bytes: impl Into<Vec<u8>>) -> Self {
        Self::Name(bytes.into())
    }

    /// The type's name, for error messages.
    #[must_use]
    pub const fn type_name(&self) -> &'static str {
        match self {
            Self::Null => "null",
            Self::Boolean(_) => "boolean",
            Self::Integer(_) => "integer",
            Self::Real(_) => "real",
            Self::Name(_) => "name",
            Self::String(..) => "string",
            Self::Array(_) => "array",
            Self::Dictionary(_) => "dictionary",
            Self::Stream(_) => "stream",
            Self::Reference(_) => "reference",
        }
    }

    /// Whether this is `null`.
    #[must_use]
    pub const fn is_null(&self) -> bool {
        matches!(self, Self::Null)
    }

    /// The boolean value.
    pub fn as_bool(&self) -> Result<bool> {
        match self {
            Self::Boolean(b) => Ok(*b),
            o => type_error("boolean", o),
        }
    }

    /// The integer value. A real with no fractional part counts, because
    /// writers do emit `612.0` where an integer belongs.
    pub fn as_i64(&self) -> Result<i64> {
        match self {
            Self::Integer(i) => Ok(*i),
            // The range check makes the cast exact.
            #[allow(clippy::cast_possible_truncation)]
            Self::Real(r) if r.fract() == 0.0 && r.abs() < 9.0e15 => Ok(*r as i64),
            o => type_error("integer", o),
        }
    }

    /// The numeric value of an integer or a real.
    pub fn as_f64(&self) -> Result<f64> {
        match self {
            // Precision beyond 2^53 is irrelevant to any PDF quantity.
            #[allow(clippy::cast_precision_loss)]
            Self::Integer(i) => Ok(*i as f64),
            Self::Real(r) => Ok(*r),
            o => type_error("number", o),
        }
    }

    /// The name's bytes.
    pub fn as_name(&self) -> Result<&[u8]> {
        match self {
            Self::Name(n) => Ok(n),
            o => type_error("name", o),
        }
    }

    /// The string's bytes.
    pub fn as_str(&self) -> Result<&[u8]> {
        match self {
            Self::String(s, _) => Ok(s),
            o => type_error("string", o),
        }
    }

    /// The array's items.
    pub fn as_array(&self) -> Result<&[Object]> {
        match self {
            Self::Array(a) => Ok(a),
            o => type_error("array", o),
        }
    }

    /// The array, mutably.
    pub fn as_array_mut(&mut self) -> Result<&mut Vec<Object>> {
        match self {
            Self::Array(a) => Ok(a),
            o => type_error("array", o),
        }
    }

    /// The dictionary. A stream answers with its dictionary.
    pub fn as_dict(&self) -> Result<&Dictionary> {
        match self {
            Self::Dictionary(d) => Ok(d),
            Self::Stream(s) => Ok(&s.dict),
            o => type_error("dictionary", o),
        }
    }

    /// The dictionary, mutably. A stream answers with its dictionary.
    pub fn as_dict_mut(&mut self) -> Result<&mut Dictionary> {
        match self {
            Self::Dictionary(d) => Ok(d),
            Self::Stream(s) => Ok(&mut s.dict),
            o => type_error("dictionary", o),
        }
    }

    /// The stream.
    pub fn as_stream(&self) -> Result<&Stream> {
        match self {
            Self::Stream(s) => Ok(s),
            o => type_error("stream", o),
        }
    }

    /// The stream, mutably.
    pub fn as_stream_mut(&mut self) -> Result<&mut Stream> {
        match self {
            Self::Stream(s) => Ok(s),
            o => type_error("stream", o),
        }
    }

    /// The reference's target.
    pub fn as_reference(&self) -> Result<ObjectId> {
        match self {
            Self::Reference(id) => Ok(*id),
            o => type_error("reference", o),
        }
    }
}

impl fmt::Debug for Object {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Null => f.write_str("null"),
            Self::Boolean(b) => write!(f, "{b}"),
            Self::Integer(i) => write!(f, "{i}"),
            Self::Real(r) => write!(f, "{r}"),
            Self::Name(n) => write!(f, "/{}", String::from_utf8_lossy(n)),
            Self::String(s, _) => write!(f, "({})", String::from_utf8_lossy(s)),
            Self::Array(a) => f.debug_list().entries(a).finish(),
            Self::Dictionary(d) => d.fmt(f),
            Self::Stream(s) => write!(f, "{:?} stream[{} bytes]", s.dict, s.raw().len()),
            Self::Reference((n, g)) => write!(f, "{n} {g} R"),
        }
    }
}

impl From<bool> for Object {
    fn from(v: bool) -> Self {
        Self::Boolean(v)
    }
}
impl From<i64> for Object {
    fn from(v: i64) -> Self {
        Self::Integer(v)
    }
}
impl From<i32> for Object {
    fn from(v: i32) -> Self {
        Self::Integer(i64::from(v))
    }
}
impl From<u32> for Object {
    fn from(v: u32) -> Self {
        Self::Integer(i64::from(v))
    }
}
impl From<usize> for Object {
    fn from(v: usize) -> Self {
        Self::Integer(i64::try_from(v).unwrap_or(i64::MAX))
    }
}
impl From<f64> for Object {
    fn from(v: f64) -> Self {
        Self::Real(v)
    }
}
impl From<f32> for Object {
    fn from(v: f32) -> Self {
        Self::Real(f64::from(v))
    }
}
/// A `&str` becomes a **name**, which is what dictionary values written by
/// hand almost always are (`"Type" => "Page"`). Use [`Object::string`] for a
/// string.
impl From<&str> for Object {
    fn from(v: &str) -> Self {
        Self::Name(v.as_bytes().to_vec())
    }
}
impl From<Vec<Object>> for Object {
    fn from(v: Vec<Object>) -> Self {
        Self::Array(v)
    }
}
impl From<Dictionary> for Object {
    fn from(v: Dictionary) -> Self {
        Self::Dictionary(v)
    }
}
impl From<Stream> for Object {
    fn from(v: Stream) -> Self {
        Self::Stream(v)
    }
}
impl From<ObjectId> for Object {
    fn from(v: ObjectId) -> Self {
        Self::Reference(v)
    }
}

/// A dictionary: names to objects.
///
/// Keys are kept sorted, so lookups stay logarithmic on the huge dictionaries
/// hostile files contain and written output is deterministic. When a file
/// repeats a key, the last value wins, as in other readers.
#[derive(Clone, PartialEq, Default)]
pub struct Dictionary(BTreeMap<Vec<u8>, Object>);

impl Dictionary {
    /// An empty dictionary.
    #[must_use]
    pub const fn new() -> Self {
        Self(BTreeMap::new())
    }

    /// The value under `key`, exactly as stored (a reference is not followed;
    /// see [`Document::resolve`](crate::Document::resolve)).
    #[must_use]
    pub fn get(&self, key: &[u8]) -> Option<&Object> {
        self.0.get(key)
    }

    /// The value under `key`, mutably.
    pub fn get_mut(&mut self, key: &[u8]) -> Option<&mut Object> {
        self.0.get_mut(key)
    }

    /// The value under `key`, or [`Error::MissingKey`].
    pub fn require(&self, key: &[u8]) -> Result<&Object> {
        self.0
            .get(key)
            .ok_or_else(|| Error::MissingKey(String::from_utf8_lossy(key).into_owned()))
    }

    /// Whether `key` is present.
    #[must_use]
    pub fn has(&self, key: &[u8]) -> bool {
        self.0.contains_key(key)
    }

    /// Set `key` to `value`, replacing any earlier value.
    pub fn set(&mut self, key: impl Into<Vec<u8>>, value: impl Into<Object>) {
        self.0.insert(key.into(), value.into());
    }

    /// Remove `key`, returning its value.
    pub fn remove(&mut self, key: &[u8]) -> Option<Object> {
        self.0.remove(key)
    }

    /// Number of entries.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Whether there are no entries.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Entries in key order.
    pub fn iter(&self) -> impl Iterator<Item = (&[u8], &Object)> {
        self.0.iter().map(|(k, v)| (k.as_slice(), v))
    }

    /// Entries in key order, values mutable.
    pub fn iter_mut(&mut self) -> impl Iterator<Item = (&[u8], &mut Object)> {
        self.0.iter_mut().map(|(k, v)| (k.as_slice(), v))
    }

    /// The name under `key`, if it is a direct name.
    #[must_use]
    pub fn get_name(&self, key: &[u8]) -> Option<&[u8]> {
        self.get(key).and_then(|o| o.as_name().ok())
    }

    /// The integer under `key`, if it is a direct integer.
    #[must_use]
    pub fn get_i64(&self, key: &[u8]) -> Option<i64> {
        self.get(key).and_then(|o| o.as_i64().ok())
    }

    /// The number under `key`, if it is a direct number.
    #[must_use]
    pub fn get_f64(&self, key: &[u8]) -> Option<f64> {
        self.get(key).and_then(|o| o.as_f64().ok())
    }

    /// The boolean under `key`, if it is a direct boolean.
    #[must_use]
    pub fn get_bool(&self, key: &[u8]) -> Option<bool> {
        self.get(key).and_then(|o| o.as_bool().ok())
    }

    /// Whether `/Type` is the name `ty`.
    #[must_use]
    pub fn is_type(&self, ty: &[u8]) -> bool {
        self.get_name(b"Type") == Some(ty)
    }
}

impl fmt::Debug for Dictionary {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut m = f.debug_map();
        for (k, v) in &self.0 {
            m.entry(&format_args!("/{}", String::from_utf8_lossy(k)), v);
        }
        m.finish()
    }
}

impl<K: Into<Vec<u8>>, V: Into<Object>> FromIterator<(K, V)> for Dictionary {
    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
        let mut d = Self::new();
        for (k, v) in iter {
            d.set(k, v);
        }
        d
    }
}

/// Build a [`Dictionary`] from `"Key" => value` pairs. A `&str` value becomes
/// a name.
///
/// ```
/// use rusty_pdf_core::{dictionary, Object};
/// let d = dictionary! { "Type" => "Page", "Rotate" => 90 };
/// assert_eq!(d.get(b"Type"), Some(&Object::name("Page")));
/// ```
#[macro_export]
macro_rules! dictionary {
    () => { $crate::Dictionary::new() };
    ($( $key:expr => $value:expr ),+ $(,)?) => {{
        let mut d = $crate::Dictionary::new();
        $( d.set($key, $value); )+
        d
    }};
}

/// Bytes that are either a window onto the loaded file or owned.
///
/// A stream parsed from a file does not copy its data; it shares the file
/// buffer.
#[derive(Clone)]
pub(crate) struct Blob {
    buf: Arc<[u8]>,
    range: Range<usize>,
}

impl Blob {
    pub(crate) fn owned(data: Vec<u8>) -> Self {
        let range = 0..data.len();
        Self { buf: data.into(), range }
    }

    /// A window onto `buf`. An out-of-range window is clamped to empty.
    pub(crate) fn window(buf: &Arc<[u8]>, range: Range<usize>) -> Self {
        let range = if range.start <= range.end && range.end <= buf.len() {
            range
        } else {
            0..0
        };
        Self { buf: Arc::clone(buf), range }
    }

    pub(crate) fn as_slice(&self) -> &[u8] {
        self.buf.get(self.range.clone()).unwrap_or(&[])
    }
}

/// A stream: a dictionary and the bytes it describes.
///
/// The bytes are **as stored**: still encoded by the stream's `/Filter`
/// chain, but already decrypted when the document is encrypted. Decode them
/// with [`Document::decode_stream`](crate::Document::decode_stream).
#[derive(Clone)]
pub struct Stream {
    /// The stream dictionary.
    pub dict: Dictionary,
    data: Blob,
}

impl Stream {
    /// A stream holding `data` exactly as given; `/Length` is set to match.
    /// The caller describes any encoding in `dict` (`/Filter`).
    #[must_use]
    pub fn new(mut dict: Dictionary, data: Vec<u8>) -> Self {
        dict.set("Length", data.len());
        Self { dict, data: Blob::owned(data) }
    }

    pub(crate) const fn from_blob(dict: Dictionary, data: Blob) -> Self {
        Self { dict, data }
    }

    /// The stored bytes (encoded, decrypted).
    #[must_use]
    pub fn raw(&self) -> &[u8] {
        self.data.as_slice()
    }

    /// Replace the stored bytes and update `/Length`. `/Filter` and
    /// `/DecodeParms` are left alone: the caller says what the bytes are.
    pub fn set_raw(&mut self, data: Vec<u8>) {
        self.dict.set("Length", data.len());
        self.data = Blob::owned(data);
    }

    /// Replace the content with `plain`, stored unencoded: `/Filter` and
    /// `/DecodeParms` are removed.
    pub fn set_plain(&mut self, plain: Vec<u8>) {
        self.dict.remove(b"Filter");
        self.dict.remove(b"DecodeParms");
        self.set_raw(plain);
    }

    /// Replace the content with `plain`, stored Flate-compressed.
    pub fn set_flate(&mut self, plain: &[u8]) {
        self.dict.remove(b"DecodeParms");
        self.dict.set("Filter", "FlateDecode");
        self.set_raw(crate::filters::flate_encode(plain));
    }

    /// The filter names, outermost first. Only direct names are seen; use
    /// [`Document::decode_stream`](crate::Document::decode_stream) for a
    /// stream whose `/Filter` is an indirect reference.
    #[must_use]
    pub fn filters(&self) -> Vec<&[u8]> {
        match self.dict.get(b"Filter") {
            Some(Object::Name(n)) => vec![n.as_slice()],
            Some(Object::Array(a)) => a.iter().filter_map(|o| o.as_name().ok()).collect(),
            _ => Vec::new(),
        }
    }
}

impl PartialEq for Stream {
    fn eq(&self, other: &Self) -> bool {
        self.dict == other.dict && self.raw() == other.raw()
    }
}

impl fmt::Debug for Stream {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?} stream[{} bytes]", self.dict, self.raw().len())
    }
}